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