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