afb-hook & afb-trace: Fix usage of readlink
[src/app-framework-binder.git] / src / afb-trace.c
1 /*
2  * Copyright (C) 2016, 2017, 2018 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <assert.h>
21 #include <string.h>
22 #include <stdarg.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <limits.h>
26 #include <unistd.h>
27 #include <pthread.h>
28
29 #include <json-c/json.h>
30
31 #define AFB_BINDING_VERSION 3
32 #include <afb/afb-binding.h>
33
34 #include "afb-hook.h"
35 #include "afb-cred.h"
36 #include "afb-session.h"
37 #include "afb-xreq.h"
38 #include "afb-export.h"
39 #include "afb-evt.h"
40 #include "afb-session.h"
41 #include "afb-trace.h"
42
43 #include "wrap-json.h"
44 #include "verbose.h"
45
46 /*******************************************************************************/
47 /*****  default names                                                      *****/
48 /*******************************************************************************/
49
50 #if !defined(DEFAULT_EVENT_NAME)
51 #  define DEFAULT_EVENT_NAME "trace"
52 #endif
53 #if !defined(DEFAULT_TAG_NAME)
54 #  define DEFAULT_TAG_NAME "trace"
55 #endif
56
57 /*******************************************************************************/
58 /*****  types                                                              *****/
59 /*******************************************************************************/
60
61 /* structure for searching flags by names */
62 struct flag
63 {
64         const char *name;       /** the name */
65         int value;              /** the value */
66 };
67
68 /* struct for tags */
69 struct tag {
70         struct tag *next;       /* link to the next */
71         char tag[1];            /* name of the tag */
72 };
73
74 /* struct for events */
75 struct event {
76         struct event *next;             /* link to the next event */
77         struct afb_evtid *evtid;        /* the event */
78 };
79
80 /* struct for sessions */
81 struct cookie {
82         struct afb_session *session;    /* the session */
83         struct afb_trace *trace;        /* the tracer */
84 };
85
86 /* struct for recording hooks */
87 struct hook {
88         struct hook *next;              /* link to next hook */
89         void *handler;                  /* the handler of the hook */
90         struct event *event;            /* the associated event */
91         struct tag *tag;                /* the associated tag */
92         struct afb_session *session;    /* the associated session */
93 };
94
95 /* types of hooks */
96 enum trace_type
97 {
98         Trace_Type_Xreq,                /* xreq hooks */
99         Trace_Type_Api,                 /* api hooks */
100         Trace_Type_Evt,                 /* evt hooks */
101         Trace_Type_Session,             /* session hooks */
102         Trace_Type_Global,              /* global hooks */
103 #if !defined(REMOVE_LEGACY_TRACE)
104         Trace_Legacy_Type_Ditf,         /* export hooks */
105         Trace_Legacy_Type_Svc,          /* export hooks */
106 #endif
107         Trace_Type_Count,               /* count of types of hooks */
108 };
109
110 /* client data */
111 struct afb_trace
112 {
113         int refcount;                           /* reference count */
114         pthread_mutex_t mutex;                  /* concurrency management */
115         const char *apiname;                    /* api name for events */
116         struct afb_session *bound;              /* bound to session */
117         struct event *events;                   /* list of events */
118         struct tag *tags;                       /* list of tags */
119         struct hook *hooks[Trace_Type_Count];   /* hooks */
120 };
121
122 /*******************************************************************************/
123 /*****  utility functions                                                  *****/
124 /*******************************************************************************/
125
126 static void ctxt_error(char **errors, const char *format, ...)
127 {
128         int len;
129         char *errs;
130         size_t sz;
131         char buffer[1024];
132         va_list ap;
133
134         va_start(ap, format);
135         len = vsnprintf(buffer, sizeof buffer, format, ap);
136         va_end(ap);
137         if (len > (int)(sizeof buffer - 2))
138                 len = (int)(sizeof buffer - 2);
139         buffer[len++] = '\n';
140         buffer[len++] = 0;
141
142         errs = *errors;
143         sz = errs ? strlen(errs) : 0;
144         errs = realloc(errs, sz + (size_t)len);
145         if (errs) {
146                 memcpy(errs + sz, buffer, len);
147                 *errors = errs;
148         }
149 }
150
151 /* get the value of the flag of 'name' in the array 'flags' of 'count elements */
152 static int get_flag(const char *name, struct flag flags[], int count)
153 {
154         /* dichotomic search */
155         int lower = 0, upper = count;
156         while (lower < upper) {
157                 int mid = (lower + upper) >> 1;
158                 int cmp = strcmp(name, flags[mid].name);
159                 if (!cmp)
160                         return flags[mid].value;
161                 if (cmp < 0)
162                         upper = mid;
163                 else
164                         lower = mid + 1;
165         }
166         return 0;
167 }
168
169 /* timestamp */
170 static struct json_object *timestamp(const struct afb_hookid *hookid)
171 {
172         char ts[50];
173
174         snprintf(ts, sizeof ts, "%llu.%06lu",
175                         (long long unsigned)hookid->time.tv_sec,
176                         (long unsigned)((hookid->time.tv_nsec + 500) / 1000));
177
178         return json_object_new_double_s(0.0f, ts); /* the real value isn't used */
179 #if 0
180         return json_object_new_string(ts);
181         return json_object_new_double_s(0f, ts); /* the real value isn't used */
182 #endif
183 }
184
185 /* verbosity level name or NULL */
186 static const char *verbosity_level_name(int level)
187 {
188         static const char *names[] = {
189                 "error",
190                 "warning",
191                 "notice",
192                 "info",
193                 "debug"
194         };
195
196         return level >= Log_Level_Error && level <= Log_Level_Debug ? names[level - Log_Level_Error] : NULL;
197 }
198
199 /* generic hook */
200 static void emit(void *closure, const struct afb_hookid *hookid, const char *type, const char *fmt1, const char *fmt2, va_list ap2, ...)
201 {
202         struct hook *hook = closure;
203         struct json_object *data, *data1, *data2;
204         va_list ap1;
205
206         data1 = data2 = data = NULL;
207         va_start(ap1, ap2);
208         wrap_json_vpack(&data1, fmt1, ap1);
209         va_end(ap1);
210         if (fmt2)
211                 wrap_json_vpack(&data2, fmt2, ap2);
212
213         wrap_json_pack(&data, "{so ss ss si so so*}",
214                                         "time", timestamp(hookid),
215                                         "tag", hook->tag->tag,
216                                         "type", type,
217                                         "id", (int)(hookid->id & INT_MAX),
218                                         type, data1,
219                                         "data", data2);
220
221         afb_evt_evtid_push(hook->event->evtid, data);
222 }
223
224 /*******************************************************************************/
225 /*****  trace the requests                                                 *****/
226 /*******************************************************************************/
227
228 static struct flag xreq_flags[] = { /* must be sorted by names */
229                 { "addref",             afb_hook_flag_req_addref },
230                 { "all",                afb_hook_flags_req_all },
231                 { "args",               afb_hook_flags_req_args },
232                 { "begin",              afb_hook_flag_req_begin },
233                 { "common",             afb_hook_flags_req_common },
234                 { "context",            afb_hook_flags_req_context },
235                 { "context_get",        afb_hook_flag_req_legacy_context_get },
236                 { "context_make",       afb_hook_flag_req_context_make },
237                 { "context_set",        afb_hook_flag_req_legacy_context_set },
238                 { "end",                afb_hook_flag_req_end },
239                 { "event",              afb_hook_flags_req_event },
240                 { "extra",              afb_hook_flags_req_extra },
241                 { "get",                afb_hook_flag_req_get },
242                 { "get_application_id", afb_hook_flag_req_get_application_id },
243                 { "get_client_info",    afb_hook_flag_req_get_client_info },
244                 { "get_uid",            afb_hook_flag_req_get_uid },
245                 { "has_permission",     afb_hook_flag_req_has_permission },
246                 { "json",               afb_hook_flag_req_json },
247                 { "life",               afb_hook_flags_req_life },
248                 { "ref",                afb_hook_flags_req_ref },
249                 { "reply",              afb_hook_flag_req_reply },
250                 { "security",           afb_hook_flags_req_security },
251                 { "session",            afb_hook_flags_req_session },
252                 { "session_close",      afb_hook_flag_req_session_close },
253                 { "session_set_LOA",    afb_hook_flag_req_session_set_LOA },
254                 { "store",              afb_hook_flag_req_legacy_store },
255                 { "stores",             afb_hook_flags_req_stores },
256                 { "subcall",            afb_hook_flag_req_subcall },
257                 { "subcall_result",     afb_hook_flag_req_subcall_result },
258                 { "subcalls",           afb_hook_flags_req_subcalls },
259                 { "subcallsync",        afb_hook_flag_req_subcallsync },
260                 { "subcallsync_result", afb_hook_flag_req_subcallsync_result },
261                 { "subscribe",          afb_hook_flag_req_subscribe },
262                 { "unref",              afb_hook_flag_req_unref },
263                 { "unstore",            afb_hook_flag_req_legacy_unstore },
264                 { "unsubscribe",        afb_hook_flag_req_unsubscribe },
265                 { "vverbose",           afb_hook_flag_req_vverbose },
266 };
267
268 /* get the xreq value for flag of 'name' */
269 static int get_xreq_flag(const char *name)
270 {
271         return get_flag(name, xreq_flags, (int)(sizeof xreq_flags / sizeof *xreq_flags));
272 }
273
274 static void hook_xreq(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *action, const char *format, ...)
275 {
276         struct json_object *cred = NULL;
277         const char *session = NULL;
278         va_list ap;
279
280         if (xreq->context.session)
281                 session = afb_session_uuid(xreq->context.session);
282
283         if (xreq->cred)
284                 wrap_json_pack(&cred, "{si ss si si ss* ss*}",
285                                                 "uid", (int)xreq->cred->uid,
286                                                 "user", xreq->cred->user,
287                                                 "gid", (int)xreq->cred->gid,
288                                                 "pid", (int)xreq->cred->pid,
289                                                 "label", xreq->cred->label,
290                                                 "id", xreq->cred->id
291                                         );
292         va_start(ap, format);
293         emit(closure, hookid, "request", "{si ss ss ss so* ss*}", format, ap,
294                                         "index", xreq->hookindex,
295                                         "api", xreq->request.called_api,
296                                         "verb", xreq->request.called_verb,
297                                         "action", action,
298                                         "credentials", cred,
299                                         "session", session);
300         va_end(ap);
301 }
302
303 static void hook_xreq_begin(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
304 {
305         hook_xreq(closure, hookid, xreq, "begin", "{sO?}",
306                                                 "json", afb_xreq_unhooked_json((struct afb_xreq*)xreq));
307 }
308
309 static void hook_xreq_end(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
310 {
311         hook_xreq(closure, hookid, xreq, "end", NULL);
312 }
313
314 static void hook_xreq_json(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct json_object *obj)
315 {
316         hook_xreq(closure, hookid, xreq, "json", "{sO?}",
317                                                 "result", obj);
318 }
319
320 static void hook_xreq_get(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *name, struct afb_arg arg)
321 {
322         hook_xreq(closure, hookid, xreq, "get", "{ss? ss? ss? ss?}",
323                                                 "query", name,
324                                                 "name", arg.name,
325                                                 "value", arg.value,
326                                                 "path", arg.path);
327 }
328
329 static void hook_xreq_reply(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct json_object *obj, const char *error, const char *info)
330 {
331         hook_xreq(closure, hookid, xreq, "reply", "{sO? ss? ss?}",
332                                                 "result", obj,
333                                                 "error", error,
334                                                 "info", info);
335 }
336
337 static void hook_xreq_context_get(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, void *value)
338 {
339         hook_xreq(closure, hookid, xreq, "context_get", NULL);
340 }
341
342 static void hook_xreq_context_set(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, void *value, void (*free_value)(void*))
343 {
344         hook_xreq(closure, hookid, xreq, "context_set", NULL);
345 }
346
347 static void hook_xreq_addref(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
348 {
349         hook_xreq(closure, hookid, xreq, "addref", NULL);
350 }
351
352 static void hook_xreq_unref(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
353 {
354         hook_xreq(closure, hookid, xreq, "unref", NULL);
355 }
356
357 static void hook_xreq_session_close(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
358 {
359         hook_xreq(closure, hookid, xreq, "session_close", NULL);
360 }
361
362 static void hook_xreq_session_set_LOA(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, unsigned level, int result)
363 {
364         hook_xreq(closure, hookid, xreq, "session_set_LOA", "{si si}",
365                                         "level", level,
366                                         "result", result);
367 }
368
369 static void hook_xreq_subscribe(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct afb_event_x2 *event, int result)
370 {
371         hook_xreq(closure, hookid, xreq, "subscribe", "{s{ss si} si}",
372                                         "event",
373                                                 "name", afb_evt_event_x2_fullname(event),
374                                                 "id", afb_evt_event_x2_id(event),
375                                         "result", result);
376 }
377
378 static void hook_xreq_unsubscribe(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct afb_event_x2 *event, int result)
379 {
380         hook_xreq(closure, hookid, xreq, "unsubscribe", "{s{ss? si} si}",
381                                         "event",
382                                                 "name", afb_evt_event_x2_fullname(event),
383                                                 "id", afb_evt_event_x2_id(event),
384                                         "result", result);
385 }
386
387 static void hook_xreq_subcall(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args)
388 {
389         hook_xreq(closure, hookid, xreq, "subcall", "{ss? ss? sO?}",
390                                         "api", api,
391                                         "verb", verb,
392                                         "args", args);
393 }
394
395 static void hook_xreq_subcall_result(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
396 {
397         hook_xreq(closure, hookid, xreq, "subcall_result", "{sO? ss? ss?}",
398                                         "object", object,
399                                         "error", error,
400                                         "info", info);
401 }
402
403 static void hook_xreq_subcallsync(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args)
404 {
405         hook_xreq(closure, hookid, xreq, "subcallsync", "{ss? ss? sO?}",
406                                         "api", api,
407                                         "verb", verb,
408                                         "args", args);
409 }
410
411 static void hook_xreq_subcallsync_result(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, int status, struct json_object *object, const char *error, const char *info)
412 {
413         hook_xreq(closure, hookid, xreq, "subcallsync_result",  "{si sO? ss? ss?}",
414                                         "status", status,
415                                         "object", object,
416                                         "error", error,
417                                         "info", info);
418 }
419
420 static void hook_xreq_vverbose(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, int level, const char *file, int line, const char *func, const char *fmt, va_list args)
421 {
422         struct json_object *pos;
423         int len;
424         char *msg;
425         va_list ap;
426
427         pos = NULL;
428         msg = NULL;
429
430         va_copy(ap, args);
431         len = vasprintf(&msg, fmt, ap);
432         va_end(ap);
433
434         if (file)
435                 wrap_json_pack(&pos, "{ss si ss*}", "file", file, "line", line, "function", func);
436
437         hook_xreq(closure, hookid, xreq, "vverbose", "{si ss* ss? so*}",
438                                         "level", level,
439                                         "type", verbosity_level_name(level),
440                                         len < 0 ? "format" : "message", len < 0 ? fmt : msg,
441                                         "position", pos);
442
443         free(msg);
444 }
445
446 static void hook_xreq_store(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct afb_stored_req *sreq)
447 {
448         hook_xreq(closure, hookid, xreq, "store", NULL);
449 }
450
451 static void hook_xreq_unstore(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
452 {
453         hook_xreq(closure, hookid, xreq, "unstore", NULL);
454 }
455
456 static void hook_xreq_has_permission(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *permission, int result)
457 {
458         hook_xreq(closure, hookid, xreq, "has_permission", "{ss sb}",
459                                         "permission", permission,
460                                         "result", result);
461 }
462
463 static void hook_xreq_get_application_id(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, char *result)
464 {
465         hook_xreq(closure, hookid, xreq, "get_application_id", "{ss?}",
466                                         "result", result);
467 }
468
469 static void hook_xreq_context_make(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, int replace, void *(*create_value)(void*), void (*free_value)(void*), void *create_closure, void *result)
470 {
471         char pc[50], pf[50], pv[50], pr[50];
472         snprintf(pc, sizeof pc, "%p", create_value);
473         snprintf(pf, sizeof pf, "%p", free_value);
474         snprintf(pv, sizeof pv, "%p", create_closure);
475         snprintf(pr, sizeof pr, "%p", result);
476         hook_xreq(closure, hookid, xreq, "context_make", "{sb ss ss ss ss}",
477                                         "replace", replace,
478                                         "create", pc,
479                                         "free", pf,
480                                         "closure", pv,
481                                         "result", pr);
482 }
483
484 static void hook_xreq_get_uid(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, int result)
485 {
486         hook_xreq(closure, hookid, xreq, "get_uid", "{si}",
487                                         "result", result);
488 }
489
490 static void hook_xreq_get_client_info(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct json_object *result)
491 {
492         hook_xreq(closure, hookid, xreq, "get_client_info", "{sO}",
493                                         "result", result);
494 }
495
496 static struct afb_hook_xreq_itf hook_xreq_itf = {
497         .hook_xreq_begin = hook_xreq_begin,
498         .hook_xreq_end = hook_xreq_end,
499         .hook_xreq_json = hook_xreq_json,
500         .hook_xreq_get = hook_xreq_get,
501         .hook_xreq_reply = hook_xreq_reply,
502         .hook_xreq_legacy_context_get = hook_xreq_context_get,
503         .hook_xreq_legacy_context_set = hook_xreq_context_set,
504         .hook_xreq_addref = hook_xreq_addref,
505         .hook_xreq_unref = hook_xreq_unref,
506         .hook_xreq_session_close = hook_xreq_session_close,
507         .hook_xreq_session_set_LOA = hook_xreq_session_set_LOA,
508         .hook_xreq_subscribe = hook_xreq_subscribe,
509         .hook_xreq_unsubscribe = hook_xreq_unsubscribe,
510         .hook_xreq_subcall = hook_xreq_subcall,
511         .hook_xreq_subcall_result = hook_xreq_subcall_result,
512         .hook_xreq_subcallsync = hook_xreq_subcallsync,
513         .hook_xreq_subcallsync_result = hook_xreq_subcallsync_result,
514         .hook_xreq_vverbose = hook_xreq_vverbose,
515         .hook_xreq_legacy_store = hook_xreq_store,
516         .hook_xreq_legacy_unstore = hook_xreq_unstore,
517         .hook_xreq_has_permission = hook_xreq_has_permission,
518         .hook_xreq_get_application_id = hook_xreq_get_application_id,
519         .hook_xreq_context_make = hook_xreq_context_make,
520         .hook_xreq_get_uid = hook_xreq_get_uid,
521         .hook_xreq_get_client_info = hook_xreq_get_client_info,
522 };
523
524 /*******************************************************************************/
525 /*****  trace the api interface                                            *****/
526 /*******************************************************************************/
527
528 #if !defined(REMOVE_LEGACY_TRACE)
529 static struct flag legacy_ditf_flags[] = { /* must be sorted by names */
530                 { "all",                        afb_hook_flags_api_ditf_all },
531                 { "common",                     afb_hook_flags_api_ditf_common },
532                 { "event_broadcast_after",      afb_hook_flag_api_event_broadcast },
533                 { "event_broadcast_before",     afb_hook_flag_api_event_broadcast },
534                 { "event_make",                 afb_hook_flag_api_event_make },
535                 { "extra",                      afb_hook_flags_api_ditf_extra },
536                 { "get_event_loop",             afb_hook_flag_api_get_event_loop },
537                 { "get_system_bus",             afb_hook_flag_api_get_system_bus },
538                 { "get_user_bus",               afb_hook_flag_api_get_user_bus },
539                 { "queue_job",                  afb_hook_flag_api_queue_job },
540                 { "require_api",                afb_hook_flag_api_require_api },
541                 { "require_api_result",         afb_hook_flag_api_require_api },
542                 { "rootdir_get_fd",             afb_hook_flag_api_rootdir_get_fd },
543                 { "rootdir_open_locale",        afb_hook_flag_api_rootdir_open_locale },
544                 { "unstore_req",                afb_hook_flag_api_legacy_unstore_req },
545                 { "vverbose",                   afb_hook_flag_api_vverbose },
546 };
547
548 static struct flag legacy_svc_flags[] = { /* must be sorted by names */
549                 { "all",                afb_hook_flags_api_svc_all },
550                 { "call",               afb_hook_flag_api_call },
551                 { "call_result",        afb_hook_flag_api_call },
552                 { "callsync",           afb_hook_flag_api_callsync },
553                 { "callsync_result",    afb_hook_flag_api_callsync },
554                 { "on_event_after",     afb_hook_flag_api_on_event },
555                 { "on_event_before",    afb_hook_flag_api_on_event },
556                 { "start_after",        afb_hook_flag_api_start },
557                 { "start_before",       afb_hook_flag_api_start },
558 };
559
560 /* get the export value for flag of 'name' */
561 static int get_legacy_ditf_flag(const char *name)
562 {
563         return get_flag(name, legacy_ditf_flags, (int)(sizeof legacy_ditf_flags / sizeof *legacy_ditf_flags));
564 }
565
566 /* get the export value for flag of 'name' */
567 static int get_legacy_svc_flag(const char *name)
568 {
569         return get_flag(name, legacy_svc_flags, (int)(sizeof legacy_svc_flags / sizeof *legacy_svc_flags));
570 }
571 #endif
572
573 static struct flag api_flags[] = { /* must be sorted by names */
574                 { "add_alias",          afb_hook_flag_api_add_alias },
575                 { "all",                afb_hook_flags_api_all },
576                 { "api_add_verb",       afb_hook_flag_api_api_add_verb },
577                 { "api",                afb_hook_flags_api_api },
578                 { "api_del_verb",       afb_hook_flag_api_api_del_verb },
579                 { "api_seal",           afb_hook_flag_api_api_seal },
580                 { "api_set_on_event",   afb_hook_flag_api_api_set_on_event },
581                 { "api_set_on_init",    afb_hook_flag_api_api_set_on_init },
582                 { "api_set_verbs",      afb_hook_flag_api_api_set_verbs },
583                 { "call",               afb_hook_flag_api_call },
584                 { "callsync",           afb_hook_flag_api_callsync },
585                 { "class_provide",      afb_hook_flag_api_class_provide },
586                 { "class_require",      afb_hook_flag_api_class_require },
587                 { "common",             afb_hook_flags_api_common },
588                 { "delete_api",         afb_hook_flag_api_delete_api },
589                 { "event",              afb_hook_flags_api_event },
590                 { "event_broadcast",    afb_hook_flag_api_event_broadcast },
591                 { "event_handler_add",  afb_hook_flag_api_event_handler_add },
592                 { "event_handler_del",  afb_hook_flag_api_event_handler_del },
593                 { "event_make",         afb_hook_flag_api_event_make },
594                 { "extra",              afb_hook_flags_api_extra },
595                 { "get_event_loop",     afb_hook_flag_api_get_event_loop },
596                 { "get_system_bus",     afb_hook_flag_api_get_system_bus },
597                 { "get_user_bus",       afb_hook_flag_api_get_user_bus },
598                 { "legacy_unstore_req", afb_hook_flag_api_legacy_unstore_req },
599                 { "new_api",            afb_hook_flag_api_new_api },
600                 { "on_event",           afb_hook_flag_api_on_event },
601                 { "on_event_handler",   afb_hook_flag_api_on_event_handler },
602                 { "queue_job",          afb_hook_flag_api_queue_job },
603                 { "require_api",        afb_hook_flag_api_require_api },
604                 { "rootdir_get_fd",     afb_hook_flag_api_rootdir_get_fd },
605                 { "rootdir_open_locale",afb_hook_flag_api_rootdir_open_locale },
606                 { "start",              afb_hook_flag_api_start },
607                 { "vverbose",           afb_hook_flag_api_vverbose },
608 };
609
610 /* get the export value for flag of 'name' */
611 static int get_api_flag(const char *name)
612 {
613         return get_flag(name, api_flags, (int)(sizeof api_flags / sizeof *api_flags));
614 }
615
616 static void hook_api(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *action, const char *format, ...)
617 {
618         va_list ap;
619
620         va_start(ap, format);
621         emit(closure, hookid, "api", "{ss ss}", format, ap,
622                                         "api", afb_export_apiname(export),
623                                         "action", action);
624         va_end(ap);
625 }
626
627 static void hook_api_event_broadcast_before(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *name, struct json_object *object)
628 {
629         hook_api(closure, hookid, export, "event_broadcast_before", "{ss sO?}",
630                         "name", name, "data", object);
631 }
632
633 static void hook_api_event_broadcast_after(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *name, struct json_object *object, int result)
634 {
635         hook_api(closure, hookid, export, "event_broadcast_after", "{ss sO? si}",
636                         "name", name, "data", object, "result", result);
637 }
638
639 static void hook_api_get_event_loop(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, struct sd_event *result)
640 {
641         hook_api(closure, hookid, export, "get_event_loop", NULL);
642 }
643
644 static void hook_api_get_user_bus(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, struct sd_bus *result)
645 {
646         hook_api(closure, hookid, export, "get_user_bus", NULL);
647 }
648
649 static void hook_api_get_system_bus(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, struct sd_bus *result)
650 {
651         hook_api(closure, hookid, export, "get_system_bus", NULL);
652 }
653
654 static void hook_api_vverbose(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int level, const char *file, int line, const char *function, const char *fmt, va_list args)
655 {
656         struct json_object *pos;
657         int len;
658         char *msg;
659         va_list ap;
660
661         pos = NULL;
662         msg = NULL;
663
664         va_copy(ap, args);
665         len = vasprintf(&msg, fmt, ap);
666         va_end(ap);
667
668         if (file)
669                 wrap_json_pack(&pos, "{ss si ss*}", "file", file, "line", line, "function", function);
670
671         hook_api(closure, hookid, export, "vverbose", "{si ss* ss? so*}",
672                                         "level", level,
673                                         "type", verbosity_level_name(level),
674                                         len < 0 ? "format" : "message", len < 0 ? fmt : msg,
675                                         "position", pos);
676
677         free(msg);
678 }
679
680 static void hook_api_event_make(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *name, struct afb_event_x2 *result)
681 {
682         hook_api(closure, hookid, export, "event_make", "{ss ss si}",
683                         "name", name, "event", afb_evt_event_x2_fullname(result), "id", afb_evt_event_x2_id(result));
684 }
685
686 static void hook_api_rootdir_get_fd(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result)
687 {
688         char path[PATH_MAX], proc[100];
689         const char *key, *val;
690         ssize_t s;
691
692         if (result >= 0) {
693                 snprintf(proc, sizeof proc, "/proc/self/fd/%d", result);
694                 s = readlink(proc, path, sizeof path);
695                 path[s < 0 ? 0 : s >= sizeof path ? sizeof path - 1 : s] = 0;
696                 key = "path";
697                 val = path;
698         } else {
699                 key = "error";
700                 val = strerror(errno);
701         }
702
703         hook_api(closure, hookid, export, "rootdir_get_fd", "{ss}", key, val);
704 }
705
706 static void hook_api_rootdir_open_locale(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *filename, int flags, const char *locale, int result)
707 {
708         char path[PATH_MAX], proc[100];
709         const char *key, *val;
710         ssize_t s;
711
712         if (result >= 0) {
713                 snprintf(proc, sizeof proc, "/proc/self/fd/%d", result);
714                 s = readlink(proc, path, sizeof path);
715                 path[s < 0 ? 0 : s >= sizeof path ? sizeof path - 1 : s] = 0;
716                 key = "path";
717                 val = path;
718         } else {
719                 key = "error";
720                 val = strerror(errno);
721         }
722
723         hook_api(closure, hookid, export, "rootdir_open_locale", "{ss si ss* ss}",
724                         "file", filename,
725                         "flags", flags,
726                         "locale", locale,
727                         key, val);
728 }
729
730 static void hook_api_queue_job(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, void (*callback)(int signum, void *arg), void *argument, void *group, int timeout, int result)
731 {
732         hook_api(closure, hookid, export, "queue_job", "{ss}", "result", result);
733 }
734
735 static void hook_api_unstore_req(void * closure, const struct afb_hookid *hookid, const struct afb_export *export, struct afb_stored_req *sreq)
736 {
737         hook_api(closure, hookid, export, "unstore_req", NULL);
738 }
739
740 static void hook_api_require_api(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *name, int initialized)
741 {
742         hook_api(closure, hookid, export, "require_api", "{ss sb}", "name", name, "initialized", initialized);
743 }
744
745 static void hook_api_require_api_result(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *name, int initialized, int result)
746 {
747         hook_api(closure, hookid, export, "require_api_result", "{ss sb si}", "name", name, "initialized", initialized, "result", result);
748 }
749
750 static void hook_api_add_alias_cb(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *api, const char *alias, int result)
751 {
752         hook_api(closure, hookid, export, "add_alias", "{si ss? ss}", "status", result, "api", api, "alias", alias);
753 }
754
755 static void hook_api_start_before(void *closure, const struct afb_hookid *hookid, const struct afb_export *export)
756 {
757         hook_api(closure, hookid, export, "start_before", NULL);
758 }
759
760 static void hook_api_start_after(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int status)
761 {
762         hook_api(closure, hookid, export, "start_after", "{si}", "result", status);
763 }
764
765 static void hook_api_on_event_before(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *event, int evtid, struct json_object *object)
766 {
767         hook_api(closure, hookid, export, "on_event_before", "{ss si sO*}",
768                         "event", event, "id", evtid, "data", object);
769 }
770
771 static void hook_api_on_event_after(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *event, int evtid, struct json_object *object)
772 {
773         hook_api(closure, hookid, export, "on_event_after", "{ss si sO?}",
774                         "event", event, "id", evtid, "data", object);
775 }
776
777 static void hook_api_call(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *api, const char *verb, struct json_object *args)
778 {
779         hook_api(closure, hookid, export, "call", "{ss ss sO?}",
780                         "api", api, "verb", verb, "args", args);
781 }
782
783 static void hook_api_call_result(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, struct json_object *object, const char *error, const char *info)
784 {
785         hook_api(closure, hookid, export, "call_result", "{sO? ss? ss?}",
786                         "object", object, "error", error, "info", info);
787 }
788
789 static void hook_api_callsync(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *api, const char *verb, struct json_object *args)
790 {
791         hook_api(closure, hookid, export, "callsync", "{ss ss sO?}",
792                         "api", api, "verb", verb, "args", args);
793 }
794
795 static void hook_api_callsync_result(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int status, struct json_object *object, const char *error, const char *info)
796 {
797         hook_api(closure, hookid, export, "callsync_result", "{si sO? ss? ss?}",
798                         "status", status, "object", object, "error", error, "info", info);
799 }
800
801 static void hook_api_new_api_before(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, const char *api, const char *info, int noconcurrency)
802 {
803         hook_api(closure, hookid, export, "new_api.before", "{ss ss? sb}",
804                         "api", api, "info", info, "noconcurrency", noconcurrency);
805 }
806
807 static void hook_api_new_api_after(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const char *api)
808 {
809         hook_api(closure, hookid, export, "new_api.after", "{si ss}",
810                                                 "status", result, "api", api);
811 }
812
813 static void hook_api_api_set_verbs_v2(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const struct afb_verb_v2 *verbs)
814 {
815         hook_api(closure, hookid, export, "set_verbs_v2", "{si}",  "status", result);
816 }
817
818 static void hook_api_api_set_verbs_v3(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const struct afb_verb_v3 *verbs)
819 {
820         hook_api(closure, hookid, export, "set_verbs_v3", "{si}",  "status", result);
821 }
822
823
824 static void hook_api_api_add_verb(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const char *verb, const char *info, int glob)
825 {
826         hook_api(closure, hookid, export, "add_verb", "{si ss ss? sb}", "status", result, "verb", verb, "info", info, "glob", glob);
827 }
828
829 static void hook_api_api_del_verb(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const char *verb)
830 {
831         hook_api(closure, hookid, export, "del_verb", "{si ss}", "status", result, "verb", verb);
832 }
833
834 static void hook_api_api_set_on_event(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result)
835 {
836         hook_api(closure, hookid, export, "set_on_event", "{si}",  "status", result);
837 }
838
839 static void hook_api_api_set_on_init(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result)
840 {
841         hook_api(closure, hookid, export, "set_on_init", "{si}",  "status", result);
842 }
843
844 static void hook_api_api_seal(void *closure, const struct afb_hookid *hookid, const struct afb_export *export)
845 {
846         hook_api(closure, hookid, export, "seal", NULL);
847 }
848
849 static void hook_api_event_handler_add(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const char *pattern)
850 {
851         hook_api(closure, hookid, export, "event_handler_add", "{si ss?}",  "status", result, "pattern", pattern);
852 }
853
854 static void hook_api_event_handler_del(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const char *pattern)
855 {
856         hook_api(closure, hookid, export, "event_handler_del", "{si ss?}",  "status", result, "pattern", pattern);
857 }
858
859 static void hook_api_class_provide(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const char *name)
860 {
861         hook_api(closure, hookid, export, "class_provide", "{si ss?}",  "status", result, "name", name);
862 }
863
864 static void hook_api_class_require(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result, const char *name)
865 {
866         hook_api(closure, hookid, export, "class_require", "{si ss?}",  "status", result, "name", name);
867 }
868
869 static void hook_api_delete_api(void *closure, const struct afb_hookid *hookid, const struct afb_export *export, int result)
870 {
871         hook_api(closure, hookid, export, "delete_api", "{si}",  "status", result);
872 }
873
874 static struct afb_hook_api_itf hook_api_itf = {
875         .hook_api_event_broadcast_before = hook_api_event_broadcast_before,
876         .hook_api_event_broadcast_after = hook_api_event_broadcast_after,
877         .hook_api_get_event_loop = hook_api_get_event_loop,
878         .hook_api_get_user_bus = hook_api_get_user_bus,
879         .hook_api_get_system_bus = hook_api_get_system_bus,
880         .hook_api_vverbose = hook_api_vverbose,
881         .hook_api_event_make = hook_api_event_make,
882         .hook_api_rootdir_get_fd = hook_api_rootdir_get_fd,
883         .hook_api_rootdir_open_locale = hook_api_rootdir_open_locale,
884         .hook_api_queue_job = hook_api_queue_job,
885         .hook_api_legacy_unstore_req = hook_api_unstore_req,
886         .hook_api_require_api = hook_api_require_api,
887         .hook_api_require_api_result = hook_api_require_api_result,
888         .hook_api_add_alias = hook_api_add_alias_cb,
889         .hook_api_start_before = hook_api_start_before,
890         .hook_api_start_after = hook_api_start_after,
891         .hook_api_on_event_before = hook_api_on_event_before,
892         .hook_api_on_event_after = hook_api_on_event_after,
893         .hook_api_call = hook_api_call,
894         .hook_api_call_result = hook_api_call_result,
895         .hook_api_callsync = hook_api_callsync,
896         .hook_api_callsync_result = hook_api_callsync_result,
897         .hook_api_new_api_before = hook_api_new_api_before,
898         .hook_api_new_api_after = hook_api_new_api_after,
899         .hook_api_api_set_verbs_v2 = hook_api_api_set_verbs_v2,
900         .hook_api_api_set_verbs_v3 = hook_api_api_set_verbs_v3,
901         .hook_api_api_add_verb = hook_api_api_add_verb,
902         .hook_api_api_del_verb = hook_api_api_del_verb,
903         .hook_api_api_set_on_event = hook_api_api_set_on_event,
904         .hook_api_api_set_on_init = hook_api_api_set_on_init,
905         .hook_api_api_seal = hook_api_api_seal,
906         .hook_api_event_handler_add = hook_api_event_handler_add,
907         .hook_api_event_handler_del = hook_api_event_handler_del,
908         .hook_api_class_provide = hook_api_class_provide,
909         .hook_api_class_require = hook_api_class_require,
910         .hook_api_delete_api = hook_api_delete_api,
911 };
912
913 /*******************************************************************************/
914 /*****  trace the events                                                   *****/
915 /*******************************************************************************/
916
917 static struct flag evt_flags[] = { /* must be sorted by names */
918                 { "addref",             afb_hook_flag_evt_addref },
919                 { "all",                afb_hook_flags_evt_all },
920                 { "broadcast_after",    afb_hook_flag_evt_broadcast_after },
921                 { "broadcast_before",   afb_hook_flag_evt_broadcast_before },
922                 { "common",             afb_hook_flags_evt_common },
923                 { "create",             afb_hook_flag_evt_create },
924                 { "extra",              afb_hook_flags_evt_extra },
925                 { "name",               afb_hook_flag_evt_name },
926                 { "push_after",         afb_hook_flag_evt_push_after },
927                 { "push_before",        afb_hook_flag_evt_push_before },
928                 { "unref",              afb_hook_flag_evt_unref },
929 };
930
931 /* get the evt value for flag of 'name' */
932 static int get_evt_flag(const char *name)
933 {
934         return get_flag(name, evt_flags, (int)(sizeof evt_flags / sizeof *evt_flags));
935 }
936
937 static void hook_evt(void *closure, const struct afb_hookid *hookid, const char *evt, int id, const char *action, const char *format, ...)
938 {
939         va_list ap;
940
941         va_start(ap, format);
942         emit(closure, hookid, "event", "{si ss ss}", format, ap,
943                                         "id", id,
944                                         "name", evt,
945                                         "action", action);
946         va_end(ap);
947 }
948
949 static void hook_evt_create(void *closure, const struct afb_hookid *hookid, const char *evt, int id)
950 {
951         hook_evt(closure, hookid, evt, id, "create", NULL);
952 }
953
954 static void hook_evt_push_before(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj)
955 {
956         hook_evt(closure, hookid, evt, id, "push_before", "{sO*}", "data", obj);
957 }
958
959
960 static void hook_evt_push_after(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj, int result)
961 {
962         hook_evt(closure, hookid, evt, id, "push_after", "{sO* si}", "data", obj, "result", result);
963 }
964
965 static void hook_evt_broadcast_before(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj)
966 {
967         hook_evt(closure, hookid, evt, id, "broadcast_before", "{sO*}", "data", obj);
968 }
969
970 static void hook_evt_broadcast_after(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj, int result)
971 {
972         hook_evt(closure, hookid, evt, id, "broadcast_after", "{sO* si}", "data", obj, "result", result);
973 }
974
975 static void hook_evt_name(void *closure, const struct afb_hookid *hookid, const char *evt, int id, const char *result)
976 {
977         hook_evt(closure, hookid, evt, id, "name", "{ss}", "result", result);
978 }
979
980 static void hook_evt_addref(void *closure, const struct afb_hookid *hookid, const char *evt, int id)
981 {
982         hook_evt(closure, hookid, evt, id, "addref", NULL);
983 }
984
985 static void hook_evt_unref(void *closure, const struct afb_hookid *hookid, const char *evt, int id)
986 {
987         hook_evt(closure, hookid, evt, id, "unref", NULL);
988 }
989
990 static struct afb_hook_evt_itf hook_evt_itf = {
991         .hook_evt_create = hook_evt_create,
992         .hook_evt_push_before = hook_evt_push_before,
993         .hook_evt_push_after = hook_evt_push_after,
994         .hook_evt_broadcast_before = hook_evt_broadcast_before,
995         .hook_evt_broadcast_after = hook_evt_broadcast_after,
996         .hook_evt_name = hook_evt_name,
997         .hook_evt_addref = hook_evt_addref,
998         .hook_evt_unref = hook_evt_unref
999 };
1000
1001 /*******************************************************************************/
1002 /*****  trace the sessions                                                 *****/
1003 /*******************************************************************************/
1004
1005 static struct flag session_flags[] = { /* must be sorted by names */
1006                 { "addref",             afb_hook_flag_session_addref },
1007                 { "all",                afb_hook_flags_session_all },
1008                 { "close",              afb_hook_flag_session_close },
1009                 { "common",             afb_hook_flags_session_common },
1010                 { "create",             afb_hook_flag_session_create },
1011                 { "destroy",            afb_hook_flag_session_destroy },
1012                 { "renew",              afb_hook_flag_session_renew },
1013                 { "unref",              afb_hook_flag_session_unref },
1014 };
1015
1016 /* get the session value for flag of 'name' */
1017 static int get_session_flag(const char *name)
1018 {
1019         return get_flag(name, session_flags, (int)(sizeof session_flags / sizeof *session_flags));
1020 }
1021
1022 static void hook_session(void *closure, const struct afb_hookid *hookid, struct afb_session *session, const char *action, const char *format, ...)
1023 {
1024         va_list ap;
1025
1026         va_start(ap, format);
1027         emit(closure, hookid, "session", "{ss ss}", format, ap,
1028                                         "uuid", session,
1029                                         "action", action);
1030         va_end(ap);
1031 }
1032
1033 static void hook_session_create(void *closure, const struct afb_hookid *hookid, struct afb_session *session)
1034 {
1035         hook_session(closure, hookid, session, "create", "{ss}", "token", afb_session_token(session));
1036 }
1037
1038 static void hook_session_close(void *closure, const struct afb_hookid *hookid, struct afb_session *session)
1039 {
1040         hook_session(closure, hookid, session, "close", NULL);
1041 }
1042
1043 static void hook_session_destroy(void *closure, const struct afb_hookid *hookid, struct afb_session *session)
1044 {
1045         hook_session(closure, hookid, session, "destroy", NULL);
1046 }
1047
1048 static void hook_session_renew(void *closure, const struct afb_hookid *hookid, struct afb_session *session)
1049 {
1050         hook_session(closure, hookid, session, "renew", "{ss}", "token", afb_session_token(session));
1051 }
1052
1053 static void hook_session_addref(void *closure, const struct afb_hookid *hookid, struct afb_session *session)
1054 {
1055         hook_session(closure, hookid, session, "addref", NULL);
1056 }
1057
1058 static void hook_session_unref(void *closure, const struct afb_hookid *hookid, struct afb_session *session)
1059 {
1060         hook_session(closure, hookid, session, "unref", NULL);
1061 }
1062
1063 static struct afb_hook_session_itf hook_session_itf = {
1064         .hook_session_create = hook_session_create,
1065         .hook_session_close = hook_session_close,
1066         .hook_session_destroy = hook_session_destroy,
1067         .hook_session_renew = hook_session_renew,
1068         .hook_session_addref = hook_session_addref,
1069         .hook_session_unref = hook_session_unref
1070 };
1071
1072 /*******************************************************************************/
1073 /*****  trace the globals                                                  *****/
1074 /*******************************************************************************/
1075
1076 static struct flag global_flags[] = { /* must be sorted by names */
1077                 { "all",                afb_hook_flags_global_all },
1078                 { "vverbose",           afb_hook_flag_global_vverbose },
1079 };
1080
1081 /* get the global value for flag of 'name' */
1082 static int get_global_flag(const char *name)
1083 {
1084         return get_flag(name, global_flags, (int)(sizeof global_flags / sizeof *global_flags));
1085 }
1086
1087 static void hook_global(void *closure, const struct afb_hookid *hookid, const char *action, const char *format, ...)
1088 {
1089         va_list ap;
1090
1091         va_start(ap, format);
1092         emit(closure, hookid, "global", "{ss}", format, ap, "action", action);
1093         va_end(ap);
1094 }
1095
1096 static void hook_global_vverbose(void *closure, const struct afb_hookid *hookid, int level, const char *file, int line, const char *function, const char *fmt, va_list args)
1097 {
1098         struct json_object *pos;
1099         int len;
1100         char *msg;
1101         va_list ap;
1102
1103         pos = NULL;
1104         msg = NULL;
1105
1106         va_copy(ap, args);
1107         len = vasprintf(&msg, fmt, ap);
1108         va_end(ap);
1109
1110         if (file)
1111                 wrap_json_pack(&pos, "{ss si ss*}", "file", file, "line", line, "function", function);
1112
1113         hook_global(closure, hookid, "vverbose", "{si ss* ss? so*}",
1114                                         "level", level,
1115                                         "type", verbosity_level_name(level),
1116                                         len < 0 ? "format" : "message", len < 0 ? fmt : msg,
1117                                         "position", pos);
1118
1119         free(msg);
1120 }
1121
1122 static struct afb_hook_global_itf hook_global_itf = {
1123         .hook_global_vverbose = hook_global_vverbose,
1124 };
1125
1126 /*******************************************************************************/
1127 /*****  abstract types                                                     *****/
1128 /*******************************************************************************/
1129
1130 static
1131 struct
1132 {
1133         const char *name;
1134         void (*unref)(void*);
1135         int (*get_flag)(const char*);
1136 }
1137 abstracting[Trace_Type_Count] =
1138 {
1139         [Trace_Type_Xreq] =
1140         {
1141                 .name = "request",
1142                 .unref =  (void(*)(void*))afb_hook_unref_xreq,
1143                 .get_flag = get_xreq_flag
1144         },
1145         [Trace_Type_Api] =
1146         {
1147                 .name = "api",
1148                 .unref =  (void(*)(void*))afb_hook_unref_api,
1149                 .get_flag = get_api_flag
1150         },
1151         [Trace_Type_Evt] =
1152         {
1153                 .name = "event",
1154                 .unref =  (void(*)(void*))afb_hook_unref_evt,
1155                 .get_flag = get_evt_flag
1156         },
1157         [Trace_Type_Session] =
1158         {
1159                 .name = "session",
1160                 .unref =  (void(*)(void*))afb_hook_unref_session,
1161                 .get_flag = get_session_flag
1162         },
1163         [Trace_Type_Global] =
1164         {
1165                 .name = "global",
1166                 .unref =  (void(*)(void*))afb_hook_unref_global,
1167                 .get_flag = get_global_flag
1168         },
1169 #if !defined(REMOVE_LEGACY_TRACE)
1170         [Trace_Legacy_Type_Ditf] =
1171         {
1172                 .name = "daemon",
1173                 .unref =  (void(*)(void*))afb_hook_unref_api,
1174                 .get_flag = get_legacy_ditf_flag
1175         },
1176         [Trace_Legacy_Type_Svc] =
1177         {
1178                 .name = "service",
1179                 .unref =  (void(*)(void*))afb_hook_unref_api,
1180                 .get_flag = get_legacy_svc_flag
1181         },
1182 #endif
1183 };
1184
1185 /*******************************************************************************/
1186 /*****  handle trace data                                                  *****/
1187 /*******************************************************************************/
1188
1189 /* drop hooks of 'trace' matching 'tag' and 'event' and 'session' */
1190 static void trace_unhook(struct afb_trace *trace, struct tag *tag, struct event *event, struct afb_session *session)
1191 {
1192         int i;
1193         struct hook *hook, **prev;
1194
1195         /* remove any event */
1196         for (i = 0 ; i < Trace_Type_Count ; i++) {
1197                 prev = &trace->hooks[i];
1198                 while ((hook = *prev)) {
1199                         if ((tag && tag != hook->tag)
1200                          || (event && event != hook->event)
1201                          || (session && session != hook->session))
1202                                 prev = &hook->next;
1203                         else {
1204                                 *prev = hook->next;
1205                                 abstracting[i].unref(hook->handler);
1206                                 free(hook);
1207                         }
1208                 }
1209         }
1210 }
1211
1212 /* cleanup: removes unused tags, events and sessions of the 'trace' */
1213 static void trace_cleanup(struct afb_trace *trace)
1214 {
1215         int i;
1216         struct hook *hook;
1217         struct tag *tag, **ptag;
1218         struct event *event, **pevent;
1219
1220         /* clean tags */
1221         ptag = &trace->tags;
1222         while ((tag = *ptag)) {
1223                 /* search for tag */
1224                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++)
1225                         for (hook = trace->hooks[i] ; hook && hook->tag != tag ; hook = hook->next);
1226                 /* keep or free whether used or not */
1227                 if (hook)
1228                         ptag = &tag->next;
1229                 else {
1230                         *ptag = tag->next;
1231                         free(tag);
1232                 }
1233         }
1234         /* clean events */
1235         pevent = &trace->events;
1236         while ((event = *pevent)) {
1237                 /* search for event */
1238                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++)
1239                         for (hook = trace->hooks[i] ; hook && hook->event != event ; hook = hook->next);
1240                 /* keep or free whether used or not */
1241                 if (hook)
1242                         pevent = &event->next;
1243                 else {
1244                         *pevent = event->next;
1245                         afb_evt_evtid_unref(event->evtid);
1246                         free(event);
1247                 }
1248         }
1249 }
1250
1251 /*
1252  * Get the tag of 'name' within 'trace'.
1253  * If 'alloc' isn't zero, create the tag and add it.
1254  */
1255 static struct tag *trace_get_tag(struct afb_trace *trace, const char *name, int alloc)
1256 {
1257         struct tag *tag;
1258
1259         /* search the tag of 'name' */
1260         tag = trace->tags;
1261         while (tag && strcmp(name, tag->tag))
1262                 tag = tag->next;
1263
1264         if (!tag && alloc) {
1265                 /* creation if needed */
1266                 tag = malloc(sizeof * tag + strlen(name));
1267                 if (tag) {
1268                         strcpy(tag->tag, name);
1269                         tag->next = trace->tags;
1270                         trace->tags = tag;
1271                 }
1272         }
1273         return tag;
1274 }
1275
1276 /*
1277  * Get the event of 'name' within 'trace'.
1278  * If 'alloc' isn't zero, create the event and add it.
1279  */
1280 static struct event *trace_get_event(struct afb_trace *trace, const char *name, int alloc)
1281 {
1282         struct event *event;
1283
1284         /* search the event */
1285         event = trace->events;
1286         while (event && strcmp(afb_evt_evtid_name(event->evtid), name))
1287                 event = event->next;
1288
1289         if (!event && alloc) {
1290                 event = malloc(sizeof * event);
1291                 if (event) {
1292                         event->evtid = afb_evt_evtid_create2(trace->apiname, name);
1293                         if (event->evtid) {
1294                                 event->next = trace->events;
1295                                 trace->events = event;
1296                         } else {
1297                                 free(event);
1298                                 event = NULL;
1299                         }
1300                 }
1301         }
1302         return event;
1303 }
1304
1305 /*
1306  * called on session closing
1307  */
1308 static void session_closed(void *item)
1309 {
1310         struct cookie *cookie = item;
1311
1312         pthread_mutex_lock(&cookie->trace->mutex);
1313         trace_unhook(cookie->trace, NULL, NULL, cookie->session);
1314         pthread_mutex_unlock(&cookie->trace->mutex);
1315         free(cookie);
1316 }
1317
1318 /*
1319  * records the cookie of session for tracking close
1320  */
1321 static void *session_open(void *closure)
1322 {
1323         struct cookie *param = closure, *cookie;
1324         cookie = malloc(sizeof *cookie);
1325         if (cookie)
1326                 *cookie = *param;
1327         return cookie;
1328 }
1329
1330 /*
1331  * Get the session of 'uuid' within 'trace'.
1332  * If 'alloc' isn't zero, create the session and add it.
1333  */
1334 static struct afb_session *trace_get_session_by_uuid(struct afb_trace *trace, const char *uuid, int alloc)
1335 {
1336         struct cookie cookie;
1337
1338         if (!alloc)
1339                 cookie.session = afb_session_search(uuid);
1340         else {
1341                 cookie.session = afb_session_get(uuid, AFB_SESSION_TIMEOUT_DEFAULT, NULL);
1342                 if (cookie.session) {
1343                         cookie.trace = trace;
1344                         afb_session_cookie(cookie.session, cookie.trace, session_open, session_closed, &cookie, 0);
1345                 }
1346         }
1347         return cookie.session;
1348 }
1349
1350 static struct hook *trace_make_detached_hook(struct afb_trace *trace, const char *event, const char *tag)
1351 {
1352         struct hook *hook;
1353
1354         tag = tag ?: DEFAULT_TAG_NAME;
1355         event = event ?: DEFAULT_EVENT_NAME;
1356         hook = malloc(sizeof *hook);
1357         if (hook) {
1358                 hook->tag = trace_get_tag(trace, tag, 1);
1359                 hook->event = trace_get_event(trace, event, 1);
1360                 hook->session = NULL;
1361                 hook->handler = NULL;
1362         }
1363         return hook;
1364 }
1365
1366 static void trace_attach_hook(struct afb_trace *trace, struct hook *hook, enum trace_type type)
1367 {
1368         hook->next = trace->hooks[type];
1369         trace->hooks[type] = hook;
1370 }
1371
1372 /*******************************************************************************/
1373 /*****  handle client requests                                             *****/
1374 /*******************************************************************************/
1375
1376 struct context
1377 {
1378         struct afb_trace *trace;
1379         afb_req_t req;
1380         char *errors;
1381 };
1382
1383 struct desc
1384 {
1385         struct context *context;
1386         const char *name;
1387         const char *tag;
1388         const char *uuid;
1389         const char *apiname;
1390         const char *verbname;
1391         const char *pattern;
1392         int flags[Trace_Type_Count];
1393 };
1394
1395 static void addhook(struct desc *desc, enum trace_type type)
1396 {
1397         struct hook *hook;
1398         struct afb_session *session;
1399         struct afb_session *bind;
1400         struct afb_trace *trace = desc->context->trace;
1401
1402         /* check permission for bound traces */
1403         bind = trace->bound;
1404         if (bind != NULL) {
1405                 if (type != Trace_Type_Xreq) {
1406                         ctxt_error(&desc->context->errors, "tracing %s is forbidden", abstracting[type].name);
1407                         return;
1408                 }
1409                 if (desc->uuid) {
1410                         ctxt_error(&desc->context->errors, "setting session is forbidden");
1411                         return;
1412                 }
1413         }
1414
1415         /* allocate the hook */
1416         hook = trace_make_detached_hook(trace, desc->name, desc->tag);
1417         if (!hook) {
1418                 ctxt_error(&desc->context->errors, "allocation of hook failed");
1419                 return;
1420         }
1421
1422         /* create the hook handler */
1423         switch (type) {
1424         case Trace_Type_Xreq:
1425                 if (!desc->uuid)
1426                         session = afb_session_addref(bind);
1427                 else {
1428                         session = trace_get_session_by_uuid(trace, desc->uuid, 1);
1429                         if (!session) {
1430                                 ctxt_error(&desc->context->errors, "allocation of session failed");
1431                                 free(hook);
1432                                 return;
1433                         }
1434                 }
1435                 hook->handler = afb_hook_create_xreq(desc->apiname, desc->verbname, session,
1436                                 desc->flags[type], &hook_xreq_itf, hook);
1437                 afb_session_unref(session);
1438                 break;
1439         case Trace_Type_Api:
1440                 hook->handler = afb_hook_create_api(desc->apiname, desc->flags[type], &hook_api_itf, hook);
1441                 break;
1442         case Trace_Type_Evt:
1443                 hook->handler = afb_hook_create_evt(desc->pattern, desc->flags[type], &hook_evt_itf, hook);
1444                 break;
1445         case Trace_Type_Session:
1446                 hook->handler = afb_hook_create_session(desc->uuid, desc->flags[type], &hook_session_itf, hook);
1447                 break;
1448         case Trace_Type_Global:
1449                 hook->handler = afb_hook_create_global(desc->flags[type], &hook_global_itf, hook);
1450                 break;
1451         default:
1452                 break;
1453         }
1454         if (!hook->handler) {
1455                 ctxt_error(&desc->context->errors, "creation of hook failed");
1456                 free(hook);
1457                 return;
1458         }
1459
1460         /* attach and activate the hook */
1461         afb_req_subscribe(desc->context->req, afb_evt_event_x2_from_evtid(hook->event->evtid));
1462         trace_attach_hook(trace, hook, type);
1463 }
1464
1465 static void addhooks(struct desc *desc)
1466 {
1467         int i;
1468
1469 #if !defined(REMOVE_LEGACY_TRACE)
1470         desc->flags[Trace_Type_Api] |= desc->flags[Trace_Legacy_Type_Ditf] | desc->flags[Trace_Legacy_Type_Svc];
1471         desc->flags[Trace_Legacy_Type_Ditf] = desc->flags[Trace_Legacy_Type_Svc] = 0;
1472 #endif
1473
1474         for (i = 0 ; i < Trace_Type_Count ; i++) {
1475                 if (desc->flags[i])
1476                         addhook(desc, i);
1477         }
1478 }
1479
1480 static void add_flags(void *closure, struct json_object *object, enum trace_type type)
1481 {
1482         int value;
1483         const char *name, *queried;
1484         struct desc *desc = closure;
1485
1486         if (wrap_json_unpack(object, "s", &name))
1487                 ctxt_error(&desc->context->errors, "unexpected %s value %s",
1488                                         abstracting[type].name,
1489                                         json_object_to_json_string(object));
1490         else {
1491                 queried = (name[0] == '*' && !name[1]) ? "all" : name;
1492                 value = abstracting[type].get_flag(queried);
1493                 if (value)
1494                         desc->flags[type] |= value;
1495                 else
1496                         ctxt_error(&desc->context->errors, "unknown %s name %s",
1497                                         abstracting[type].name, name);
1498         }
1499 }
1500
1501 static void add_xreq_flags(void *closure, struct json_object *object)
1502 {
1503         add_flags(closure, object, Trace_Type_Xreq);
1504 }
1505
1506 #if !defined(REMOVE_LEGACY_TRACE)
1507 static void legacy_add_ditf_flags(void *closure, struct json_object *object)
1508 {
1509         add_flags(closure, object, Trace_Legacy_Type_Ditf);
1510 }
1511
1512 static void legacy_add_svc_flags(void *closure, struct json_object *object)
1513 {
1514         add_flags(closure, object, Trace_Legacy_Type_Svc);
1515 }
1516 #endif
1517
1518 static void add_api_flags(void *closure, struct json_object *object)
1519 {
1520         add_flags(closure, object, Trace_Type_Api);
1521 }
1522
1523 static void add_evt_flags(void *closure, struct json_object *object)
1524 {
1525         add_flags(closure, object, Trace_Type_Evt);
1526 }
1527
1528 static void add_session_flags(void *closure, struct json_object *object)
1529 {
1530         add_flags(closure, object, Trace_Type_Session);
1531 }
1532
1533 static void add_global_flags(void *closure, struct json_object *object)
1534 {
1535         add_flags(closure, object, Trace_Type_Global);
1536 }
1537
1538 /* add hooks */
1539 static void add(void *closure, struct json_object *object)
1540 {
1541         int rc;
1542         struct desc desc;
1543         struct json_object *request, *event, *sub, *global, *session, *api;
1544 #if !defined(REMOVE_LEGACY_TRACE)
1545         struct json_object *daemon, *service;
1546 #endif
1547
1548         memcpy (&desc, closure, sizeof desc);
1549         request = event = sub = global = session = api = NULL;
1550 #if !defined(REMOVE_LEGACY_TRACE)
1551         daemon = service = NULL;
1552 #endif
1553
1554         rc = wrap_json_unpack(object, "{s?s s?s s?s s?s s?s s?s s?o s?o s?o s?o s?o s?o s?o}",
1555                         "name", &desc.name,
1556                         "tag", &desc.tag,
1557                         "apiname", &desc.apiname,
1558                         "verbname", &desc.verbname,
1559                         "uuid", &desc.uuid,
1560                         "pattern", &desc.pattern,
1561                         "api", &api,
1562                         "request", &request,
1563 #if !defined(REMOVE_LEGACY_TRACE)
1564                         "daemon", &daemon,
1565                         "service", &service,
1566 #endif
1567                         "event", &event,
1568                         "session", &session,
1569                         "global", &global,
1570                         "for", &sub);
1571
1572         if (!rc) {
1573                 /* replace stars */
1574                 if (desc.apiname && desc.apiname[0] == '*' && !desc.apiname[1])
1575                         desc.apiname = NULL;
1576
1577                 if (desc.verbname && desc.verbname[0] == '*' && !desc.verbname[1])
1578                         desc.verbname = NULL;
1579
1580                 if (desc.uuid && desc.uuid[0] == '*' && !desc.uuid[1])
1581                         desc.uuid = NULL;
1582
1583                 /* get what is expected */
1584                 if (request)
1585                         wrap_json_optarray_for_all(request, add_xreq_flags, &desc);
1586
1587                 if (api)
1588                         wrap_json_optarray_for_all(api, add_api_flags, &desc);
1589
1590 #if !defined(REMOVE_LEGACY_TRACE)
1591                 if (daemon)
1592                         wrap_json_optarray_for_all(daemon, legacy_add_ditf_flags, &desc);
1593
1594                 if (service)
1595                         wrap_json_optarray_for_all(service, legacy_add_svc_flags, &desc);
1596 #endif
1597
1598                 if (event)
1599                         wrap_json_optarray_for_all(event, add_evt_flags, &desc);
1600
1601                 if (session)
1602                         wrap_json_optarray_for_all(event, add_session_flags, &desc);
1603
1604                 if (global)
1605                         wrap_json_optarray_for_all(global, add_global_flags, &desc);
1606
1607                 /* apply */
1608                 if (sub)
1609                         wrap_json_optarray_for_all(sub, add, &desc);
1610                 else
1611                         addhooks(&desc);
1612         }
1613         else {
1614                 wrap_json_optarray_for_all(object, add_xreq_flags, &desc);
1615                 addhooks(&desc);
1616         }
1617 }
1618
1619 /* drop hooks of given tag */
1620 static void drop_tag(void *closure, struct json_object *object)
1621 {
1622         int rc;
1623         struct context *context = closure;
1624         struct tag *tag;
1625         const char *name;
1626
1627         rc = wrap_json_unpack(object, "s", &name);
1628         if (rc)
1629                 ctxt_error(&context->errors, "unexpected tag value %s", json_object_to_json_string(object));
1630         else {
1631                 tag = trace_get_tag(context->trace, name, 0);
1632                 if (!tag)
1633                         ctxt_error(&context->errors, "tag %s not found", name);
1634                 else
1635                         trace_unhook(context->trace, tag, NULL, NULL);
1636         }
1637 }
1638
1639 /* drop hooks of given event */
1640 static void drop_event(void *closure, struct json_object *object)
1641 {
1642         int rc;
1643         struct context *context = closure;
1644         struct event *event;
1645         const char *name;
1646
1647         rc = wrap_json_unpack(object, "s", &name);
1648         if (rc)
1649                 ctxt_error(&context->errors, "unexpected event value %s", json_object_to_json_string(object));
1650         else {
1651                 event = trace_get_event(context->trace, name, 0);
1652                 if (!event)
1653                         ctxt_error(&context->errors, "event %s not found", name);
1654                 else
1655                         trace_unhook(context->trace, NULL, event, NULL);
1656         }
1657 }
1658
1659 /* drop hooks of given session */
1660 static void drop_session(void *closure, struct json_object *object)
1661 {
1662         int rc;
1663         struct context *context = closure;
1664         struct afb_session *session;
1665         const char *uuid;
1666
1667         rc = wrap_json_unpack(object, "s", &uuid);
1668         if (rc)
1669                 ctxt_error(&context->errors, "unexpected session value %s", json_object_to_json_string(object));
1670         else {
1671                 session = trace_get_session_by_uuid(context->trace, uuid, 0);
1672                 if (!session)
1673                         ctxt_error(&context->errors, "session %s not found", uuid);
1674                 else {
1675                         trace_unhook(context->trace, NULL, NULL, session);
1676                         afb_session_unref(session);
1677                 }
1678         }
1679 }
1680
1681 /*******************************************************************************/
1682 /*****  public interface                                                   *****/
1683 /*******************************************************************************/
1684
1685 /* allocates an afb_trace instance */
1686 struct afb_trace *afb_trace_create(const char *apiname, struct afb_session *bound)
1687 {
1688         struct afb_trace *trace;
1689
1690         assert(apiname);
1691
1692         trace = calloc(1, sizeof *trace);
1693         if (trace) {
1694                 trace->refcount = 1;
1695                 trace->bound = bound;
1696                 trace->apiname = apiname;
1697                 pthread_mutex_init(&trace->mutex, NULL);
1698         }
1699         return trace;
1700 }
1701
1702 /* add a reference to the trace */
1703 void afb_trace_addref(struct afb_trace *trace)
1704 {
1705         __atomic_add_fetch(&trace->refcount, 1, __ATOMIC_RELAXED);
1706 }
1707
1708 /* drop one reference to the trace */
1709 void afb_trace_unref(struct afb_trace *trace)
1710 {
1711         if (trace && !__atomic_sub_fetch(&trace->refcount, 1, __ATOMIC_RELAXED)) {
1712                 /* clean hooks */
1713                 trace_unhook(trace, NULL, NULL, NULL);
1714                 trace_cleanup(trace);
1715                 pthread_mutex_destroy(&trace->mutex);
1716                 free(trace);
1717         }
1718 }
1719
1720 /* add traces */
1721 int afb_trace_add(afb_req_t req, struct json_object *args, struct afb_trace *trace)
1722 {
1723         struct context context;
1724         struct desc desc;
1725
1726         memset(&context, 0, sizeof context);
1727         context.trace = trace;
1728         context.req = req;
1729
1730         memset(&desc, 0, sizeof desc);
1731         desc.context = &context;
1732
1733         pthread_mutex_lock(&trace->mutex);
1734         wrap_json_optarray_for_all(args, add, &desc);
1735         pthread_mutex_unlock(&trace->mutex);
1736
1737         if (!context.errors)
1738                 return 0;
1739
1740         afb_req_fail(req, "error-detected", context.errors);
1741         free(context.errors);
1742         return -1;
1743 }
1744
1745 /* drop traces */
1746 int afb_trace_drop(afb_req_t req, struct json_object *args, struct afb_trace *trace)
1747 {
1748         int rc;
1749         struct context context;
1750         struct json_object *tags, *events, *uuids;
1751
1752         memset(&context, 0, sizeof context);
1753         context.trace = trace;
1754         context.req = req;
1755
1756         /* special: boolean value */
1757         if (!wrap_json_unpack(args, "b", &rc)) {
1758                 if (rc) {
1759                         pthread_mutex_lock(&trace->mutex);
1760                         trace_unhook(trace, NULL, NULL, NULL);
1761                         trace_cleanup(trace);
1762                         pthread_mutex_unlock(&trace->mutex);
1763                 }
1764                 return 0;
1765         }
1766
1767         tags = events = uuids = NULL;
1768         rc = wrap_json_unpack(args, "{s?o s?o s?o}",
1769                         "event", &events,
1770                         "tag", &tags,
1771                         "uuid", &uuids);
1772
1773         if (rc < 0 || !(events || tags || uuids)) {
1774                 afb_req_fail(req, "error-detected", "bad drop arguments");
1775                 return -1;
1776         }
1777
1778         pthread_mutex_lock(&trace->mutex);
1779
1780         if (tags)
1781                 wrap_json_optarray_for_all(tags, drop_tag, &context);
1782
1783         if (events)
1784                 wrap_json_optarray_for_all(events, drop_event, &context);
1785
1786         if (uuids)
1787                 wrap_json_optarray_for_all(uuids, drop_session, &context);
1788
1789         trace_cleanup(trace);
1790
1791         pthread_mutex_unlock(&trace->mutex);
1792
1793         if (!context.errors)
1794                 return 0;
1795
1796         afb_req_fail(req, "error-detected", context.errors);
1797         free(context.errors);
1798         return -1;
1799 }