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