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