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