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