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