hook+trace: add a unique timestamp
[src/app-framework-binder.git] / src / afb-trace.c
1 /*
2  * Copyright (C) 2016, 2017 "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 #define AFB_BINDING_PRAGMA_NO_VERBOSE_MACRO
20
21 #include <assert.h>
22 #include <string.h>
23 #include <stdarg.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <limits.h>
27 #include <unistd.h>
28 #include <pthread.h>
29
30 #include <json-c/json.h>
31 #include <afb/afb-binding-v2.h>
32
33 #include "afb-hook.h"
34 #include "afb-cred.h"
35 #include "afb-session.h"
36 #include "afb-xreq.h"
37 #include "afb-ditf.h"
38 #include "afb-svc.h"
39 #include "afb-evt.h"
40 #include "afb-trace.h"
41
42 #include "wrap-json.h"
43
44 /*******************************************************************************/
45 /*****  default names                                                      *****/
46 /*******************************************************************************/
47
48 #if !defined(DEFAULT_EVENT_NAME)
49 #  define DEFAULT_EVENT_NAME "trace"
50 #endif
51 #if !defined(DEFAULT_TAG_NAME)
52 #  define DEFAULT_TAG_NAME "trace"
53 #endif
54
55 /*******************************************************************************/
56 /*****  types                                                              *****/
57 /*******************************************************************************/
58
59 /* structure for searching flags by names */
60 struct flag
61 {
62         const char *name;       /** the name */
63         int value;              /** the value */
64 };
65
66 /* struct for tags */
67 struct tag {
68         struct tag *next;       /* link to the next */
69         char tag[1];            /* name of the tag */
70 };
71
72 /* struct for events */
73 struct event {
74         struct event *next;             /* link to the next event */
75         struct afb_event event;         /* the event */
76 };
77
78 /* struct for sessions */
79 struct session {
80         struct session *next;           /* link to the next session */
81         struct afb_session *session;    /* the session */
82         struct afb_trace *trace;        /* the tracer */
83 };
84
85 /* struct for recording hooks */
86 struct hook {
87         struct hook *next;              /* link to next hook */
88         void *handler;                  /* the handler of the hook */
89         struct event *event;            /* the associated event */
90         struct tag *tag;                /* the associated tag */
91         struct session *session;        /* the associated session */
92 };
93
94 /* types of hooks */
95 enum trace_type
96 {
97         Trace_Type_Xreq,        /* xreq hooks */
98         Trace_Type_Ditf,        /* ditf hooks */
99         Trace_Type_Svc,         /* svc hooks */
100         Trace_Type_Evt,         /* evt hooks */
101         Trace_Type_Count        /* count of types of hooks */
102 };
103
104 /* client data */
105 struct afb_trace
106 {
107         int refcount;                           /* reference count */
108         pthread_mutex_t mutex;                  /* concurrency management */
109         struct afb_daemon *daemon;              /* daemon */
110         struct afb_session *bound;              /* bound to session */
111         struct event *events;                   /* list of events */
112         struct tag *tags;                       /* list of tags */
113         struct session *sessions;               /* list of tags */
114         struct hook *hooks[Trace_Type_Count];   /* hooks */
115 };
116
117 /*******************************************************************************/
118 /*****  utility functions                                                  *****/
119 /*******************************************************************************/
120
121 static void ctxt_error(char **errors, const char *format, ...)
122 {
123         int len;
124         char *errs;
125         size_t sz;
126         char buffer[1024];
127         va_list ap;
128
129         va_start(ap, format);
130         len = vsnprintf(buffer, sizeof buffer, format, ap);
131         va_end(ap);
132         if (len > (int)(sizeof buffer - 2))
133                 len = (int)(sizeof buffer - 2);
134         buffer[len++] = '\n';
135         buffer[len++] = 0;
136
137         errs = *errors;
138         sz = errs ? strlen(errs) : 0;
139         errs = realloc(errs, sz + (size_t)len);
140         if (errs) {
141                 memcpy(errs + sz, buffer, len);
142                 *errors = errs;
143         }
144 }
145
146 /* get the value of the flag of 'name' in the array 'flags' of 'count elements */
147 static int get_flag(const char *name, struct flag flags[], int count)
148 {
149         /* dichotomic search */
150         int lower = 0, upper = count;
151         while (lower < upper) {
152                 int mid = (lower + upper) >> 1;
153                 int cmp = strcmp(name, flags[mid].name);
154                 if (!cmp)
155                         return flags[mid].value;
156                 if (cmp < 0)
157                         upper = mid;
158                 else
159                         lower = mid + 1;
160         }
161         return 0;
162 }
163
164 /* timestamp */
165 static struct json_object *timestamp(const struct afb_hookid *hookid)
166 {
167         char ts[50];
168
169         snprintf(ts, sizeof ts, "%llu.%06lu", (long long unsigned)hookid->time.tv_sec, (long unsigned)(hookid->time.tv_nsec / 1000));
170         return json_object_new_string(ts);
171 }
172
173 /* verbosity level name or NULL */
174 static const char *verbosity_level_name(int level)
175 {
176         static const char *names[] = {
177                 "error",
178                 "warning",
179                 "notice",
180                 "info",
181                 "debug"
182         };
183
184         return level >= 3 && level <= 7 ? names[level - 3] : NULL;
185 }
186
187 /* generic hook */
188 static void emit(void *closure, const struct afb_hookid *hookid, const char *type, const char *fmt1, const char *fmt2, va_list ap2, ...)
189 {
190         struct hook *hook = closure;
191         struct json_object *event, *data1, *data2;
192         va_list ap1;
193
194         data1 = data2 = event = NULL;
195         va_start(ap1, ap2);
196         wrap_json_vpack(&data1, fmt1, ap1);
197         va_end(ap1);
198         if (fmt2)
199                 wrap_json_vpack(&data2, fmt2, ap2);
200
201         wrap_json_pack(&event, "{so ss ss si so so*}",
202                                         "time", timestamp(hookid),
203                                         "tag", hook->tag->tag,
204                                         "type", type,
205                                         "id", (int)(hookid->id & INT_MAX),
206                                         type, data1,
207                                         "data", data2);
208
209         afb_evt_unhooked_push(hook->event->event, event);
210 }
211
212 /*******************************************************************************/
213 /*****  trace the requests                                                 *****/
214 /*******************************************************************************/
215
216 static struct flag xreq_flags[] = { /* must be sorted by names */
217                 { "addref",             afb_hook_flag_req_addref },
218                 { "all",                afb_hook_flags_req_all },
219                 { "args",               afb_hook_flags_req_args },
220                 { "begin",              afb_hook_flag_req_begin },
221                 { "common",             afb_hook_flags_req_common },
222                 { "context",            afb_hook_flags_req_context },
223                 { "context_get",        afb_hook_flag_req_context_get },
224                 { "context_set",        afb_hook_flag_req_context_set },
225                 { "end",                afb_hook_flag_req_end },
226                 { "event",              afb_hook_flags_req_event },
227                 { "extra",              afb_hook_flags_req_extra },
228                 { "fail",               afb_hook_flag_req_fail },
229                 { "get",                afb_hook_flag_req_get },
230                 { "json",               afb_hook_flag_req_json },
231                 { "life",               afb_hook_flags_req_life },
232                 { "ref",                afb_hook_flags_req_ref },
233                 { "result",             afb_hook_flags_req_result },
234                 { "session",            afb_hook_flags_req_session },
235                 { "session_close",      afb_hook_flag_req_session_close },
236                 { "session_set_LOA",    afb_hook_flag_req_session_set_LOA },
237                 { "store",              afb_hook_flag_req_store },
238                 { "stores",             afb_hook_flags_req_stores },
239                 { "subcall",            afb_hook_flag_req_subcall },
240                 { "subcall_req",        afb_hook_flag_req_subcall_req },
241                 { "subcall_req_result", afb_hook_flag_req_subcall_req_result },
242                 { "subcall_result",     afb_hook_flag_req_subcall_result },
243                 { "subcalls",           afb_hook_flags_req_subcalls },
244                 { "subcallsync",        afb_hook_flag_req_subcallsync },
245                 { "subcallsync_result", afb_hook_flag_req_subcallsync_result },
246                 { "subscribe",          afb_hook_flag_req_subscribe },
247                 { "success",            afb_hook_flag_req_success },
248                 { "unref",              afb_hook_flag_req_unref },
249                 { "unstore",            afb_hook_flag_req_unstore },
250                 { "unsubscribe",        afb_hook_flag_req_unsubscribe },
251                 { "vverbose",           afb_hook_flag_req_vverbose },
252 };
253
254 /* get the xreq value for flag of 'name' */
255 static int get_xreq_flag(const char *name)
256 {
257         return get_flag(name, xreq_flags, (int)(sizeof xreq_flags / sizeof *xreq_flags));
258 }
259
260 static void hook_xreq(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *action, const char *format, ...)
261 {
262         struct json_object *cred = NULL;
263         const char *session = NULL;
264         va_list ap;
265
266         if (xreq->context.session)
267                 session = afb_session_uuid(xreq->context.session);
268
269         if (xreq->cred)
270                 wrap_json_pack(&cred, "{si ss si si ss* ss*}",
271                                                 "uid", (int)xreq->cred->uid,
272                                                 "user", xreq->cred->user,
273                                                 "gid", (int)xreq->cred->gid,
274                                                 "pid", (int)xreq->cred->pid,
275                                                 "label", xreq->cred->label,
276                                                 "id", xreq->cred->id
277                                         );
278         va_start(ap, format);
279         emit(closure, hookid, "request", "{si ss ss ss so* ss*}", format, ap,
280                                         "index", xreq->hookindex,
281                                         "api", xreq->api,
282                                         "verb", xreq->verb,
283                                         "action", action,
284                                         "credentials", cred,
285                                         "session", session);
286         va_end(ap);
287 }
288
289 static void hook_xreq_begin(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
290 {
291         hook_xreq(closure, hookid, xreq, "begin", NULL);
292 }
293
294 static void hook_xreq_end(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
295 {
296         hook_xreq(closure, hookid, xreq, "end", NULL);
297 }
298
299 static void hook_xreq_json(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct json_object *obj)
300 {
301         hook_xreq(closure, hookid, xreq, "json", "{sO?}",
302                                                 "result", obj);
303 }
304
305 static void hook_xreq_get(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *name, struct afb_arg arg)
306 {
307         hook_xreq(closure, hookid, xreq, "get", "{ss? ss? ss? ss?}",
308                                                 "query", name,
309                                                 "name", arg.name,
310                                                 "value", arg.value,
311                                                 "path", arg.path);
312 }
313
314 static void hook_xreq_success(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct json_object *obj, const char *info)
315 {
316         hook_xreq(closure, hookid, xreq, "success", "{sO? ss?}",
317                                                 "result", obj,
318                                                 "info", info);
319 }
320
321 static void hook_xreq_fail(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *status, const char *info)
322 {
323         hook_xreq(closure, hookid, xreq, "fail", "{ss? ss?}",
324                                                 "status", status,
325                                                 "info", info);
326 }
327
328 static void hook_xreq_context_get(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, void *value)
329 {
330         hook_xreq(closure, hookid, xreq, "context_get", NULL);
331 }
332
333 static void hook_xreq_context_set(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, void *value, void (*free_value)(void*))
334 {
335         hook_xreq(closure, hookid, xreq, "context_set", NULL);
336 }
337
338 static void hook_xreq_addref(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
339 {
340         hook_xreq(closure, hookid, xreq, "addref", NULL);
341 }
342
343 static void hook_xreq_unref(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
344 {
345         hook_xreq(closure, hookid, xreq, "unref", NULL);
346 }
347
348 static void hook_xreq_session_close(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
349 {
350         hook_xreq(closure, hookid, xreq, "session_close", NULL);
351 }
352
353 static void hook_xreq_session_set_LOA(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, unsigned level, int result)
354 {
355         hook_xreq(closure, hookid, xreq, "session_set_LOA", "{si si}",
356                                         "level", level,
357                                         "result", result);
358 }
359
360 static void hook_xreq_subscribe(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct afb_event event, int result)
361 {
362         hook_xreq(closure, hookid, xreq, "subscribe", "{s{ss si} si}",
363                                         "event",
364                                                 "name", afb_evt_event_name(event),
365                                                 "id", afb_evt_event_id(event),
366                                         "result", result);
367 }
368
369 static void hook_xreq_unsubscribe(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct afb_event event, int result)
370 {
371         hook_xreq(closure, hookid, xreq, "unsubscribe", "{s{ss? si} si}",
372                                         "event",
373                                                 "name", afb_evt_event_name(event),
374                                                 "id", afb_evt_event_id(event),
375                                         "result", result);
376 }
377
378 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)
379 {
380         hook_xreq(closure, hookid, xreq, "subcall", "{ss? ss? sO?}",
381                                         "api", api,
382                                         "verb", verb,
383                                         "args", args);
384 }
385
386 static void hook_xreq_subcall_result(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, int status, struct json_object *result)
387 {
388         hook_xreq(closure, hookid, xreq, "subcall_result", "{si sO?}",
389                                         "status", status,
390                                         "result", result);
391 }
392
393 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)
394 {
395         hook_xreq(closure, hookid, xreq, "subcallsync", "{ss? ss? sO?}",
396                                         "api", api,
397                                         "verb", verb,
398                                         "args", args);
399 }
400
401 static void hook_xreq_subcallsync_result(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, int status, struct json_object *result)
402 {
403         hook_xreq(closure, hookid, xreq, "subcallsync_result", "{si sO?}",
404                                         "status", status,
405                                         "result", result);
406 }
407
408 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)
409 {
410         struct json_object *pos;
411         int len;
412         char *msg;
413         va_list ap;
414
415         pos = NULL;
416         msg = NULL;
417
418         va_copy(ap, args);
419         len = vasprintf(&msg, fmt, ap);
420         va_end(ap);
421
422         if (file)
423                 wrap_json_pack(&pos, "{ss si ss*}", "file", file, "line", line, "function", func);
424
425         hook_xreq(closure, hookid, xreq, "vverbose", "{si ss* ss? so*}",
426                                         "level", level,
427                                         "type", verbosity_level_name(level),
428                                         len < 0 ? "format" : "message", len < 0 ? fmt : msg,
429                                         "position", pos);
430
431         free(msg);
432 }
433
434 static void hook_xreq_store(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct afb_stored_req *sreq)
435 {
436         hook_xreq(closure, hookid, xreq, "store", NULL);
437 }
438
439 static void hook_xreq_unstore(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
440 {
441         hook_xreq(closure, hookid, xreq, "unstore", NULL);
442 }
443
444 static void hook_xreq_subcall_req(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args)
445 {
446         hook_xreq(closure, hookid, xreq, "subcall_req", "{ss? ss? sO?}",
447                                         "api", api,
448                                         "verb", verb,
449                                         "args", args);
450 }
451
452 static void hook_xreq_subcall_req_result(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, int status, struct json_object *result)
453 {
454         hook_xreq(closure, hookid, xreq, "subcall_req_result", "{si sO?}",
455                                         "status", status,
456                                         "result", result);
457 }
458
459 static struct afb_hook_xreq_itf hook_xreq_itf = {
460         .hook_xreq_begin = hook_xreq_begin,
461         .hook_xreq_end = hook_xreq_end,
462         .hook_xreq_json = hook_xreq_json,
463         .hook_xreq_get = hook_xreq_get,
464         .hook_xreq_success = hook_xreq_success,
465         .hook_xreq_fail = hook_xreq_fail,
466         .hook_xreq_context_get = hook_xreq_context_get,
467         .hook_xreq_context_set = hook_xreq_context_set,
468         .hook_xreq_addref = hook_xreq_addref,
469         .hook_xreq_unref = hook_xreq_unref,
470         .hook_xreq_session_close = hook_xreq_session_close,
471         .hook_xreq_session_set_LOA = hook_xreq_session_set_LOA,
472         .hook_xreq_subscribe = hook_xreq_subscribe,
473         .hook_xreq_unsubscribe = hook_xreq_unsubscribe,
474         .hook_xreq_subcall = hook_xreq_subcall,
475         .hook_xreq_subcall_result = hook_xreq_subcall_result,
476         .hook_xreq_subcallsync = hook_xreq_subcallsync,
477         .hook_xreq_subcallsync_result = hook_xreq_subcallsync_result,
478         .hook_xreq_vverbose = hook_xreq_vverbose,
479         .hook_xreq_store = hook_xreq_store,
480         .hook_xreq_unstore = hook_xreq_unstore,
481         .hook_xreq_subcall_req = hook_xreq_subcall_req,
482         .hook_xreq_subcall_req_result = hook_xreq_subcall_req_result
483 };
484
485 /*******************************************************************************/
486 /*****  trace the daemon interface                                         *****/
487 /*******************************************************************************/
488
489 static struct flag ditf_flags[] = { /* must be sorted by names */
490                 { "all",                        afb_hook_flags_ditf_all },
491                 { "common",                     afb_hook_flags_ditf_common },
492                 { "event_broadcast_after",      afb_hook_flag_ditf_event_broadcast_after },
493                 { "event_broadcast_before",     afb_hook_flag_ditf_event_broadcast_before },
494                 { "event_make",                 afb_hook_flag_ditf_event_make },
495                 { "extra",                      afb_hook_flags_ditf_extra },
496                 { "get_event_loop",             afb_hook_flag_ditf_get_event_loop },
497                 { "get_system_bus",             afb_hook_flag_ditf_get_system_bus },
498                 { "get_user_bus",               afb_hook_flag_ditf_get_user_bus },
499                 { "queue_job",                  afb_hook_flag_ditf_queue_job },
500                 { "require_api",                afb_hook_flag_ditf_require_api },
501                 { "require_api_result",         afb_hook_flag_ditf_require_api_result },
502                 { "rootdir_get_fd",             afb_hook_flag_ditf_rootdir_get_fd },
503                 { "rootdir_open_locale",        afb_hook_flag_ditf_rootdir_open_locale },
504                 { "unstore_req",                afb_hook_flag_ditf_unstore_req },
505                 { "vverbose",                   afb_hook_flag_ditf_vverbose },
506 };
507
508 /* get the ditf value for flag of 'name' */
509 static int get_ditf_flag(const char *name)
510 {
511         return get_flag(name, ditf_flags, (int)(sizeof ditf_flags / sizeof *ditf_flags));
512 }
513
514
515 static void hook_ditf(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *action, const char *format, ...)
516 {
517         va_list ap;
518
519         va_start(ap, format);
520         emit(closure, hookid, "daemon", "{ss ss}", format, ap,
521                                         "api", ditf->api,
522                                         "action", action);
523         va_end(ap);
524 }
525
526 static void hook_ditf_event_broadcast_before(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *name, struct json_object *object)
527 {
528         hook_ditf(closure, hookid, ditf, "event_broadcast_before", "{ss sO*}",
529                         "name", name, "data", object);
530 }
531
532 static void hook_ditf_event_broadcast_after(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *name, struct json_object *object, int result)
533 {
534         hook_ditf(closure, hookid, ditf, "event_broadcast_after", "{ss sO* si}",
535                         "name", name, "data", object, "result", result);
536 }
537
538 static void hook_ditf_get_event_loop(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, struct sd_event *result)
539 {
540         hook_ditf(closure, hookid, ditf, "get_event_loop", NULL);
541 }
542
543 static void hook_ditf_get_user_bus(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, struct sd_bus *result)
544 {
545         hook_ditf(closure, hookid, ditf, "get_user_bus", NULL);
546 }
547
548 static void hook_ditf_get_system_bus(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, struct sd_bus *result)
549 {
550         hook_ditf(closure, hookid, ditf, "get_system_bus", NULL);
551 }
552
553 static void hook_ditf_vverbose(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, int level, const char *file, int line, const char *function, const char *fmt, va_list args)
554 {
555         struct json_object *pos;
556         int len;
557         char *msg;
558         va_list ap;
559
560         pos = NULL;
561         msg = NULL;
562
563         va_copy(ap, args);
564         len = vasprintf(&msg, fmt, ap);
565         va_end(ap);
566
567         if (file)
568                 wrap_json_pack(&pos, "{ss si ss*}", "file", file, "line", line, "function", function);
569
570         hook_ditf(closure, hookid, ditf, "vverbose", "{si ss* ss? so*}",
571                                         "level", level,
572                                         "type", verbosity_level_name(level),
573                                         len < 0 ? "format" : "message", len < 0 ? fmt : msg,
574                                         "position", pos);
575
576         free(msg);
577 }
578
579 static void hook_ditf_event_make(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *name, struct afb_event result)
580 {
581         hook_ditf(closure, hookid, ditf, "event_make", "{ss ss si}",
582                         "name", name, "event", afb_evt_event_name(result), "id", afb_evt_event_id(result));
583 }
584
585 static void hook_ditf_rootdir_get_fd(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, int result)
586 {
587         char path[PATH_MAX];
588
589         if (result >= 0) {
590                 sprintf(path, "/proc/self/fd/%d", result);
591                 readlink(path, path, sizeof path);
592         }
593
594         hook_ditf(closure, hookid, ditf, "rootdir_get_fd", "{ss}",
595                         result < 0 ? "path" : "error",
596                         result < 0 ? strerror(errno) : path);
597 }
598
599 static void hook_ditf_rootdir_open_locale(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *filename, int flags, const char *locale, int result)
600 {
601         char path[PATH_MAX];
602
603         if (result >= 0) {
604                 sprintf(path, "/proc/self/fd/%d", result);
605                 readlink(path, path, sizeof path);
606         }
607
608         hook_ditf(closure, hookid, ditf, "rootdir_open_locale", "{ss si ss* ss}",
609                         "file", filename,
610                         "flags", flags,
611                         "locale", locale,
612                         result < 0 ? "path" : "error",
613                         result < 0 ? strerror(errno) : path);
614 }
615
616 static void hook_ditf_queue_job(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, void (*callback)(int signum, void *arg), void *argument, void *group, int timeout, int result)
617 {
618         hook_ditf(closure, hookid, ditf, "queue_job", "{ss}", "result", result);
619 }
620
621 static void hook_ditf_unstore_req(void * closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, struct afb_stored_req *sreq)
622 {
623         hook_ditf(closure, hookid, ditf, "unstore_req", NULL);
624 }
625
626 static void hook_ditf_require_api(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *name, int initialized)
627 {
628         hook_ditf(closure, hookid, ditf, "require_api", "{ss sb}", "name", name, "initialized", initialized);
629 }
630
631 static void hook_ditf_require_api_result(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *name, int initialized, int result)
632 {
633         hook_ditf(closure, hookid, ditf, "require_api_result", "{ss sb si}", "name", name, "initialized", initialized, "result", result);
634 }
635
636 static struct afb_hook_ditf_itf hook_ditf_itf = {
637         .hook_ditf_event_broadcast_before = hook_ditf_event_broadcast_before,
638         .hook_ditf_event_broadcast_after = hook_ditf_event_broadcast_after,
639         .hook_ditf_get_event_loop = hook_ditf_get_event_loop,
640         .hook_ditf_get_user_bus = hook_ditf_get_user_bus,
641         .hook_ditf_get_system_bus = hook_ditf_get_system_bus,
642         .hook_ditf_vverbose = hook_ditf_vverbose,
643         .hook_ditf_event_make = hook_ditf_event_make,
644         .hook_ditf_rootdir_get_fd = hook_ditf_rootdir_get_fd,
645         .hook_ditf_rootdir_open_locale = hook_ditf_rootdir_open_locale,
646         .hook_ditf_queue_job = hook_ditf_queue_job,
647         .hook_ditf_unstore_req = hook_ditf_unstore_req,
648         .hook_ditf_require_api = hook_ditf_require_api,
649         .hook_ditf_require_api_result = hook_ditf_require_api_result
650 };
651
652 /*******************************************************************************/
653 /*****  trace the services                                                 *****/
654 /*******************************************************************************/
655
656 static struct flag svc_flags[] = { /* must be sorted by names */
657                 { "all",                afb_hook_flags_svc_all },
658                 { "call",               afb_hook_flag_svc_call },
659                 { "call_result",        afb_hook_flag_svc_call_result },
660                 { "callsync",           afb_hook_flag_svc_callsync },
661                 { "callsync_result",    afb_hook_flag_svc_callsync_result },
662                 { "on_event_after",     afb_hook_flag_svc_on_event_after },
663                 { "on_event_before",    afb_hook_flag_svc_on_event_before },
664                 { "start_after",        afb_hook_flag_svc_start_after },
665                 { "start_before",       afb_hook_flag_svc_start_before },
666 };
667
668 /* get the svc value for flag of 'name' */
669 static int get_svc_flag(const char *name)
670 {
671         return get_flag(name, svc_flags, (int)(sizeof svc_flags / sizeof *svc_flags));
672 }
673
674 static void hook_svc(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, const char *action, const char *format, ...)
675 {
676         va_list ap;
677
678         va_start(ap, format);
679         emit(closure, hookid, "service", "{ss ss}", format, ap,
680                                         "api", svc->api,
681                                         "action", action);
682         va_end(ap);
683 }
684
685 static void hook_svc_start_before(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc)
686 {
687         hook_svc(closure, hookid, svc, "start_before", NULL);
688 }
689
690 static void hook_svc_start_after(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, int status)
691 {
692         hook_svc(closure, hookid, svc, "start_after", "{si}", "result", status);
693 }
694
695 static void hook_svc_on_event_before(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, const char *event, int eventid, struct json_object *object)
696 {
697         hook_svc(closure, hookid, svc, "on_event_before", "{ss si sO*}",
698                         "event", event, "id", eventid, "data", object);
699 }
700
701 static void hook_svc_on_event_after(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, const char *event, int eventid, struct json_object *object)
702 {
703         hook_svc(closure, hookid, svc, "on_event_after", "{ss si sO*}",
704                         "event", event, "id", eventid, "data", object);
705 }
706
707 static void hook_svc_call(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, const char *api, const char *verb, struct json_object *args)
708 {
709         hook_svc(closure, hookid, svc, "call", "{ss ss sO*}",
710                         "api", api, "verb", verb, "args", args);
711 }
712
713 static void hook_svc_call_result(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, int status, struct json_object *result)
714 {
715         hook_svc(closure, hookid, svc, "call_result", "{si sO*}",
716                         "status", status, "result", result);
717 }
718
719 static void hook_svc_callsync(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, const char *api, const char *verb, struct json_object *args)
720 {
721         hook_svc(closure, hookid, svc, "callsync", "{ss ss sO*}",
722                         "api", api, "verb", verb, "args", args);
723 }
724
725 static void hook_svc_callsync_result(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, int status, struct json_object *result)
726 {
727         hook_svc(closure, hookid, svc, "callsync_result", "{si sO*}",
728                         "status", status, "result", result);
729 }
730
731 static struct afb_hook_svc_itf hook_svc_itf = {
732         .hook_svc_start_before = hook_svc_start_before,
733         .hook_svc_start_after = hook_svc_start_after,
734         .hook_svc_on_event_before = hook_svc_on_event_before,
735         .hook_svc_on_event_after = hook_svc_on_event_after,
736         .hook_svc_call = hook_svc_call,
737         .hook_svc_call_result = hook_svc_call_result,
738         .hook_svc_callsync = hook_svc_callsync,
739         .hook_svc_callsync_result = hook_svc_callsync_result
740 };
741
742 /*******************************************************************************/
743 /*****  trace the events                                                   *****/
744 /*******************************************************************************/
745
746 static struct flag evt_flags[] = { /* must be sorted by names */
747                 { "all",                afb_hook_flags_evt_all },
748                 { "broadcast_after",    afb_hook_flag_evt_broadcast_after },
749                 { "broadcast_before",   afb_hook_flag_evt_broadcast_before },
750                 { "common",             afb_hook_flags_evt_common },
751                 { "create",             afb_hook_flag_evt_create },
752                 { "drop",               afb_hook_flag_evt_drop },
753                 { "extra",              afb_hook_flags_evt_extra },
754                 { "name",               afb_hook_flag_evt_name },
755                 { "push_after",         afb_hook_flag_evt_push_after },
756                 { "push_before",        afb_hook_flag_evt_push_before },
757 };
758
759 /* get the evt value for flag of 'name' */
760 static int get_evt_flag(const char *name)
761 {
762         return get_flag(name, evt_flags, (int)(sizeof evt_flags / sizeof *evt_flags));
763 }
764
765 static void hook_evt(void *closure, const struct afb_hookid *hookid, const char *evt, int id, const char *action, const char *format, ...)
766 {
767         va_list ap;
768
769         va_start(ap, format);
770         emit(closure, hookid, "event", "{si ss ss}", format, ap,
771                                         "id", id,
772                                         "name", evt,
773                                         "action", action);
774         va_end(ap);
775 }
776
777 static void hook_evt_create(void *closure, const struct afb_hookid *hookid, const char *evt, int id)
778 {
779         hook_evt(closure, hookid, evt, id, "create", NULL);
780 }
781
782 static void hook_evt_push_before(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj)
783 {
784         hook_evt(closure, hookid, evt, id, "push_before", "{sO*}", "data", obj);
785 }
786
787
788 static void hook_evt_push_after(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj, int result)
789 {
790         hook_evt(closure, hookid, evt, id, "push_after", "{sO* si}", "data", obj, "result", result);
791 }
792
793 static void hook_evt_broadcast_before(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj)
794 {
795         hook_evt(closure, hookid, evt, id, "broadcast_before", "{sO*}", "data", obj);
796 }
797
798 static void hook_evt_broadcast_after(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj, int result)
799 {
800         hook_evt(closure, hookid, evt, id, "broadcast_after", "{sO* si}", "data", obj, "result", result);
801 }
802
803 static void hook_evt_name(void *closure, const struct afb_hookid *hookid, const char *evt, int id)
804 {
805         hook_evt(closure, hookid, evt, id, "name", NULL);
806 }
807
808 static void hook_evt_drop(void *closure, const struct afb_hookid *hookid, const char *evt, int id)
809 {
810         hook_evt(closure, hookid, evt, id, "drop", NULL);
811 }
812
813 static struct afb_hook_evt_itf hook_evt_itf = {
814         .hook_evt_create = hook_evt_create,
815         .hook_evt_push_before = hook_evt_push_before,
816         .hook_evt_push_after = hook_evt_push_after,
817         .hook_evt_broadcast_before = hook_evt_broadcast_before,
818         .hook_evt_broadcast_after = hook_evt_broadcast_after,
819         .hook_evt_name = hook_evt_name,
820         .hook_evt_drop = hook_evt_drop
821 };
822
823 /*******************************************************************************/
824 /*****  abstract types                                                     *****/
825 /*******************************************************************************/
826
827 static
828 struct
829 {
830         const char *name;
831         void (*unref)(void*);
832         int (*get_flag)(const char*);
833 }
834 abstracting[Trace_Type_Count] =
835 {
836         [Trace_Type_Xreq] =
837         {
838                 .name = "request",
839                 .unref =  (void(*)(void*))afb_hook_unref_xreq,
840                 .get_flag = get_xreq_flag
841         },
842         [Trace_Type_Ditf] =
843         {
844                 .name = "daemon",
845                 .unref =  (void(*)(void*))afb_hook_unref_ditf,
846                 .get_flag = get_ditf_flag
847         },
848         [Trace_Type_Svc] =
849         {
850                 .name = "service",
851                 .unref =  (void(*)(void*))afb_hook_unref_svc,
852                 .get_flag = get_svc_flag
853         },
854         [Trace_Type_Evt] =
855         {
856                 .name = "event",
857                 .unref =  (void(*)(void*))afb_hook_unref_evt,
858                 .get_flag = get_evt_flag
859         }
860 };
861
862 /*******************************************************************************/
863 /*****  handle trace data                                                  *****/
864 /*******************************************************************************/
865
866 /* drop hooks of 'trace' matching 'tag' and 'event' and 'session' */
867 static void trace_unhook(struct afb_trace *trace, struct tag *tag, struct event *event, struct session *session)
868 {
869         int i;
870         struct hook *hook, **prev;
871
872         /* remove any event */
873         for (i = 0 ; i < Trace_Type_Count ; i++) {
874                 prev = &trace->hooks[i];
875                 while ((hook = *prev)) {
876                         if ((tag && tag != hook->tag)
877                          || (event && event != hook->event)
878                          || (session && session != hook->session))
879                                 prev = &hook->next;
880                         else {
881                                 *prev = hook->next;
882                                 abstracting[i].unref(hook->handler);
883                                 free(hook);
884                         }
885                 }
886         }
887 }
888
889 /* cleanup: removes unused tags, events and sessions of the 'trace' */
890 static void trace_cleanup(struct afb_trace *trace)
891 {
892         int i;
893         struct hook *hook;
894         struct tag *tag, **ptag;
895         struct event *event, **pevent;
896         struct session *session, **psession;
897
898         /* clean sessions */
899         psession = &trace->sessions;
900         while ((session = *psession)) {
901                 /* search for session */
902                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++) 
903                         for (hook = trace->hooks[i] ; hook && hook->session != session ; hook = hook->next);
904                 /* keep or free whether used or not */
905                 if (hook)
906                         psession = &session->next;
907                 else {
908                         *psession = session->next;
909                         if (__atomic_exchange_n(&session->trace, NULL, __ATOMIC_RELAXED))
910                                 afb_session_set_cookie(session->session, session, NULL, NULL);
911                         free(session);
912                 }
913         }
914         /* clean tags */
915         ptag = &trace->tags;
916         while ((tag = *ptag)) {
917                 /* search for tag */
918                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++) 
919                         for (hook = trace->hooks[i] ; hook && hook->tag != tag ; hook = hook->next);
920                 /* keep or free whether used or not */
921                 if (hook)
922                         ptag = &tag->next;
923                 else {
924                         *ptag = tag->next;
925                         free(tag);
926                 }
927         }
928         /* clean events */
929         pevent = &trace->events;
930         while ((event = *pevent)) {
931                 /* search for event */
932                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++) 
933                         for (hook = trace->hooks[i] ; hook && hook->event != event ; hook = hook->next);
934                 /* keep or free whether used or not */
935                 if (hook)
936                         pevent = &event->next;
937                 else {
938                         *pevent = event->next;
939                         afb_event_drop(event->event);
940                         free(event);
941                 }
942         }
943 }
944
945 /* callback at end of traced session */
946 static void free_session_cookie(void *cookie)
947 {
948         struct session *session = cookie;
949         struct afb_trace *trace = __atomic_exchange_n(&session->trace, NULL, __ATOMIC_RELAXED);
950         if (trace) {
951                 pthread_mutex_lock(&trace->mutex);
952                 trace_unhook(trace, NULL, NULL, session);
953                 trace_cleanup(trace);
954                 pthread_mutex_unlock(&trace->mutex);
955         }
956 }
957
958 /*
959  * Get the tag of 'name' within 'trace'.
960  * If 'alloc' isn't zero, create the tag and add it.
961  */
962 static struct tag *trace_get_tag(struct afb_trace *trace, const char *name, int alloc)
963 {
964         struct tag *tag;
965
966         /* search the tag of 'name' */
967         tag = trace->tags;
968         while (tag && strcmp(name, tag->tag))
969                 tag = tag->next;
970
971         if (!tag && alloc) {
972                 /* creation if needed */
973                 tag = malloc(sizeof * tag + strlen(name));
974                 if (tag) {
975                         strcpy(tag->tag, name);
976                         tag->next = trace->tags;
977                         trace->tags = tag;
978                 }
979         }
980         return tag;
981 }
982
983 /*
984  * Get the event of 'name' within 'trace'.
985  * If 'alloc' isn't zero, create the event and add it.
986  */
987 static struct event *trace_get_event(struct afb_trace *trace, const char *name, int alloc)
988 {
989         struct event *event;
990
991         /* search the event */
992         event = trace->events;
993         while (event && strcmp(afb_event_name(event->event), name))
994                 event = event->next;
995
996         if (!event && alloc) {
997                 event = malloc(sizeof * event);
998                 if (event) {
999                         event->event = trace->daemon->itf->event_make(trace->daemon->closure, name);
1000                         if (afb_event_is_valid(event->event)) {
1001                                 event->next = trace->events;
1002                                 trace->events = event;
1003                         } else {
1004                                 free(event);
1005                                 event = NULL;
1006                         }
1007                 }
1008         }
1009         return event;
1010 }
1011
1012 /*
1013  * Get the session of 'value' within 'trace'.
1014  * If 'alloc' isn't zero, create the session and add it.
1015  */
1016 static struct session *trace_get_session(struct afb_trace *trace, struct afb_session *value, int alloc)
1017 {
1018         struct session *session;
1019
1020         /* search the session */
1021         session = trace->sessions;
1022         while (session && session->session != value)
1023                 session = session->next;
1024
1025         if (!session && alloc) {
1026                 session = malloc(sizeof * session);
1027                 if (session) {
1028                         session->session = value;
1029                         session->trace = NULL;
1030                         session->next = trace->sessions;
1031                         trace->sessions = session;
1032                 }
1033         }
1034         return session;
1035 }
1036
1037 /*
1038  * Get the session of 'uuid' within 'trace'.
1039  * If 'alloc' isn't zero, create the session and add it.
1040  */
1041 static struct session *trace_get_session_by_uuid(struct afb_trace *trace, const char *uuid, int alloc)
1042 {
1043         struct afb_session *session;
1044         int created;
1045
1046         session = afb_session_get(uuid, alloc ? &created : NULL);
1047         return session ? trace_get_session(trace, session, alloc) : NULL;
1048 }
1049
1050 static struct hook *trace_make_detached_hook(struct afb_trace *trace, const char *event, const char *tag)
1051 {
1052         struct hook *hook;
1053
1054         tag = tag ?: DEFAULT_TAG_NAME;
1055         event = event ?: DEFAULT_EVENT_NAME;
1056         hook = malloc(sizeof *hook);
1057         if (hook) {
1058                 hook->tag = trace_get_tag(trace, tag, 1);
1059                 hook->event = trace_get_event(trace, event, 1);
1060                 hook->session = NULL;
1061                 hook->handler = NULL;
1062         }
1063         return hook;
1064 }
1065
1066 static void trace_attach_hook(struct afb_trace *trace, struct hook *hook, enum trace_type type)
1067 {
1068         struct session *session = hook->session;
1069         hook->next = trace->hooks[type];
1070         trace->hooks[type] = hook;
1071         if (session && !session->trace) {
1072                 session->trace = trace;
1073                 afb_session_set_cookie(session->session, session, session, free_session_cookie);
1074         }
1075 }
1076
1077 /*******************************************************************************/
1078 /*****  handle client requests                                             *****/
1079 /*******************************************************************************/
1080
1081 struct context
1082 {
1083         struct afb_trace *trace;
1084         struct afb_req req;
1085         char *errors;
1086 };
1087
1088 struct desc
1089 {
1090         struct context *context;
1091         const char *name;
1092         const char *tag;
1093         const char *session;
1094         const char *api;
1095         const char *verb;
1096         const char *pattern;
1097         int flags[Trace_Type_Count];
1098 };
1099
1100
1101 static void addhook(struct desc *desc, enum trace_type type)
1102 {
1103         struct hook *hook;
1104         struct session *session;
1105         struct afb_session *bind;
1106         struct afb_trace *trace = desc->context->trace;
1107
1108         /* check permission for bound traces */
1109         bind = trace->bound;
1110         if (bind != NULL) {
1111                 if (type != Trace_Type_Xreq) {
1112                         ctxt_error(&desc->context->errors, "tracing %s is forbidden", abstracting[type].name);
1113                         return;
1114                 }
1115                 if (desc->session) {
1116                         ctxt_error(&desc->context->errors, "setting session is forbidden");
1117                         return;
1118                 }
1119         }
1120
1121         /* allocate the hook */
1122         hook = trace_make_detached_hook(trace, desc->name, desc->tag);
1123         if (!hook) {
1124                 ctxt_error(&desc->context->errors, "allocation of hook failed");
1125                 return;
1126         }
1127
1128         /* create the hook handler */
1129         switch (type) {
1130         case Trace_Type_Xreq:
1131                 if (desc->session) {
1132                         session = trace_get_session_by_uuid(trace, desc->session, 1);
1133                         if (!session) {
1134                                 ctxt_error(&desc->context->errors, "allocation of session failed");
1135                                 free(hook);
1136                                 return;
1137                         }
1138                         bind = session->session;
1139                 }
1140                 hook->handler = afb_hook_create_xreq(desc->api, desc->verb, bind,
1141                                 desc->flags[type], &hook_xreq_itf, hook);
1142                 break;
1143         case Trace_Type_Ditf:
1144                 hook->handler = afb_hook_create_ditf(desc->api, desc->flags[type], &hook_ditf_itf, hook);
1145                 break;
1146         case Trace_Type_Svc:
1147                 hook->handler = afb_hook_create_svc(desc->api, desc->flags[type], &hook_svc_itf, hook);
1148                 break;
1149         case Trace_Type_Evt:
1150                 hook->handler = afb_hook_create_evt(desc->pattern, desc->flags[type], &hook_evt_itf, hook);
1151                 break;
1152         default:
1153                 break;
1154         }
1155         if (!hook->handler) {
1156                 ctxt_error(&desc->context->errors, "creation of hook failed");
1157                 free(hook);
1158                 return;
1159         }
1160
1161         /* attach and activate the hook */
1162         afb_req_subscribe(desc->context->req, hook->event->event);
1163         trace_attach_hook(trace, hook, type);
1164 }
1165
1166 static void addhooks(struct desc *desc)
1167 {
1168         int i;
1169
1170         for (i = 0 ; i < Trace_Type_Count ; i++) {
1171                 if (desc->flags[i])
1172                         addhook(desc, i);
1173         }
1174 }
1175
1176 static void add_flags(void *closure, struct json_object *object, enum trace_type type)
1177 {
1178         int value;
1179         const char *name, *queried;
1180         struct desc *desc = closure;
1181
1182         if (wrap_json_unpack(object, "s", &name))
1183                 ctxt_error(&desc->context->errors, "unexpected %s value %s",
1184                                         abstracting[type].name,
1185                                         json_object_to_json_string(object));
1186         else {
1187                 queried = (name[0] == '*' && !name[1]) ? "all" : name;
1188                 value = abstracting[type].get_flag(queried);
1189                 if (value)
1190                         desc->flags[type] |= value;
1191                 else
1192                         ctxt_error(&desc->context->errors, "unknown %s name %s",
1193                                         abstracting[type].name, name);
1194         }
1195 }
1196
1197 static void add_xreq_flags(void *closure, struct json_object *object)
1198 {
1199         add_flags(closure, object, Trace_Type_Xreq);
1200 }
1201
1202 static void add_ditf_flags(void *closure, struct json_object *object)
1203 {
1204         add_flags(closure, object, Trace_Type_Ditf);
1205 }
1206
1207 static void add_svc_flags(void *closure, struct json_object *object)
1208 {
1209         add_flags(closure, object, Trace_Type_Svc);
1210 }
1211
1212 static void add_evt_flags(void *closure, struct json_object *object)
1213 {
1214         add_flags(closure, object, Trace_Type_Evt);
1215 }
1216
1217 /* add hooks */
1218 static void add(void *closure, struct json_object *object)
1219 {
1220         int rc;
1221         struct desc desc;
1222         struct json_object *request, *event, *daemon, *service, *sub;
1223
1224         memcpy (&desc, closure, sizeof desc);
1225         request = event = daemon = service = sub = NULL;
1226
1227         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}",
1228                         "name", &desc.name,
1229                         "tag", &desc.tag,
1230                         "api", &desc.api,
1231                         "verb", &desc.verb,
1232                         "session", &desc.session,
1233                         "pattern", &desc.pattern,
1234                         "request", &request,
1235                         "daemon", &daemon,
1236                         "service", &service,
1237                         "event", &event,
1238                         "for", &sub);
1239
1240         if (!rc) {
1241                 /* replace stars */
1242                 if (desc.api && desc.api[0] == '*' && !desc.api[1])
1243                         desc.api = NULL;
1244
1245                 if (desc.verb && desc.verb[0] == '*' && !desc.verb[1])
1246                         desc.verb = NULL;
1247
1248                 if (desc.session && desc.session[0] == '*' && !desc.session[1])
1249                         desc.session = NULL;
1250
1251                 /* get what is expected */
1252                 if (request)
1253                         wrap_json_optarray_for_all(request, add_xreq_flags, &desc);
1254
1255                 if (daemon)
1256                         wrap_json_optarray_for_all(daemon, add_ditf_flags, &desc);
1257
1258                 if (service)
1259                         wrap_json_optarray_for_all(service, add_svc_flags, &desc);
1260
1261                 if (event)
1262                         wrap_json_optarray_for_all(event, add_evt_flags, &desc);
1263
1264                 /* apply */
1265                 if (sub)
1266                         wrap_json_optarray_for_all(sub, add, &desc);
1267                 else
1268                         addhooks(&desc);
1269         }
1270         else {
1271                 wrap_json_optarray_for_all(object, add_xreq_flags, &desc);
1272                 addhooks(&desc);
1273         }
1274 }
1275
1276 /* drop hooks of given tag */
1277 static void drop_tag(void *closure, struct json_object *object)
1278 {
1279         int rc;
1280         struct context *context = closure;
1281         struct tag *tag;
1282         const char *name;
1283
1284         rc = wrap_json_unpack(object, "s", &name);
1285         if (rc)
1286                 ctxt_error(&context->errors, "unexpected tag value %s", json_object_to_json_string(object));
1287         else {
1288                 tag = trace_get_tag(context->trace, name, 0);
1289                 if (!tag)
1290                         ctxt_error(&context->errors, "tag %s not found", name);
1291                 else
1292                         trace_unhook(context->trace, tag, NULL, NULL);
1293         }
1294 }
1295
1296 /* drop hooks of given event */
1297 static void drop_event(void *closure, struct json_object *object)
1298 {
1299         int rc;
1300         struct context *context = closure;
1301         struct event *event;
1302         const char *name;
1303
1304         rc = wrap_json_unpack(object, "s", &name);
1305         if (rc)
1306                 ctxt_error(&context->errors, "unexpected event value %s", json_object_to_json_string(object));
1307         else {
1308                 event = trace_get_event(context->trace, name, 0);
1309                 if (!event)
1310                         ctxt_error(&context->errors, "event %s not found", name);
1311                 else
1312                         trace_unhook(context->trace, NULL, event, NULL);
1313         }
1314 }
1315
1316 /* drop hooks of given session */
1317 static void drop_session(void *closure, struct json_object *object)
1318 {
1319         int rc;
1320         struct context *context = closure;
1321         struct session *session;
1322         const char *uuid;
1323
1324         rc = wrap_json_unpack(object, "s", &uuid);
1325         if (rc)
1326                 ctxt_error(&context->errors, "unexpected session value %s", json_object_to_json_string(object));
1327         else {
1328                 session = trace_get_session_by_uuid(context->trace, uuid, 0);
1329                 if (!session)
1330                         ctxt_error(&context->errors, "session %s not found", uuid);
1331                 else
1332                         trace_unhook(context->trace, NULL, NULL, session);
1333         }
1334 }
1335
1336 /*******************************************************************************/
1337 /*****  public interface                                                   *****/
1338 /*******************************************************************************/
1339
1340 /* allocates an afb_trace instance */
1341 struct afb_trace *afb_trace_create(struct afb_daemon *daemon, struct afb_session *bound)
1342 {
1343         struct afb_trace *trace;
1344
1345         assert(daemon);
1346
1347         trace = calloc(1, sizeof *trace);
1348         if (trace) {
1349                 trace->refcount = 1;
1350                 trace->bound = bound;
1351                 trace->daemon = daemon;
1352                 pthread_mutex_init(&trace->mutex, NULL);
1353         }
1354         return trace;
1355 }
1356
1357 /* add a reference to the trace */
1358 void afb_trace_addref(struct afb_trace *trace)
1359 {
1360         __atomic_add_fetch(&trace->refcount, 1, __ATOMIC_RELAXED);
1361 }
1362
1363 /* drop one reference to the trace */
1364 void afb_trace_unref(struct afb_trace *trace)
1365 {
1366         if (trace && !__atomic_sub_fetch(&trace->refcount, 1, __ATOMIC_RELAXED)) {
1367                 /* clean hooks */
1368                 trace_unhook(trace, NULL, NULL, NULL);
1369                 trace_cleanup(trace);
1370                 pthread_mutex_destroy(&trace->mutex);
1371                 free(trace);
1372         }
1373 }
1374
1375 /* add traces */
1376 int afb_trace_add(struct afb_req req, struct json_object *args, struct afb_trace *trace)
1377 {
1378         struct context context;
1379         struct desc desc;
1380
1381         memset(&context, 0, sizeof context);
1382         context.trace = trace;
1383         context.req = req;
1384
1385         memset(&desc, 0, sizeof desc);
1386         desc.context = &context;
1387
1388         pthread_mutex_lock(&trace->mutex);
1389         wrap_json_optarray_for_all(args, add, &desc);
1390         pthread_mutex_unlock(&trace->mutex);
1391
1392         if (!context.errors)
1393                 return 0;
1394
1395         afb_req_fail(req, "error-detected", context.errors);
1396         free(context.errors);
1397         return -1;
1398 }
1399
1400 /* drop traces */
1401 extern int afb_trace_drop(struct afb_req req, struct json_object *args, struct afb_trace *trace)
1402 {
1403         int rc;
1404         struct context context;
1405         struct json_object *tags, *events, *sessions;
1406
1407         memset(&context, 0, sizeof context);
1408         context.trace = trace;
1409         context.req = req;
1410
1411         /* special: boolean value */
1412         if (!wrap_json_unpack(args, "b", &rc)) {
1413                 if (rc) {
1414                         pthread_mutex_lock(&trace->mutex);
1415                         trace_unhook(trace, NULL, NULL, NULL);
1416                         trace_cleanup(trace);
1417                         pthread_mutex_unlock(&trace->mutex);
1418                 }
1419                 return 0;
1420         }
1421
1422         tags = events = sessions = NULL;
1423         rc = wrap_json_unpack(args, "{s?o s?o s?o}",
1424                         "event", &events,
1425                         "tag", &tags,
1426                         "session", &sessions);
1427
1428         if (rc < 0 || !(events || tags || sessions)) {
1429                 afb_req_fail(req, "error-detected", "bad drop arguments");
1430                 return -1;
1431         }
1432
1433         pthread_mutex_lock(&trace->mutex);
1434
1435         if (tags)
1436                 wrap_json_optarray_for_all(tags, drop_tag, &context);
1437
1438         if (events)
1439                 wrap_json_optarray_for_all(events, drop_event, &context);
1440
1441         if (sessions)
1442                 wrap_json_optarray_for_all(sessions, drop_session, &context);
1443
1444         trace_cleanup(trace);
1445
1446         pthread_mutex_unlock(&trace->mutex);
1447
1448         if (!context.errors)
1449                 return 0;
1450
1451         afb_req_fail(req, "error-detected", context.errors);
1452         free(context.errors);
1453         return -1;
1454 }
1455