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