Remove tailing spaces and TODO file
[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
20 #include <assert.h>
21 #include <string.h>
22 #include <stdarg.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <limits.h>
26 #include <unistd.h>
27 #include <pthread.h>
28
29 #include <json-c/json.h>
30 #include <afb/afb-binding-v2.h>
31
32 #include "afb-hook.h"
33 #include "afb-cred.h"
34 #include "afb-session.h"
35 #include "afb-xreq.h"
36 #include "afb-ditf.h"
37 #include "afb-svc.h"
38 #include "afb-evt.h"
39 #include "afb-trace.h"
40
41 #include "wrap-json.h"
42 #include "verbose.h"
43
44 /*******************************************************************************/
45 /*****  default names                                                      *****/
46 /*******************************************************************************/
47
48 #if !defined(DEFAULT_EVENT_NAME)
49 #  define DEFAULT_EVENT_NAME "trace"
50 #endif
51 #if !defined(DEFAULT_TAG_NAME)
52 #  define DEFAULT_TAG_NAME "trace"
53 #endif
54
55 /*******************************************************************************/
56 /*****  types                                                              *****/
57 /*******************************************************************************/
58
59 /* structure for searching flags by names */
60 struct flag
61 {
62         const char *name;       /** the name */
63         int value;              /** the value */
64 };
65
66 /* struct for tags */
67 struct tag {
68         struct tag *next;       /* link to the next */
69         char tag[1];            /* name of the tag */
70 };
71
72 /* struct for events */
73 struct event {
74         struct event *next;             /* link to the next event */
75         struct afb_event event;         /* the event */
76 };
77
78 /* struct for sessions */
79 struct session {
80         struct session *next;           /* link to the next session */
81         struct afb_session *session;    /* the session */
82         struct afb_trace *trace;        /* the tracer */
83 };
84
85 /* struct for recording hooks */
86 struct hook {
87         struct hook *next;              /* link to next hook */
88         void *handler;                  /* the handler of the hook */
89         struct event *event;            /* the associated event */
90         struct tag *tag;                /* the associated tag */
91         struct session *session;        /* the associated session */
92 };
93
94 /* types of hooks */
95 enum trace_type
96 {
97         Trace_Type_Xreq,        /* xreq hooks */
98         Trace_Type_Ditf,        /* ditf hooks */
99         Trace_Type_Svc,         /* svc hooks */
100         Trace_Type_Evt,         /* evt hooks */
101         Trace_Type_Global,      /* global 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(const struct afb_hookid *hookid)
167 {
168         char ts[50];
169
170         snprintf(ts, sizeof ts, "%llu.%06lu", (long long unsigned)hookid->time.tv_sec, (long unsigned)(hookid->time.tv_nsec / 1000));
171         return json_object_new_string(ts);
172 }
173
174 /* verbosity level name or NULL */
175 static const char *verbosity_level_name(int level)
176 {
177         static const char *names[] = {
178                 "error",
179                 "warning",
180                 "notice",
181                 "info",
182                 "debug"
183         };
184
185         return level >= Log_Level_Error && level <= Log_Level_Debug ? names[level - Log_Level_Error] : NULL;
186 }
187
188 /* generic hook */
189 static void emit(void *closure, const struct afb_hookid *hookid, const char *type, const char *fmt1, const char *fmt2, va_list ap2, ...)
190 {
191         struct hook *hook = closure;
192         struct json_object *event, *data1, *data2;
193         va_list ap1;
194
195         data1 = data2 = event = NULL;
196         va_start(ap1, ap2);
197         wrap_json_vpack(&data1, fmt1, ap1);
198         va_end(ap1);
199         if (fmt2)
200                 wrap_json_vpack(&data2, fmt2, ap2);
201
202         wrap_json_pack(&event, "{so ss ss si so so*}",
203                                         "time", timestamp(hookid),
204                                         "tag", hook->tag->tag,
205                                         "type", type,
206                                         "id", (int)(hookid->id & INT_MAX),
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_hookid *hookid, 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, hookid, "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_hookid *hookid, const struct afb_xreq *xreq)
291 {
292         hook_xreq(closure, hookid, xreq, "begin", NULL);
293 }
294
295 static void hook_xreq_end(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
296 {
297         hook_xreq(closure, hookid, xreq, "end", NULL);
298 }
299
300 static void hook_xreq_json(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, struct json_object *obj)
301 {
302         hook_xreq(closure, hookid, xreq, "json", "{sO?}",
303                                                 "result", obj);
304 }
305
306 static void hook_xreq_get(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *name, struct afb_arg arg)
307 {
308         hook_xreq(closure, hookid, 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_hookid *hookid, const struct afb_xreq *xreq, struct json_object *obj, const char *info)
316 {
317         hook_xreq(closure, hookid, xreq, "success", "{sO? ss?}",
318                                                 "result", obj,
319                                                 "info", info);
320 }
321
322 static void hook_xreq_fail(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *status, const char *info)
323 {
324         hook_xreq(closure, hookid, xreq, "fail", "{ss? ss?}",
325                                                 "status", status,
326                                                 "info", info);
327 }
328
329 static void hook_xreq_context_get(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, void *value)
330 {
331         hook_xreq(closure, hookid, xreq, "context_get", NULL);
332 }
333
334 static void hook_xreq_context_set(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, void *value, void (*free_value)(void*))
335 {
336         hook_xreq(closure, hookid, xreq, "context_set", NULL);
337 }
338
339 static void hook_xreq_addref(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
340 {
341         hook_xreq(closure, hookid, xreq, "addref", NULL);
342 }
343
344 static void hook_xreq_unref(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
345 {
346         hook_xreq(closure, hookid, xreq, "unref", NULL);
347 }
348
349 static void hook_xreq_session_close(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
350 {
351         hook_xreq(closure, hookid, xreq, "session_close", NULL);
352 }
353
354 static void hook_xreq_session_set_LOA(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, unsigned level, int result)
355 {
356         hook_xreq(closure, hookid, 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_hookid *hookid, const struct afb_xreq *xreq, struct afb_event event, int result)
362 {
363         hook_xreq(closure, hookid, 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_hookid *hookid, const struct afb_xreq *xreq, struct afb_event event, int result)
371 {
372         hook_xreq(closure, hookid, 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_hookid *hookid, const struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args)
380 {
381         hook_xreq(closure, hookid, 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_hookid *hookid, const struct afb_xreq *xreq, int status, struct json_object *result)
388 {
389         hook_xreq(closure, hookid, xreq, "subcall_result", "{si sO?}",
390                                         "status", status,
391                                         "result", result);
392 }
393
394 static void hook_xreq_subcallsync(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args)
395 {
396         hook_xreq(closure, hookid, 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_hookid *hookid, const struct afb_xreq *xreq, int status, struct json_object *result)
403 {
404         hook_xreq(closure, hookid, xreq, "subcallsync_result", "{si sO?}",
405                                         "status", status,
406                                         "result", result);
407 }
408
409 static void hook_xreq_vverbose(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, int level, const char *file, int line, const char *func, const char *fmt, va_list args)
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, hookid, 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_hookid *hookid, const struct afb_xreq *xreq, struct afb_stored_req *sreq)
436 {
437         hook_xreq(closure, hookid, xreq, "store", NULL);
438 }
439
440 static void hook_xreq_unstore(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq)
441 {
442         hook_xreq(closure, hookid, xreq, "unstore", NULL);
443 }
444
445 static void hook_xreq_subcall_req(void *closure, const struct afb_hookid *hookid, const struct afb_xreq *xreq, const char *api, const char *verb, struct json_object *args)
446 {
447         hook_xreq(closure, hookid, 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_hookid *hookid, const struct afb_xreq *xreq, int status, struct json_object *result)
454 {
455         hook_xreq(closure, hookid, 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_hookid *hookid, 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, hookid, "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_hookid *hookid, const struct afb_ditf *ditf, const char *name, struct json_object *object)
528 {
529         hook_ditf(closure, hookid, 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_hookid *hookid, const struct afb_ditf *ditf, const char *name, struct json_object *object, int result)
534 {
535         hook_ditf(closure, hookid, 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_hookid *hookid, const struct afb_ditf *ditf, struct sd_event *result)
540 {
541         hook_ditf(closure, hookid, ditf, "get_event_loop", NULL);
542 }
543
544 static void hook_ditf_get_user_bus(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, struct sd_bus *result)
545 {
546         hook_ditf(closure, hookid, ditf, "get_user_bus", NULL);
547 }
548
549 static void hook_ditf_get_system_bus(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, struct sd_bus *result)
550 {
551         hook_ditf(closure, hookid, ditf, "get_system_bus", NULL);
552 }
553
554 static void hook_ditf_vverbose(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, int level, const char *file, int line, const char *function, const char *fmt, va_list args)
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, hookid, 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_hookid *hookid, const struct afb_ditf *ditf, const char *name, struct afb_event result)
581 {
582         hook_ditf(closure, hookid, 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_hookid *hookid, 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, hookid, 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_hookid *hookid, 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, hookid, 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_hookid *hookid, const struct afb_ditf *ditf, void (*callback)(int signum, void *arg), void *argument, void *group, int timeout, int result)
618 {
619         hook_ditf(closure, hookid, ditf, "queue_job", "{ss}", "result", result);
620 }
621
622 static void hook_ditf_unstore_req(void * closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, struct afb_stored_req *sreq)
623 {
624         hook_ditf(closure, hookid, ditf, "unstore_req", NULL);
625 }
626
627 static void hook_ditf_require_api(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *name, int initialized)
628 {
629         hook_ditf(closure, hookid, ditf, "require_api", "{ss sb}", "name", name, "initialized", initialized);
630 }
631
632 static void hook_ditf_require_api_result(void *closure, const struct afb_hookid *hookid, const struct afb_ditf *ditf, const char *name, int initialized, int result)
633 {
634         hook_ditf(closure, hookid, 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_hookid *hookid, 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, hookid, "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_hookid *hookid, const struct afb_svc *svc)
687 {
688         hook_svc(closure, hookid, svc, "start_before", NULL);
689 }
690
691 static void hook_svc_start_after(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, int status)
692 {
693         hook_svc(closure, hookid, svc, "start_after", "{si}", "result", status);
694 }
695
696 static void hook_svc_on_event_before(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, const char *event, int eventid, struct json_object *object)
697 {
698         hook_svc(closure, hookid, 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_hookid *hookid, const struct afb_svc *svc, const char *event, int eventid, struct json_object *object)
703 {
704         hook_svc(closure, hookid, 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_hookid *hookid, const struct afb_svc *svc, const char *api, const char *verb, struct json_object *args)
709 {
710         hook_svc(closure, hookid, 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_hookid *hookid, const struct afb_svc *svc, int status, struct json_object *result)
715 {
716         hook_svc(closure, hookid, svc, "call_result", "{si sO*}",
717                         "status", status, "result", result);
718 }
719
720 static void hook_svc_callsync(void *closure, const struct afb_hookid *hookid, const struct afb_svc *svc, const char *api, const char *verb, struct json_object *args)
721 {
722         hook_svc(closure, hookid, 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_hookid *hookid, const struct afb_svc *svc, int status, struct json_object *result)
727 {
728         hook_svc(closure, hookid, 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 struct afb_hookid *hookid, 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, hookid, "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 struct afb_hookid *hookid, const char *evt, int id)
779 {
780         hook_evt(closure, hookid, evt, id, "create", NULL);
781 }
782
783 static void hook_evt_push_before(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj)
784 {
785         hook_evt(closure, hookid, evt, id, "push_before", "{sO*}", "data", obj);
786 }
787
788
789 static void hook_evt_push_after(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj, int result)
790 {
791         hook_evt(closure, hookid, evt, id, "push_after", "{sO* si}", "data", obj, "result", result);
792 }
793
794 static void hook_evt_broadcast_before(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj)
795 {
796         hook_evt(closure, hookid, evt, id, "broadcast_before", "{sO*}", "data", obj);
797 }
798
799 static void hook_evt_broadcast_after(void *closure, const struct afb_hookid *hookid, const char *evt, int id, struct json_object *obj, int result)
800 {
801         hook_evt(closure, hookid, evt, id, "broadcast_after", "{sO* si}", "data", obj, "result", result);
802 }
803
804 static void hook_evt_name(void *closure, const struct afb_hookid *hookid, const char *evt, int id)
805 {
806         hook_evt(closure, hookid, evt, id, "name", NULL);
807 }
808
809 static void hook_evt_drop(void *closure, const struct afb_hookid *hookid, const char *evt, int id)
810 {
811         hook_evt(closure, hookid, 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 /*****  trace the globals                                                  *****/
826 /*******************************************************************************/
827
828 static struct flag global_flags[] = { /* must be sorted by names */
829                 { "all",                afb_hook_flags_global_all },
830                 { "vverbose",           afb_hook_flag_global_vverbose },
831 };
832
833 /* get the global value for flag of 'name' */
834 static int get_global_flag(const char *name)
835 {
836         return get_flag(name, global_flags, (int)(sizeof global_flags / sizeof *global_flags));
837 }
838
839 static void hook_global(void *closure, const struct afb_hookid *hookid, const char *action, const char *format, ...)
840 {
841         va_list ap;
842
843         va_start(ap, format);
844         emit(closure, hookid, "global", "{ss}", format, ap, "action", action);
845         va_end(ap);
846 }
847
848 static void hook_global_vverbose(void *closure, const struct afb_hookid *hookid, int level, const char *file, int line, const char *function, const char *fmt, va_list args)
849 {
850         struct json_object *pos;
851         int len;
852         char *msg;
853         va_list ap;
854
855         pos = NULL;
856         msg = NULL;
857
858         va_copy(ap, args);
859         len = vasprintf(&msg, fmt, ap);
860         va_end(ap);
861
862         if (file)
863                 wrap_json_pack(&pos, "{ss si ss*}", "file", file, "line", line, "function", function);
864
865         hook_global(closure, hookid, "vverbose", "{si ss* ss? so*}",
866                                         "level", level,
867                                         "type", verbosity_level_name(level),
868                                         len < 0 ? "format" : "message", len < 0 ? fmt : msg,
869                                         "position", pos);
870
871         free(msg);
872 }
873
874 static struct afb_hook_global_itf hook_global_itf = {
875         .hook_global_vverbose = hook_global_vverbose,
876 };
877
878 /*******************************************************************************/
879 /*****  abstract types                                                     *****/
880 /*******************************************************************************/
881
882 static
883 struct
884 {
885         const char *name;
886         void (*unref)(void*);
887         int (*get_flag)(const char*);
888 }
889 abstracting[Trace_Type_Count] =
890 {
891         [Trace_Type_Xreq] =
892         {
893                 .name = "request",
894                 .unref =  (void(*)(void*))afb_hook_unref_xreq,
895                 .get_flag = get_xreq_flag
896         },
897         [Trace_Type_Ditf] =
898         {
899                 .name = "daemon",
900                 .unref =  (void(*)(void*))afb_hook_unref_ditf,
901                 .get_flag = get_ditf_flag
902         },
903         [Trace_Type_Svc] =
904         {
905                 .name = "service",
906                 .unref =  (void(*)(void*))afb_hook_unref_svc,
907                 .get_flag = get_svc_flag
908         },
909         [Trace_Type_Evt] =
910         {
911                 .name = "event",
912                 .unref =  (void(*)(void*))afb_hook_unref_evt,
913                 .get_flag = get_evt_flag
914         },
915         [Trace_Type_Global] =
916         {
917                 .name = "global",
918                 .unref =  (void(*)(void*))afb_hook_unref_global,
919                 .get_flag = get_global_flag
920         },
921 };
922
923 /*******************************************************************************/
924 /*****  handle trace data                                                  *****/
925 /*******************************************************************************/
926
927 /* drop hooks of 'trace' matching 'tag' and 'event' and 'session' */
928 static void trace_unhook(struct afb_trace *trace, struct tag *tag, struct event *event, struct session *session)
929 {
930         int i;
931         struct hook *hook, **prev;
932
933         /* remove any event */
934         for (i = 0 ; i < Trace_Type_Count ; i++) {
935                 prev = &trace->hooks[i];
936                 while ((hook = *prev)) {
937                         if ((tag && tag != hook->tag)
938                          || (event && event != hook->event)
939                          || (session && session != hook->session))
940                                 prev = &hook->next;
941                         else {
942                                 *prev = hook->next;
943                                 abstracting[i].unref(hook->handler);
944                                 free(hook);
945                         }
946                 }
947         }
948 }
949
950 /* cleanup: removes unused tags, events and sessions of the 'trace' */
951 static void trace_cleanup(struct afb_trace *trace)
952 {
953         int i;
954         struct hook *hook;
955         struct tag *tag, **ptag;
956         struct event *event, **pevent;
957         struct session *session, **psession;
958
959         /* clean sessions */
960         psession = &trace->sessions;
961         while ((session = *psession)) {
962                 /* search for session */
963                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++)
964                         for (hook = trace->hooks[i] ; hook && hook->session != session ; hook = hook->next);
965                 /* keep or free whether used or not */
966                 if (hook)
967                         psession = &session->next;
968                 else {
969                         *psession = session->next;
970                         if (__atomic_exchange_n(&session->trace, NULL, __ATOMIC_RELAXED))
971                                 afb_session_set_cookie(session->session, session, NULL, NULL);
972                         free(session);
973                 }
974         }
975         /* clean tags */
976         ptag = &trace->tags;
977         while ((tag = *ptag)) {
978                 /* search for tag */
979                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++)
980                         for (hook = trace->hooks[i] ; hook && hook->tag != tag ; hook = hook->next);
981                 /* keep or free whether used or not */
982                 if (hook)
983                         ptag = &tag->next;
984                 else {
985                         *ptag = tag->next;
986                         free(tag);
987                 }
988         }
989         /* clean events */
990         pevent = &trace->events;
991         while ((event = *pevent)) {
992                 /* search for event */
993                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++)
994                         for (hook = trace->hooks[i] ; hook && hook->event != event ; hook = hook->next);
995                 /* keep or free whether used or not */
996                 if (hook)
997                         pevent = &event->next;
998                 else {
999                         *pevent = event->next;
1000                         afb_event_drop(event->event);
1001                         free(event);
1002                 }
1003         }
1004 }
1005
1006 /* callback at end of traced session */
1007 static void free_session_cookie(void *cookie)
1008 {
1009         struct session *session = cookie;
1010         struct afb_trace *trace = __atomic_exchange_n(&session->trace, NULL, __ATOMIC_RELAXED);
1011         if (trace) {
1012                 pthread_mutex_lock(&trace->mutex);
1013                 trace_unhook(trace, NULL, NULL, session);
1014                 trace_cleanup(trace);
1015                 pthread_mutex_unlock(&trace->mutex);
1016         }
1017 }
1018
1019 /*
1020  * Get the tag of 'name' within 'trace'.
1021  * If 'alloc' isn't zero, create the tag and add it.
1022  */
1023 static struct tag *trace_get_tag(struct afb_trace *trace, const char *name, int alloc)
1024 {
1025         struct tag *tag;
1026
1027         /* search the tag of 'name' */
1028         tag = trace->tags;
1029         while (tag && strcmp(name, tag->tag))
1030                 tag = tag->next;
1031
1032         if (!tag && alloc) {
1033                 /* creation if needed */
1034                 tag = malloc(sizeof * tag + strlen(name));
1035                 if (tag) {
1036                         strcpy(tag->tag, name);
1037                         tag->next = trace->tags;
1038                         trace->tags = tag;
1039                 }
1040         }
1041         return tag;
1042 }
1043
1044 /*
1045  * Get the event of 'name' within 'trace'.
1046  * If 'alloc' isn't zero, create the event and add it.
1047  */
1048 static struct event *trace_get_event(struct afb_trace *trace, const char *name, int alloc)
1049 {
1050         struct event *event;
1051
1052         /* search the event */
1053         event = trace->events;
1054         while (event && strcmp(afb_event_name(event->event), name))
1055                 event = event->next;
1056
1057         if (!event && alloc) {
1058                 event = malloc(sizeof * event);
1059                 if (event) {
1060                         event->event = trace->daemon->itf->event_make(trace->daemon->closure, name);
1061                         if (afb_event_is_valid(event->event)) {
1062                                 event->next = trace->events;
1063                                 trace->events = event;
1064                         } else {
1065                                 free(event);
1066                                 event = NULL;
1067                         }
1068                 }
1069         }
1070         return event;
1071 }
1072
1073 /*
1074  * Get the session of 'value' within 'trace'.
1075  * If 'alloc' isn't zero, create the session and add it.
1076  */
1077 static struct session *trace_get_session(struct afb_trace *trace, struct afb_session *value, int alloc)
1078 {
1079         struct session *session;
1080
1081         /* search the session */
1082         session = trace->sessions;
1083         while (session && session->session != value)
1084                 session = session->next;
1085
1086         if (!session && alloc) {
1087                 session = malloc(sizeof * session);
1088                 if (session) {
1089                         session->session = value;
1090                         session->trace = NULL;
1091                         session->next = trace->sessions;
1092                         trace->sessions = session;
1093                 }
1094         }
1095         return session;
1096 }
1097
1098 /*
1099  * Get the session of 'uuid' within 'trace'.
1100  * If 'alloc' isn't zero, create the session and add it.
1101  */
1102 static struct session *trace_get_session_by_uuid(struct afb_trace *trace, const char *uuid, int alloc)
1103 {
1104         struct afb_session *session;
1105         int created;
1106
1107         session = afb_session_get(uuid, alloc ? &created : NULL);
1108         return session ? trace_get_session(trace, session, alloc) : NULL;
1109 }
1110
1111 static struct hook *trace_make_detached_hook(struct afb_trace *trace, const char *event, const char *tag)
1112 {
1113         struct hook *hook;
1114
1115         tag = tag ?: DEFAULT_TAG_NAME;
1116         event = event ?: DEFAULT_EVENT_NAME;
1117         hook = malloc(sizeof *hook);
1118         if (hook) {
1119                 hook->tag = trace_get_tag(trace, tag, 1);
1120                 hook->event = trace_get_event(trace, event, 1);
1121                 hook->session = NULL;
1122                 hook->handler = NULL;
1123         }
1124         return hook;
1125 }
1126
1127 static void trace_attach_hook(struct afb_trace *trace, struct hook *hook, enum trace_type type)
1128 {
1129         struct session *session = hook->session;
1130         hook->next = trace->hooks[type];
1131         trace->hooks[type] = hook;
1132         if (session && !session->trace) {
1133                 session->trace = trace;
1134                 afb_session_set_cookie(session->session, session, session, free_session_cookie);
1135         }
1136 }
1137
1138 /*******************************************************************************/
1139 /*****  handle client requests                                             *****/
1140 /*******************************************************************************/
1141
1142 struct context
1143 {
1144         struct afb_trace *trace;
1145         struct afb_req req;
1146         char *errors;
1147 };
1148
1149 struct desc
1150 {
1151         struct context *context;
1152         const char *name;
1153         const char *tag;
1154         const char *session;
1155         const char *api;
1156         const char *verb;
1157         const char *pattern;
1158         int flags[Trace_Type_Count];
1159 };
1160
1161
1162 static void addhook(struct desc *desc, enum trace_type type)
1163 {
1164         struct hook *hook;
1165         struct session *session;
1166         struct afb_session *bind;
1167         struct afb_trace *trace = desc->context->trace;
1168
1169         /* check permission for bound traces */
1170         bind = trace->bound;
1171         if (bind != NULL) {
1172                 if (type != Trace_Type_Xreq) {
1173                         ctxt_error(&desc->context->errors, "tracing %s is forbidden", abstracting[type].name);
1174                         return;
1175                 }
1176                 if (desc->session) {
1177                         ctxt_error(&desc->context->errors, "setting session is forbidden");
1178                         return;
1179                 }
1180         }
1181
1182         /* allocate the hook */
1183         hook = trace_make_detached_hook(trace, desc->name, desc->tag);
1184         if (!hook) {
1185                 ctxt_error(&desc->context->errors, "allocation of hook failed");
1186                 return;
1187         }
1188
1189         /* create the hook handler */
1190         switch (type) {
1191         case Trace_Type_Xreq:
1192                 if (desc->session) {
1193                         session = trace_get_session_by_uuid(trace, desc->session, 1);
1194                         if (!session) {
1195                                 ctxt_error(&desc->context->errors, "allocation of session failed");
1196                                 free(hook);
1197                                 return;
1198                         }
1199                         bind = session->session;
1200                 }
1201                 hook->handler = afb_hook_create_xreq(desc->api, desc->verb, bind,
1202                                 desc->flags[type], &hook_xreq_itf, hook);
1203                 break;
1204         case Trace_Type_Ditf:
1205                 hook->handler = afb_hook_create_ditf(desc->api, desc->flags[type], &hook_ditf_itf, hook);
1206                 break;
1207         case Trace_Type_Svc:
1208                 hook->handler = afb_hook_create_svc(desc->api, desc->flags[type], &hook_svc_itf, hook);
1209                 break;
1210         case Trace_Type_Evt:
1211                 hook->handler = afb_hook_create_evt(desc->pattern, desc->flags[type], &hook_evt_itf, hook);
1212                 break;
1213         case Trace_Type_Global:
1214                 hook->handler = afb_hook_create_global(desc->flags[type], &hook_global_itf, hook);
1215                 break;
1216         default:
1217                 break;
1218         }
1219         if (!hook->handler) {
1220                 ctxt_error(&desc->context->errors, "creation of hook failed");
1221                 free(hook);
1222                 return;
1223         }
1224
1225         /* attach and activate the hook */
1226         afb_req_subscribe(desc->context->req, hook->event->event);
1227         trace_attach_hook(trace, hook, type);
1228 }
1229
1230 static void addhooks(struct desc *desc)
1231 {
1232         int i;
1233
1234         for (i = 0 ; i < Trace_Type_Count ; i++) {
1235                 if (desc->flags[i])
1236                         addhook(desc, i);
1237         }
1238 }
1239
1240 static void add_flags(void *closure, struct json_object *object, enum trace_type type)
1241 {
1242         int value;
1243         const char *name, *queried;
1244         struct desc *desc = closure;
1245
1246         if (wrap_json_unpack(object, "s", &name))
1247                 ctxt_error(&desc->context->errors, "unexpected %s value %s",
1248                                         abstracting[type].name,
1249                                         json_object_to_json_string(object));
1250         else {
1251                 queried = (name[0] == '*' && !name[1]) ? "all" : name;
1252                 value = abstracting[type].get_flag(queried);
1253                 if (value)
1254                         desc->flags[type] |= value;
1255                 else
1256                         ctxt_error(&desc->context->errors, "unknown %s name %s",
1257                                         abstracting[type].name, name);
1258         }
1259 }
1260
1261 static void add_xreq_flags(void *closure, struct json_object *object)
1262 {
1263         add_flags(closure, object, Trace_Type_Xreq);
1264 }
1265
1266 static void add_ditf_flags(void *closure, struct json_object *object)
1267 {
1268         add_flags(closure, object, Trace_Type_Ditf);
1269 }
1270
1271 static void add_svc_flags(void *closure, struct json_object *object)
1272 {
1273         add_flags(closure, object, Trace_Type_Svc);
1274 }
1275
1276 static void add_evt_flags(void *closure, struct json_object *object)
1277 {
1278         add_flags(closure, object, Trace_Type_Evt);
1279 }
1280
1281 static void add_global_flags(void *closure, struct json_object *object)
1282 {
1283         add_flags(closure, object, Trace_Type_Global);
1284 }
1285
1286 /* add hooks */
1287 static void add(void *closure, struct json_object *object)
1288 {
1289         int rc;
1290         struct desc desc;
1291         struct json_object *request, *event, *daemon, *service, *sub, *global;
1292
1293         memcpy (&desc, closure, sizeof desc);
1294         request = event = daemon = service = sub = global = NULL;
1295
1296         rc = wrap_json_unpack(object, "{s?s s?s s?s s?s s?s s?s s?o s?o s?o s?o s?o s?o}",
1297                         "name", &desc.name,
1298                         "tag", &desc.tag,
1299                         "api", &desc.api,
1300                         "verb", &desc.verb,
1301                         "session", &desc.session,
1302                         "pattern", &desc.pattern,
1303                         "request", &request,
1304                         "daemon", &daemon,
1305                         "service", &service,
1306                         "event", &event,
1307                         "global", &global,
1308                         "for", &sub);
1309
1310         if (!rc) {
1311                 /* replace stars */
1312                 if (desc.api && desc.api[0] == '*' && !desc.api[1])
1313                         desc.api = NULL;
1314
1315                 if (desc.verb && desc.verb[0] == '*' && !desc.verb[1])
1316                         desc.verb = NULL;
1317
1318                 if (desc.session && desc.session[0] == '*' && !desc.session[1])
1319                         desc.session = NULL;
1320
1321                 /* get what is expected */
1322                 if (request)
1323                         wrap_json_optarray_for_all(request, add_xreq_flags, &desc);
1324
1325                 if (daemon)
1326                         wrap_json_optarray_for_all(daemon, add_ditf_flags, &desc);
1327
1328                 if (service)
1329                         wrap_json_optarray_for_all(service, add_svc_flags, &desc);
1330
1331                 if (event)
1332                         wrap_json_optarray_for_all(event, add_evt_flags, &desc);
1333
1334                 if (global)
1335                         wrap_json_optarray_for_all(global, add_global_flags, &desc);
1336
1337                 /* apply */
1338                 if (sub)
1339                         wrap_json_optarray_for_all(sub, add, &desc);
1340                 else
1341                         addhooks(&desc);
1342         }
1343         else {
1344                 wrap_json_optarray_for_all(object, add_xreq_flags, &desc);
1345                 addhooks(&desc);
1346         }
1347 }
1348
1349 /* drop hooks of given tag */
1350 static void drop_tag(void *closure, struct json_object *object)
1351 {
1352         int rc;
1353         struct context *context = closure;
1354         struct tag *tag;
1355         const char *name;
1356
1357         rc = wrap_json_unpack(object, "s", &name);
1358         if (rc)
1359                 ctxt_error(&context->errors, "unexpected tag value %s", json_object_to_json_string(object));
1360         else {
1361                 tag = trace_get_tag(context->trace, name, 0);
1362                 if (!tag)
1363                         ctxt_error(&context->errors, "tag %s not found", name);
1364                 else
1365                         trace_unhook(context->trace, tag, NULL, NULL);
1366         }
1367 }
1368
1369 /* drop hooks of given event */
1370 static void drop_event(void *closure, struct json_object *object)
1371 {
1372         int rc;
1373         struct context *context = closure;
1374         struct event *event;
1375         const char *name;
1376
1377         rc = wrap_json_unpack(object, "s", &name);
1378         if (rc)
1379                 ctxt_error(&context->errors, "unexpected event value %s", json_object_to_json_string(object));
1380         else {
1381                 event = trace_get_event(context->trace, name, 0);
1382                 if (!event)
1383                         ctxt_error(&context->errors, "event %s not found", name);
1384                 else
1385                         trace_unhook(context->trace, NULL, event, NULL);
1386         }
1387 }
1388
1389 /* drop hooks of given session */
1390 static void drop_session(void *closure, struct json_object *object)
1391 {
1392         int rc;
1393         struct context *context = closure;
1394         struct session *session;
1395         const char *uuid;
1396
1397         rc = wrap_json_unpack(object, "s", &uuid);
1398         if (rc)
1399                 ctxt_error(&context->errors, "unexpected session value %s", json_object_to_json_string(object));
1400         else {
1401                 session = trace_get_session_by_uuid(context->trace, uuid, 0);
1402                 if (!session)
1403                         ctxt_error(&context->errors, "session %s not found", uuid);
1404                 else
1405                         trace_unhook(context->trace, NULL, NULL, session);
1406         }
1407 }
1408
1409 /*******************************************************************************/
1410 /*****  public interface                                                   *****/
1411 /*******************************************************************************/
1412
1413 /* allocates an afb_trace instance */
1414 struct afb_trace *afb_trace_create(struct afb_daemon *daemon, struct afb_session *bound)
1415 {
1416         struct afb_trace *trace;
1417
1418         assert(daemon);
1419
1420         trace = calloc(1, sizeof *trace);
1421         if (trace) {
1422                 trace->refcount = 1;
1423                 trace->bound = bound;
1424                 trace->daemon = daemon;
1425                 pthread_mutex_init(&trace->mutex, NULL);
1426         }
1427         return trace;
1428 }
1429
1430 /* add a reference to the trace */
1431 void afb_trace_addref(struct afb_trace *trace)
1432 {
1433         __atomic_add_fetch(&trace->refcount, 1, __ATOMIC_RELAXED);
1434 }
1435
1436 /* drop one reference to the trace */
1437 void afb_trace_unref(struct afb_trace *trace)
1438 {
1439         if (trace && !__atomic_sub_fetch(&trace->refcount, 1, __ATOMIC_RELAXED)) {
1440                 /* clean hooks */
1441                 trace_unhook(trace, NULL, NULL, NULL);
1442                 trace_cleanup(trace);
1443                 pthread_mutex_destroy(&trace->mutex);
1444                 free(trace);
1445         }
1446 }
1447
1448 /* add traces */
1449 int afb_trace_add(struct afb_req req, struct json_object *args, struct afb_trace *trace)
1450 {
1451         struct context context;
1452         struct desc desc;
1453
1454         memset(&context, 0, sizeof context);
1455         context.trace = trace;
1456         context.req = req;
1457
1458         memset(&desc, 0, sizeof desc);
1459         desc.context = &context;
1460
1461         pthread_mutex_lock(&trace->mutex);
1462         wrap_json_optarray_for_all(args, add, &desc);
1463         pthread_mutex_unlock(&trace->mutex);
1464
1465         if (!context.errors)
1466                 return 0;
1467
1468         afb_req_fail(req, "error-detected", context.errors);
1469         free(context.errors);
1470         return -1;
1471 }
1472
1473 /* drop traces */
1474 extern int afb_trace_drop(struct afb_req req, struct json_object *args, struct afb_trace *trace)
1475 {
1476         int rc;
1477         struct context context;
1478         struct json_object *tags, *events, *sessions;
1479
1480         memset(&context, 0, sizeof context);
1481         context.trace = trace;
1482         context.req = req;
1483
1484         /* special: boolean value */
1485         if (!wrap_json_unpack(args, "b", &rc)) {
1486                 if (rc) {
1487                         pthread_mutex_lock(&trace->mutex);
1488                         trace_unhook(trace, NULL, NULL, NULL);
1489                         trace_cleanup(trace);
1490                         pthread_mutex_unlock(&trace->mutex);
1491                 }
1492                 return 0;
1493         }
1494
1495         tags = events = sessions = NULL;
1496         rc = wrap_json_unpack(args, "{s?o s?o s?o}",
1497                         "event", &events,
1498                         "tag", &tags,
1499                         "session", &sessions);
1500
1501         if (rc < 0 || !(events || tags || sessions)) {
1502                 afb_req_fail(req, "error-detected", "bad drop arguments");
1503                 return -1;
1504         }
1505
1506         pthread_mutex_lock(&trace->mutex);
1507
1508         if (tags)
1509                 wrap_json_optarray_for_all(tags, drop_tag, &context);
1510
1511         if (events)
1512                 wrap_json_optarray_for_all(events, drop_event, &context);
1513
1514         if (sessions)
1515                 wrap_json_optarray_for_all(sessions, drop_session, &context);
1516
1517         trace_cleanup(trace);
1518
1519         pthread_mutex_unlock(&trace->mutex);
1520
1521         if (!context.errors)
1522                 return 0;
1523
1524         afb_req_fail(req, "error-detected", context.errors);
1525         free(context.errors);
1526         return -1;
1527 }
1528