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