Remove refreshing token
[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_addref(void *closure, const struct afb_hookid *hookid, struct afb_session *session)
870 {
871         hook_session(closure, hookid, session, "addref", NULL);
872 }
873
874 static void hook_session_unref(void *closure, const struct afb_hookid *hookid, struct afb_session *session)
875 {
876         hook_session(closure, hookid, session, "unref", NULL);
877 }
878
879 static struct afb_hook_session_itf hook_session_itf = {
880         .hook_session_create = hook_session_create,
881         .hook_session_close = hook_session_close,
882         .hook_session_destroy = hook_session_destroy,
883         .hook_session_addref = hook_session_addref,
884         .hook_session_unref = hook_session_unref
885 };
886
887 /*******************************************************************************/
888 /*****  trace the globals                                                  *****/
889 /*******************************************************************************/
890
891 static void hook_global(void *closure, const struct afb_hookid *hookid, const char *action, const char *format, ...)
892 {
893         va_list ap;
894
895         va_start(ap, format);
896         emit(closure, hookid, "global", "{ss}", format, ap, "action", action);
897         va_end(ap);
898 }
899
900 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)
901 {
902         struct json_object *pos;
903         int len;
904         char *msg;
905         va_list ap;
906
907         pos = NULL;
908         msg = NULL;
909
910         va_copy(ap, args);
911         len = vasprintf(&msg, fmt, ap);
912         va_end(ap);
913
914         if (file)
915                 wrap_json_pack(&pos, "{ss si ss*}", "file", file, "line", line, "function", function);
916
917         hook_global(closure, hookid, "vverbose", "{si ss* ss? so*}",
918                                         "level", level,
919                                         "type", verbosity_level_name(level),
920                                         len < 0 ? "format" : "message", len < 0 ? fmt : msg,
921                                         "position", pos);
922
923         free(msg);
924 }
925
926 static struct afb_hook_global_itf hook_global_itf = {
927         .hook_global_vverbose = hook_global_vverbose,
928 };
929
930 /*******************************************************************************/
931 /*****  abstract types                                                     *****/
932 /*******************************************************************************/
933
934 static
935 struct
936 {
937         const char *name;
938         void (*unref)(void*);
939         int (*get_flag)(const char*);
940 }
941 abstracting[Trace_Type_Count] =
942 {
943         [Trace_Type_Xreq] =
944         {
945                 .name = "request",
946                 .unref =  (void(*)(void*))afb_hook_unref_xreq,
947                 .get_flag = afb_hook_flags_xreq_from_text
948         },
949         [Trace_Type_Api] =
950         {
951                 .name = "api",
952                 .unref =  (void(*)(void*))afb_hook_unref_api,
953                 .get_flag = afb_hook_flags_api_from_text
954         },
955         [Trace_Type_Evt] =
956         {
957                 .name = "event",
958                 .unref =  (void(*)(void*))afb_hook_unref_evt,
959                 .get_flag = afb_hook_flags_evt_from_text
960         },
961         [Trace_Type_Session] =
962         {
963                 .name = "session",
964                 .unref =  (void(*)(void*))afb_hook_unref_session,
965                 .get_flag = afb_hook_flags_session_from_text
966         },
967         [Trace_Type_Global] =
968         {
969                 .name = "global",
970                 .unref =  (void(*)(void*))afb_hook_unref_global,
971                 .get_flag = afb_hook_flags_global_from_text
972         },
973 #if !defined(REMOVE_LEGACY_TRACE)
974         [Trace_Legacy_Type_Ditf] =
975         {
976                 .name = "daemon",
977                 .unref =  (void(*)(void*))afb_hook_unref_api,
978                 .get_flag = afb_hook_flags_legacy_ditf_from_text
979         },
980         [Trace_Legacy_Type_Svc] =
981         {
982                 .name = "service",
983                 .unref =  (void(*)(void*))afb_hook_unref_api,
984                 .get_flag = afb_hook_flags_legacy_svc_from_text
985         },
986 #endif
987 };
988
989 /*******************************************************************************/
990 /*****  handle trace data                                                  *****/
991 /*******************************************************************************/
992
993 /* drop hooks of 'trace' matching 'tag' and 'event' and 'session' */
994 static void trace_unhook(struct afb_trace *trace, struct tag *tag, struct event *event, struct afb_session *session)
995 {
996         int i;
997         struct hook *hook, **prev;
998
999         /* remove any event */
1000         for (i = 0 ; i < Trace_Type_Count ; i++) {
1001                 prev = &trace->hooks[i];
1002                 while ((hook = *prev)) {
1003                         if ((tag && tag != hook->tag)
1004                          || (event && event != hook->event)
1005                          || (session && session != hook->session))
1006                                 prev = &hook->next;
1007                         else {
1008                                 *prev = hook->next;
1009                                 abstracting[i].unref(hook->handler);
1010                                 free(hook);
1011                         }
1012                 }
1013         }
1014 }
1015
1016 /* cleanup: removes unused tags, events and sessions of the 'trace' */
1017 static void trace_cleanup(struct afb_trace *trace)
1018 {
1019         int i;
1020         struct hook *hook;
1021         struct tag *tag, **ptag;
1022         struct event *event, **pevent;
1023
1024         /* clean tags */
1025         ptag = &trace->tags;
1026         while ((tag = *ptag)) {
1027                 /* search for tag */
1028                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++)
1029                         for (hook = trace->hooks[i] ; hook && hook->tag != tag ; hook = hook->next);
1030                 /* keep or free whether used or not */
1031                 if (hook)
1032                         ptag = &tag->next;
1033                 else {
1034                         *ptag = tag->next;
1035                         free(tag);
1036                 }
1037         }
1038         /* clean events */
1039         pevent = &trace->events;
1040         while ((event = *pevent)) {
1041                 /* search for event */
1042                 for (hook = NULL, i = 0 ; !hook && i < Trace_Type_Count ; i++)
1043                         for (hook = trace->hooks[i] ; hook && hook->event != event ; hook = hook->next);
1044                 /* keep or free whether used or not */
1045                 if (hook)
1046                         pevent = &event->next;
1047                 else {
1048                         *pevent = event->next;
1049                         afb_evt_evtid_unref(event->evtid);
1050                         free(event);
1051                 }
1052         }
1053 }
1054
1055 /*
1056  * Get the tag of 'name' within 'trace'.
1057  * If 'alloc' isn't zero, create the tag and add it.
1058  */
1059 static struct tag *trace_get_tag(struct afb_trace *trace, const char *name, int alloc)
1060 {
1061         struct tag *tag;
1062
1063         /* search the tag of 'name' */
1064         tag = trace->tags;
1065         while (tag && strcmp(name, tag->tag))
1066                 tag = tag->next;
1067
1068         if (!tag && alloc) {
1069                 /* creation if needed */
1070                 tag = malloc(sizeof * tag + 1 + strlen(name));
1071                 if (tag) {
1072                         strcpy(tag->tag, name);
1073                         tag->next = trace->tags;
1074                         trace->tags = tag;
1075                 }
1076         }
1077         return tag;
1078 }
1079
1080 /*
1081  * Get the event of 'name' within 'trace'.
1082  * If 'alloc' isn't zero, create the event and add it.
1083  */
1084 static struct event *trace_get_event(struct afb_trace *trace, const char *name, int alloc)
1085 {
1086         struct event *event;
1087
1088         /* search the event */
1089         event = trace->events;
1090         while (event && strcmp(afb_evt_evtid_name(event->evtid), name))
1091                 event = event->next;
1092
1093         if (!event && alloc) {
1094                 event = malloc(sizeof * event);
1095                 if (event) {
1096                         event->evtid = afb_evt_evtid_create2(trace->apiname, name);
1097                         if (event->evtid) {
1098                                 event->next = trace->events;
1099                                 trace->events = event;
1100                         } else {
1101                                 free(event);
1102                                 event = NULL;
1103                         }
1104                 }
1105         }
1106         return event;
1107 }
1108
1109 /*
1110  * called on session closing
1111  */
1112 static void session_closed(void *item)
1113 {
1114         struct cookie *cookie = item;
1115
1116         pthread_mutex_lock(&cookie->trace->mutex);
1117         trace_unhook(cookie->trace, NULL, NULL, cookie->session);
1118         pthread_mutex_unlock(&cookie->trace->mutex);
1119         free(cookie);
1120 }
1121
1122 /*
1123  * records the cookie of session for tracking close
1124  */
1125 static void *session_open(void *closure)
1126 {
1127         struct cookie *param = closure, *cookie;
1128         cookie = malloc(sizeof *cookie);
1129         if (cookie)
1130                 *cookie = *param;
1131         return cookie;
1132 }
1133
1134 /*
1135  * Get the session of 'uuid' within 'trace'.
1136  * If 'alloc' isn't zero, create the session and add it.
1137  */
1138 static struct afb_session *trace_get_session_by_uuid(struct afb_trace *trace, const char *uuid, int alloc)
1139 {
1140         struct cookie cookie;
1141
1142         if (!alloc)
1143                 cookie.session = afb_session_search(uuid);
1144         else {
1145                 cookie.session = afb_session_get(uuid, AFB_SESSION_TIMEOUT_DEFAULT, NULL);
1146                 if (cookie.session) {
1147                         cookie.trace = trace;
1148                         afb_session_cookie(cookie.session, cookie.trace, session_open, session_closed, &cookie, 0);
1149                 }
1150         }
1151         return cookie.session;
1152 }
1153
1154 static struct hook *trace_make_detached_hook(struct afb_trace *trace, const char *event, const char *tag)
1155 {
1156         struct hook *hook;
1157
1158         tag = tag ?: DEFAULT_TAG_NAME;
1159         event = event ?: DEFAULT_EVENT_NAME;
1160         hook = malloc(sizeof *hook);
1161         if (hook) {
1162                 hook->tag = trace_get_tag(trace, tag, 1);
1163                 hook->event = trace_get_event(trace, event, 1);
1164                 hook->session = NULL;
1165                 hook->handler = NULL;
1166         }
1167         return hook;
1168 }
1169
1170 static void trace_attach_hook(struct afb_trace *trace, struct hook *hook, enum trace_type type)
1171 {
1172         hook->next = trace->hooks[type];
1173         trace->hooks[type] = hook;
1174 }
1175
1176 /*******************************************************************************/
1177 /*****  handle client requests                                             *****/
1178 /*******************************************************************************/
1179
1180 struct context
1181 {
1182         struct afb_trace *trace;
1183         afb_req_t req;
1184         char *errors;
1185 };
1186
1187 struct desc
1188 {
1189         struct context *context;
1190         const char *name;
1191         const char *tag;
1192         const char *uuid;
1193         const char *apiname;
1194         const char *verbname;
1195         const char *pattern;
1196         int flags[Trace_Type_Count];
1197 };
1198
1199 static void addhook(struct desc *desc, enum trace_type type)
1200 {
1201         struct hook *hook;
1202         struct afb_session *session;
1203         struct afb_session *bind;
1204         struct afb_trace *trace = desc->context->trace;
1205
1206         /* check permission for bound traces */
1207         bind = trace->bound;
1208         if (bind != NULL) {
1209                 if (type != Trace_Type_Xreq) {
1210                         ctxt_error(&desc->context->errors, "tracing %s is forbidden", abstracting[type].name);
1211                         return;
1212                 }
1213                 if (desc->uuid) {
1214                         ctxt_error(&desc->context->errors, "setting session is forbidden");
1215                         return;
1216                 }
1217         }
1218
1219         /* allocate the hook */
1220         hook = trace_make_detached_hook(trace, desc->name, desc->tag);
1221         if (!hook) {
1222                 ctxt_error(&desc->context->errors, "allocation of hook failed");
1223                 return;
1224         }
1225
1226         /* create the hook handler */
1227         switch (type) {
1228         case Trace_Type_Xreq:
1229                 if (!desc->uuid)
1230                         session = afb_session_addref(bind);
1231                 else {
1232                         session = trace_get_session_by_uuid(trace, desc->uuid, 1);
1233                         if (!session) {
1234                                 ctxt_error(&desc->context->errors, "allocation of session failed");
1235                                 free(hook);
1236                                 return;
1237                         }
1238                 }
1239                 hook->handler = afb_hook_create_xreq(desc->apiname, desc->verbname, session,
1240                                 desc->flags[type], &hook_xreq_itf, hook);
1241                 afb_session_unref(session);
1242                 break;
1243         case Trace_Type_Api:
1244                 hook->handler = afb_hook_create_api(desc->apiname, desc->flags[type], &hook_api_itf, hook);
1245                 break;
1246         case Trace_Type_Evt:
1247                 hook->handler = afb_hook_create_evt(desc->pattern, desc->flags[type], &hook_evt_itf, hook);
1248                 break;
1249         case Trace_Type_Session:
1250                 hook->handler = afb_hook_create_session(desc->uuid, desc->flags[type], &hook_session_itf, hook);
1251                 break;
1252         case Trace_Type_Global:
1253                 hook->handler = afb_hook_create_global(desc->flags[type], &hook_global_itf, hook);
1254                 break;
1255         default:
1256                 break;
1257         }
1258         if (!hook->handler) {
1259                 ctxt_error(&desc->context->errors, "creation of hook failed");
1260                 free(hook);
1261                 return;
1262         }
1263
1264         /* attach and activate the hook */
1265         afb_req_subscribe(desc->context->req, afb_evt_event_x2_from_evtid(hook->event->evtid));
1266         trace_attach_hook(trace, hook, type);
1267 }
1268
1269 static void addhooks(struct desc *desc)
1270 {
1271         int i;
1272
1273 #if !defined(REMOVE_LEGACY_TRACE)
1274         desc->flags[Trace_Type_Api] |= desc->flags[Trace_Legacy_Type_Ditf] | desc->flags[Trace_Legacy_Type_Svc];
1275         desc->flags[Trace_Legacy_Type_Ditf] = desc->flags[Trace_Legacy_Type_Svc] = 0;
1276 #endif
1277
1278         for (i = 0 ; i < Trace_Type_Count ; i++) {
1279                 if (desc->flags[i])
1280                         addhook(desc, i);
1281         }
1282 }
1283
1284 static void add_flags(void *closure, struct json_object *object, enum trace_type type)
1285 {
1286         int value;
1287         const char *name, *queried;
1288         struct desc *desc = closure;
1289
1290         if (wrap_json_unpack(object, "s", &name))
1291                 ctxt_error(&desc->context->errors, "unexpected %s value %s",
1292                                         abstracting[type].name,
1293                                         json_object_to_json_string_ext(object, JSON_C_TO_STRING_NOSLASHESCAPE));
1294         else {
1295                 queried = (name[0] == '*' && !name[1]) ? "all" : name;
1296                 value = abstracting[type].get_flag(queried);
1297                 if (value)
1298                         desc->flags[type] |= value;
1299                 else
1300                         ctxt_error(&desc->context->errors, "unknown %s name %s",
1301                                         abstracting[type].name, name);
1302         }
1303 }
1304
1305 static void add_xreq_flags(void *closure, struct json_object *object)
1306 {
1307         add_flags(closure, object, Trace_Type_Xreq);
1308 }
1309
1310 #if !defined(REMOVE_LEGACY_TRACE)
1311 static void legacy_add_ditf_flags(void *closure, struct json_object *object)
1312 {
1313         add_flags(closure, object, Trace_Legacy_Type_Ditf);
1314 }
1315
1316 static void legacy_add_svc_flags(void *closure, struct json_object *object)
1317 {
1318         add_flags(closure, object, Trace_Legacy_Type_Svc);
1319 }
1320 #endif
1321
1322 static void add_api_flags(void *closure, struct json_object *object)
1323 {
1324         add_flags(closure, object, Trace_Type_Api);
1325 }
1326
1327 static void add_evt_flags(void *closure, struct json_object *object)
1328 {
1329         add_flags(closure, object, Trace_Type_Evt);
1330 }
1331
1332 static void add_session_flags(void *closure, struct json_object *object)
1333 {
1334         add_flags(closure, object, Trace_Type_Session);
1335 }
1336
1337 static void add_global_flags(void *closure, struct json_object *object)
1338 {
1339         add_flags(closure, object, Trace_Type_Global);
1340 }
1341
1342 /* add hooks */
1343 static void add(void *closure, struct json_object *object)
1344 {
1345         int rc;
1346         struct desc desc;
1347         struct json_object *request, *event, *sub, *global, *session, *api;
1348 #if !defined(REMOVE_LEGACY_TRACE)
1349         struct json_object *daemon, *service;
1350 #endif
1351
1352         memcpy (&desc, closure, sizeof desc);
1353         request = event = sub = global = session = api = NULL;
1354 #if !defined(REMOVE_LEGACY_TRACE)
1355         daemon = service = NULL;
1356 #endif
1357
1358         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}",
1359                         "name", &desc.name,
1360                         "tag", &desc.tag,
1361                         "apiname", &desc.apiname,
1362                         "verbname", &desc.verbname,
1363                         "uuid", &desc.uuid,
1364                         "pattern", &desc.pattern,
1365                         "api", &api,
1366                         "request", &request,
1367 #if !defined(REMOVE_LEGACY_TRACE)
1368                         "daemon", &daemon,
1369                         "service", &service,
1370 #endif
1371                         "event", &event,
1372                         "session", &session,
1373                         "global", &global,
1374                         "for", &sub);
1375
1376         if (!rc) {
1377                 /* replace stars */
1378                 if (desc.apiname && desc.apiname[0] == '*' && !desc.apiname[1])
1379                         desc.apiname = NULL;
1380
1381                 if (desc.verbname && desc.verbname[0] == '*' && !desc.verbname[1])
1382                         desc.verbname = NULL;
1383
1384                 if (desc.uuid && desc.uuid[0] == '*' && !desc.uuid[1])
1385                         desc.uuid = NULL;
1386
1387                 /* get what is expected */
1388                 if (request)
1389                         wrap_json_optarray_for_all(request, add_xreq_flags, &desc);
1390
1391                 if (api)
1392                         wrap_json_optarray_for_all(api, add_api_flags, &desc);
1393
1394 #if !defined(REMOVE_LEGACY_TRACE)
1395                 if (daemon)
1396                         wrap_json_optarray_for_all(daemon, legacy_add_ditf_flags, &desc);
1397
1398                 if (service)
1399                         wrap_json_optarray_for_all(service, legacy_add_svc_flags, &desc);
1400 #endif
1401
1402                 if (event)
1403                         wrap_json_optarray_for_all(event, add_evt_flags, &desc);
1404
1405                 if (session)
1406                         wrap_json_optarray_for_all(session, add_session_flags, &desc);
1407
1408                 if (global)
1409                         wrap_json_optarray_for_all(global, add_global_flags, &desc);
1410
1411                 /* apply */
1412                 if (sub)
1413                         wrap_json_optarray_for_all(sub, add, &desc);
1414                 else
1415                         addhooks(&desc);
1416         }
1417         else {
1418                 wrap_json_optarray_for_all(object, add_xreq_flags, &desc);
1419                 addhooks(&desc);
1420         }
1421 }
1422
1423 /* drop hooks of given tag */
1424 static void drop_tag(void *closure, struct json_object *object)
1425 {
1426         int rc;
1427         struct context *context = closure;
1428         struct tag *tag;
1429         const char *name;
1430
1431         rc = wrap_json_unpack(object, "s", &name);
1432         if (rc)
1433                 ctxt_error(&context->errors, "unexpected tag value %s", json_object_to_json_string_ext(object, JSON_C_TO_STRING_NOSLASHESCAPE));
1434         else {
1435                 tag = trace_get_tag(context->trace, name, 0);
1436                 if (!tag)
1437                         ctxt_error(&context->errors, "tag %s not found", name);
1438                 else
1439                         trace_unhook(context->trace, tag, NULL, NULL);
1440         }
1441 }
1442
1443 /* drop hooks of given event */
1444 static void drop_event(void *closure, struct json_object *object)
1445 {
1446         int rc;
1447         struct context *context = closure;
1448         struct event *event;
1449         const char *name;
1450
1451         rc = wrap_json_unpack(object, "s", &name);
1452         if (rc)
1453                 ctxt_error(&context->errors, "unexpected event value %s", json_object_to_json_string_ext(object, JSON_C_TO_STRING_NOSLASHESCAPE));
1454         else {
1455                 event = trace_get_event(context->trace, name, 0);
1456                 if (!event)
1457                         ctxt_error(&context->errors, "event %s not found", name);
1458                 else
1459                         trace_unhook(context->trace, NULL, event, NULL);
1460         }
1461 }
1462
1463 /* drop hooks of given session */
1464 static void drop_session(void *closure, struct json_object *object)
1465 {
1466         int rc;
1467         struct context *context = closure;
1468         struct afb_session *session;
1469         const char *uuid;
1470
1471         rc = wrap_json_unpack(object, "s", &uuid);
1472         if (rc)
1473                 ctxt_error(&context->errors, "unexpected session value %s", json_object_to_json_string_ext(object, JSON_C_TO_STRING_NOSLASHESCAPE));
1474         else {
1475                 session = trace_get_session_by_uuid(context->trace, uuid, 0);
1476                 if (!session)
1477                         ctxt_error(&context->errors, "session %s not found", uuid);
1478                 else {
1479                         trace_unhook(context->trace, NULL, NULL, session);
1480                         afb_session_unref(session);
1481                 }
1482         }
1483 }
1484
1485 /*******************************************************************************/
1486 /*****  public interface                                                   *****/
1487 /*******************************************************************************/
1488
1489 /* allocates an afb_trace instance */
1490 struct afb_trace *afb_trace_create(const char *apiname, struct afb_session *bound)
1491 {
1492         struct afb_trace *trace;
1493
1494         assert(apiname);
1495
1496         trace = calloc(1, sizeof *trace);
1497         if (trace) {
1498                 trace->refcount = 1;
1499                 trace->bound = bound;
1500                 trace->apiname = apiname;
1501                 pthread_mutex_init(&trace->mutex, NULL);
1502         }
1503         return trace;
1504 }
1505
1506 /* add a reference to the trace */
1507 void afb_trace_addref(struct afb_trace *trace)
1508 {
1509         __atomic_add_fetch(&trace->refcount, 1, __ATOMIC_RELAXED);
1510 }
1511
1512 /* drop one reference to the trace */
1513 void afb_trace_unref(struct afb_trace *trace)
1514 {
1515         if (trace && !__atomic_sub_fetch(&trace->refcount, 1, __ATOMIC_RELAXED)) {
1516                 /* clean hooks */
1517                 trace_unhook(trace, NULL, NULL, NULL);
1518                 trace_cleanup(trace);
1519                 pthread_mutex_destroy(&trace->mutex);
1520                 free(trace);
1521         }
1522 }
1523
1524 /* add traces */
1525 int afb_trace_add(afb_req_t req, struct json_object *args, struct afb_trace *trace)
1526 {
1527         struct context context;
1528         struct desc desc;
1529
1530         memset(&context, 0, sizeof context);
1531         context.trace = trace;
1532         context.req = req;
1533
1534         memset(&desc, 0, sizeof desc);
1535         desc.context = &context;
1536
1537         pthread_mutex_lock(&trace->mutex);
1538         wrap_json_optarray_for_all(args, add, &desc);
1539         pthread_mutex_unlock(&trace->mutex);
1540
1541         if (!context.errors)
1542                 return 0;
1543
1544         afb_req_fail(req, "error-detected", context.errors);
1545         free(context.errors);
1546         return -1;
1547 }
1548
1549 /* drop traces */
1550 int afb_trace_drop(afb_req_t req, struct json_object *args, struct afb_trace *trace)
1551 {
1552         int rc;
1553         struct context context;
1554         struct json_object *tags, *events, *uuids;
1555
1556         memset(&context, 0, sizeof context);
1557         context.trace = trace;
1558         context.req = req;
1559
1560         /* special: boolean value */
1561         if (!wrap_json_unpack(args, "b", &rc)) {
1562                 if (rc) {
1563                         pthread_mutex_lock(&trace->mutex);
1564                         trace_unhook(trace, NULL, NULL, NULL);
1565                         trace_cleanup(trace);
1566                         pthread_mutex_unlock(&trace->mutex);
1567                 }
1568                 return 0;
1569         }
1570
1571         tags = events = uuids = NULL;
1572         rc = wrap_json_unpack(args, "{s?o s?o s?o}",
1573                         "event", &events,
1574                         "tag", &tags,
1575                         "uuid", &uuids);
1576
1577         if (rc < 0 || !(events || tags || uuids)) {
1578                 afb_req_fail(req, "error-detected", "bad drop arguments");
1579                 return -1;
1580         }
1581
1582         pthread_mutex_lock(&trace->mutex);
1583
1584         if (tags)
1585                 wrap_json_optarray_for_all(tags, drop_tag, &context);
1586
1587         if (events)
1588                 wrap_json_optarray_for_all(events, drop_event, &context);
1589
1590         if (uuids)
1591                 wrap_json_optarray_for_all(uuids, drop_session, &context);
1592
1593         trace_cleanup(trace);
1594
1595         pthread_mutex_unlock(&trace->mutex);
1596
1597         if (!context.errors)
1598                 return 0;
1599
1600         afb_req_fail(req, "error-detected", context.errors);
1601         free(context.errors);
1602         return -1;
1603 }
1604
1605 #endif