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