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