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