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