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