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