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