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