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