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