Fix false ***buffer overflow*** detection
[src/app-framework-binder.git] / src / afb-api-dbus.c
1 /*
2  * Copyright (C) 2015-2019 "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 #if WITH_DBUS_TRANSPARENCY
19
20 #define _GNU_SOURCE
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <assert.h>
26 #include <errno.h>
27
28 #include <systemd/sd-bus.h>
29 #include <json-c/json.h>
30 #if !defined(JSON_C_TO_STRING_NOSLASHESCAPE)
31 #define JSON_C_TO_STRING_NOSLASHESCAPE 0
32 #endif
33
34 #include <afb/afb-event-x2.h>
35
36 #include "afb-session.h"
37 #include "afb-msg-json.h"
38 #include "afb-api.h"
39 #include "afb-apiset.h"
40 #include "afb-api-dbus.h"
41 #include "afb-context.h"
42 #include "afb-cred.h"
43 #include "afb-evt.h"
44 #include "afb-xreq.h"
45
46 #include "verbose.h"
47 #include "systemd.h"
48 #include "jobs.h"
49
50 static const char DEFAULT_PATH_PREFIX[] = "/org/agl/afb/api/";
51
52 struct dbus_memo;
53 struct dbus_event;
54 struct origin;
55
56 /*
57  * The path given are of the form
58  *     system:/org/agl/afb/api/...
59  * or
60  *     user:/org/agl/afb/api/...
61  */
62 struct api_dbus
63 {
64         struct sd_bus *sdbus;   /* the bus */
65         char *path;             /* path of the object for the API */
66         char *name;             /* name/interface of the object */
67         char *api;              /* api name of the interface */
68         union {
69                 struct {
70                         struct sd_bus_slot *slot_broadcast;
71                         struct sd_bus_slot *slot_event;
72                         struct dbus_event *events;
73                         struct dbus_memo *memos;
74                 } client;
75                 struct {
76                         struct sd_bus_slot *slot_call;
77                         struct afb_evt_listener *listener; /* listener for broadcasted events */
78                         struct origin *origins;
79                         struct afb_apiset *apiset;
80                 } server;
81         };
82 };
83
84 /******************* common part **********************************/
85
86 /*
87  * create a structure api_dbus connected on either the system
88  * bus if 'system' is not null or on the user bus. The connection
89  * is established for either emiting/receiving on 'path' being of length
90  * 'pathlen'.
91  */
92 static struct api_dbus *make_api_dbus_3(int system, const char *path, size_t pathlen)
93 {
94         struct api_dbus *api;
95         struct sd_bus *sdbus;
96         char *ptr;
97
98         /* allocates the structure */
99         api = calloc(1, sizeof *api + 1 + pathlen + pathlen);
100         if (api == NULL) {
101                 errno = ENOMEM;
102                 goto error;
103         }
104
105         /* init the structure's strings */
106
107         /* path is copied after the struct */
108         api->path = (void*)(api+1);
109         strcpy(api->path, path);
110
111         /* api name is at the end of the path */
112         api->api = strrchr(api->path, '/');
113         if (api->api == NULL) {
114                 errno = EINVAL;
115                 goto error2;
116         }
117         api->api++;
118         if (!afb_api_is_valid_name(api->api)) {
119                 errno = EINVAL;
120                 goto error2;
121         }
122
123         /* the name/interface is copied after the path */
124         api->name = &api->path[pathlen + 1];
125         strcpy(api->name, &path[1]);
126         ptr = strchr(api->name, '/');
127         while(ptr != NULL) {
128                 *ptr = '.';
129                 ptr = strchr(ptr, '/');
130         }
131
132         /* choose the bus */
133         jobs_acquire_event_manager();
134         sdbus = (system ? systemd_get_system_bus : systemd_get_user_bus)();
135         if (sdbus == NULL)
136                 goto error2;
137
138         api->sdbus = sdbus;
139         return api;
140
141 error2:
142         free(api);
143 error:
144         return NULL;
145 }
146
147 /*
148  * create a structure api_dbus connected on either the system
149  * bus if 'system' is not null or on the user bus. The connection
150  * is established for either emiting/receiving on 'path'.
151  * If 'path' is not absolute, it is prefixed with DEFAULT_PATH_PREFIX.
152  */
153 static struct api_dbus *make_api_dbus_2(int system, const char *path)
154 {
155         size_t len;
156         char *ptr;
157
158         /* check the length of the path */
159         len = strlen(path);
160         if (len == 0) {
161                 errno = EINVAL;
162                 return NULL;
163         }
164
165         /* if the path is absolute, creation now */
166         if (path[0] == '/')
167                 return make_api_dbus_3(system, path, len);
168
169         /* compute the path prefixed with DEFAULT_PATH_PREFIX */
170         assert(strlen(DEFAULT_PATH_PREFIX) > 0);
171         assert(DEFAULT_PATH_PREFIX[strlen(DEFAULT_PATH_PREFIX) - 1] == '/');
172         len += strlen(DEFAULT_PATH_PREFIX);
173         ptr = alloca(len + 1);
174         strcpy(stpcpy(ptr, DEFAULT_PATH_PREFIX), path);
175
176         /* creation for prefixed path */
177         return make_api_dbus_3(system, ptr, len);
178 }
179
180 /*
181  * create a structure api_dbus connected either emiting/receiving
182  * on 'path'.
183  * The path can be prefixed with "system:" or "user:" to select
184  * either the user or the system D-Bus. If none is set then user's
185  * bus is selected.
186  * If remaining 'path' is not absolute, it is prefixed with
187  * DEFAULT_PATH_PREFIX.
188  */
189 static struct api_dbus *make_api_dbus(const char *path)
190 {
191         const char *ptr;
192         size_t preflen;
193
194         /* retrieves the prefix "scheme-like" part */
195         ptr = strchr(path, ':');
196         if (ptr == NULL)
197                 return make_api_dbus_2(0, path);
198
199         /* check the prefix part */
200         preflen = (size_t)(ptr - path);
201         if (strncmp(path, "system", preflen) == 0)
202                 return make_api_dbus_2(1, ptr + 1);
203
204         if (strncmp(path, "user", preflen) == 0)
205                 return make_api_dbus_2(0, ptr + 1);
206
207         /* TODO: connect to a foreign D-Bus? */
208         errno = EINVAL;
209         return NULL;
210 }
211
212 static void destroy_api_dbus(struct api_dbus *api)
213 {
214         free(api);
215 }
216
217 /******************* client part **********************************/
218
219 /*
220  * structure for recording query data
221  */
222 struct dbus_memo {
223         struct dbus_memo *next;         /* the next memo */
224         struct api_dbus *api;           /* the dbus api */
225         struct afb_xreq *xreq;          /* the request */
226         uint64_t msgid;                 /* the message identifier */
227 };
228
229 struct dbus_event
230 {
231         struct dbus_event *next;
232         struct afb_event_x2 *event;
233         int id;
234         int refcount;
235 };
236
237 /* allocates and init the memorizing data */
238 static struct dbus_memo *api_dbus_client_memo_make(struct api_dbus *api, struct afb_xreq *xreq)
239 {
240         struct dbus_memo *memo;
241
242         memo = malloc(sizeof *memo);
243         if (memo != NULL) {
244                 afb_xreq_unhooked_addref(xreq);
245                 memo->xreq = xreq;
246                 memo->msgid = 0;
247                 memo->api = api;
248                 memo->next = api->client.memos;
249                 api->client.memos = memo;
250         }
251         return memo;
252 }
253
254 /* free and release the memorizing data */
255 static void api_dbus_client_memo_destroy(struct dbus_memo *memo)
256 {
257         struct dbus_memo **prv;
258
259         prv = &memo->api->client.memos;
260         while (*prv != NULL) {
261                 if (*prv == memo) {
262                         *prv = memo->next;
263                         break;
264                 }
265                 prv = &(*prv)->next;
266         }
267
268         afb_xreq_unhooked_unref(memo->xreq);
269         free(memo);
270 }
271
272 /* search a memorized request */
273 static struct dbus_memo *api_dbus_client_memo_search(struct api_dbus *api, uint64_t msgid)
274 {
275         struct dbus_memo *memo;
276
277         memo = api->client.memos;
278         while (memo != NULL && memo->msgid != msgid)
279                 memo = memo->next;
280
281         return memo;
282 }
283
284 /* callback when received answer */
285 static int api_dbus_client_on_reply(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
286 {
287         int rc;
288         struct dbus_memo *memo;
289         const char *json, *error, *info;
290         struct json_object *object;
291         enum json_tokener_error jerr;
292
293         /* retrieve the recorded data */
294         memo = userdata;
295
296         /* get the answer */
297         rc = sd_bus_message_read(message, "sss", &json, &error, &info);
298         if (rc < 0) {
299                 /* failing to have the answer */
300                 afb_xreq_reply(memo->xreq, NULL, "error", "dbus error");
301         } else {
302                 /* report the answer */
303                 if (!*json)
304                         object = NULL;
305                 else {
306                         object = json_tokener_parse_verbose(json, &jerr);
307                         if (jerr != json_tokener_success)
308                                 object = json_object_new_string(json);
309                 }
310                 afb_xreq_reply(memo->xreq, object, *error ? error : NULL, *info ? info : NULL);
311         }
312         api_dbus_client_memo_destroy(memo);
313         return 1;
314 }
315
316 /* on call, propagate it to the dbus service */
317 static void api_dbus_client_call(void *closure, struct afb_xreq *xreq)
318 {
319         struct api_dbus *api = closure;
320         size_t size;
321         int rc;
322         struct dbus_memo *memo;
323         struct sd_bus_message *msg;
324         const char *creds;
325
326         /* create the recording data */
327         memo = api_dbus_client_memo_make(api, xreq);
328         if (memo == NULL) {
329                 afb_xreq_reply(memo->xreq, NULL, "error", "out of memory");
330                 return;
331         }
332
333         /* creates the message */
334         msg = NULL;
335         rc = sd_bus_message_new_method_call(api->sdbus, &msg, api->name, api->path, api->name, xreq->request.called_verb);
336         if (rc < 0)
337                 goto error;
338
339         creds = xreq_on_behalf_cred_export(xreq);
340         rc = sd_bus_message_append(msg, "ssus",
341                         afb_xreq_raw(xreq, &size),
342                         afb_session_uuid(xreq->context.session),
343                         (uint32_t)xreq->context.flags,
344                         creds ?: "");
345         if (rc < 0)
346                 goto error;
347
348         /* makes the call */
349         rc = sd_bus_call_async(api->sdbus, NULL, msg, api_dbus_client_on_reply, memo, (uint64_t)-1);
350         if (rc < 0)
351                 goto error;
352
353         rc = sd_bus_message_get_cookie(msg, &memo->msgid);
354         if (rc >= 0)
355                 goto end;
356
357 error:
358         /* if there was an error report it directly */
359         errno = -rc;
360         afb_xreq_reply(memo->xreq, NULL, "error", "dbus error");
361         api_dbus_client_memo_destroy(memo);
362 end:
363         sd_bus_message_unref(msg);
364 }
365
366 /* receives broadcasted events */
367 static int api_dbus_client_on_broadcast_event(sd_bus_message *m, void *userdata, sd_bus_error *ret_error)
368 {
369         struct json_object *object;
370         const char *event, *data;
371         enum json_tokener_error jerr;
372         int rc = sd_bus_message_read(m, "ss", &event, &data);
373         if (rc < 0)
374                 ERROR("unreadable broadcasted event");
375         else {
376                 object = json_tokener_parse_verbose(data, &jerr);
377                 if (jerr != json_tokener_success)
378                         object = json_object_new_string(data);
379                 afb_evt_broadcast(event, object);
380         }
381         return 1;
382 }
383
384 /* search the eventid */
385 static struct dbus_event *api_dbus_client_event_search(struct api_dbus *api, int id, const char *name)
386 {
387         struct dbus_event *ev;
388
389         ev = api->client.events;
390         while (ev != NULL && (ev->id != id || 0 != strcmp(afb_evt_event_x2_fullname(ev->event), name)))
391                 ev = ev->next;
392
393         return ev;
394 }
395
396 /* adds an eventid */
397 static void api_dbus_client_event_create(struct api_dbus *api, int id, const char *name)
398 {
399         struct dbus_event *ev;
400
401         /* check conflicts */
402         ev = api_dbus_client_event_search(api, id, name);
403         if (ev != NULL) {
404                 ev->refcount++;
405                 return;
406         }
407
408         /* no conflict, try to add it */
409         ev = malloc(sizeof *ev);
410         if (ev != NULL) {
411                 ev->event = afb_evt_event_x2_create(name);
412                 if (ev->event == NULL)
413                         free(ev);
414                 else {
415                         ev->refcount = 1;
416                         ev->id = id;
417                         ev->next = api->client.events;
418                         api->client.events = ev;
419                         return;
420                 }
421         }
422         ERROR("can't create event %s, out of memory", name);
423 }
424
425 /* removes an eventid */
426 static void api_dbus_client_event_drop(struct api_dbus *api, int id, const char *name)
427 {
428         struct dbus_event *ev, **prv;
429
430         /* retrieves the event */
431         ev = api_dbus_client_event_search(api, id, name);
432         if (ev == NULL) {
433                 ERROR("event %s not found", name);
434                 return;
435         }
436
437         /* decrease the reference count */
438         if (--ev->refcount)
439                 return;
440
441         /* unlinks the event */
442         prv = &api->client.events;
443         while (*prv != ev)
444                 prv = &(*prv)->next;
445         *prv = ev->next;
446
447         /* destroys the event */
448         afb_evt_event_x2_unref(ev->event);
449         free(ev);
450 }
451
452 /* pushs an event */
453 static void api_dbus_client_event_push(struct api_dbus *api, int id, const char *name, const char *data)
454 {
455         struct json_object *object;
456         struct dbus_event *ev;
457         enum json_tokener_error jerr;
458
459         /* retrieves the event */
460         ev = api_dbus_client_event_search(api, id, name);
461         if (ev == NULL) {
462                 ERROR("event %s not found", name);
463                 return;
464         }
465
466         /* destroys the event */
467         object = json_tokener_parse_verbose(data, &jerr);
468         if (jerr != json_tokener_success)
469                 object = json_object_new_string(data);
470         afb_evt_event_x2_push(ev->event, object);
471 }
472
473 /* subscribes an event */
474 static void api_dbus_client_event_subscribe(struct api_dbus *api, int id, const char *name, uint64_t msgid)
475 {
476         int rc;
477         struct dbus_event *ev;
478         struct dbus_memo *memo;
479
480         /* retrieves the event */
481         ev = api_dbus_client_event_search(api, id, name);
482         if (ev == NULL) {
483                 ERROR("event %s not found", name);
484                 return;
485         }
486
487         /* retrieves the memo */
488         memo = api_dbus_client_memo_search(api, msgid);
489         if (memo == NULL) {
490                 ERROR("message not found");
491                 return;
492         }
493
494         /* subscribe the request to the event */
495         rc = afb_xreq_subscribe(memo->xreq, ev->event);
496         if (rc < 0)
497                 ERROR("can't subscribe: %m");
498 }
499
500 /* unsubscribes an event */
501 static void api_dbus_client_event_unsubscribe(struct api_dbus *api, int id, const char *name, uint64_t msgid)
502 {
503         int rc;
504         struct dbus_event *ev;
505         struct dbus_memo *memo;
506
507         /* retrieves the event */
508         ev = api_dbus_client_event_search(api, id, name);
509         if (ev == NULL) {
510                 ERROR("event %s not found", name);
511                 return;
512         }
513
514         /* retrieves the memo */
515         memo = api_dbus_client_memo_search(api, msgid);
516         if (memo == NULL) {
517                 ERROR("message not found");
518                 return;
519         }
520
521         /* unsubscribe the request from the event */
522         rc = afb_xreq_unsubscribe(memo->xreq, ev->event);
523         if (rc < 0)
524                 ERROR("can't unsubscribe: %m");
525 }
526
527 /* receives calls for event */
528 static int api_dbus_client_on_manage_event(sd_bus_message *m, void *userdata, sd_bus_error *ret_error)
529 {
530         const char *eventname, *data;
531         int rc;
532         int32_t eventid;
533         uint8_t order;
534         struct api_dbus *api;
535         uint64_t msgid;
536
537         /* check if expected message */
538         api = userdata;
539         if (0 != strcmp(api->name, sd_bus_message_get_interface(m)))
540                 return 0; /* not the expected interface */
541         if (0 != strcmp("event", sd_bus_message_get_member(m)))
542                 return 0; /* not the expected member */
543         if (sd_bus_message_get_expect_reply(m))
544                 return 0; /* not the expected type of message */
545
546         /* reads the message */
547         rc = sd_bus_message_read(m, "yisst", &order, &eventid, &eventname, &data, &msgid);
548         if (rc < 0) {
549                 ERROR("unreadable event");
550                 return 1;
551         }
552
553         /* what is the order ? */
554         switch ((char)order) {
555         case '+': /* creates the event */
556                 api_dbus_client_event_create(api, eventid, eventname);
557                 break;
558         case '-': /* drops the event */
559                 api_dbus_client_event_drop(api, eventid, eventname);
560                 break;
561         case '!': /* pushs the event */
562                 api_dbus_client_event_push(api, eventid, eventname, data);
563                 break;
564         case 'S': /* subscribe event for a request */
565                 api_dbus_client_event_subscribe(api, eventid, eventname, msgid);
566                 break;
567         case 'U': /* unsubscribe event for a request */
568                 api_dbus_client_event_unsubscribe(api, eventid, eventname, msgid);
569                 break;
570         default:
571                 /* unexpected order */
572                 ERROR("unexpected order '%c' received", (char)order);
573                 break;
574         }
575         return 1;
576 }
577
578 static struct afb_api_itf dbus_api_itf = {
579         .call = api_dbus_client_call
580 };
581
582 /* adds a afb-dbus-service client api */
583 int afb_api_dbus_add_client(const char *path, struct afb_apiset *declare_set, struct afb_apiset *call_set)
584 {
585         int rc;
586         struct api_dbus *api;
587         struct afb_api_item afb_api;
588         char *match;
589
590         /* create the dbus client api */
591         api = make_api_dbus(path);
592         if (api == NULL)
593                 goto error;
594
595         /* connect to broadcasted events */
596         rc = asprintf(&match, "type='signal',path='%s',interface='%s',member='broadcast'", api->path, api->name);
597         if (rc < 0) {
598                 errno = ENOMEM;
599                 ERROR("out of memory");
600                 goto error;
601         }
602         rc = sd_bus_add_match(api->sdbus, &api->client.slot_broadcast, match, api_dbus_client_on_broadcast_event, api);
603         free(match);
604         if (rc < 0) {
605                 errno = -rc;
606                 ERROR("can't add dbus match %s for %s", api->path, api->name);
607                 goto error;
608         }
609
610         /* connect to event management */
611         rc = sd_bus_add_object(api->sdbus, &api->client.slot_event, api->path, api_dbus_client_on_manage_event, api);
612         if (rc < 0) {
613                 errno = -rc;
614                 ERROR("can't add dbus object %s for %s", api->path, api->name);
615                 goto error;
616         }
617
618         /* record it as an API */
619         afb_api.closure = api;
620         afb_api.itf = &dbus_api_itf;
621         afb_api.group = NULL;
622         if (afb_apiset_add(declare_set, api->api, afb_api) < 0)
623                 goto error2;
624
625         return 0;
626
627 error2:
628         destroy_api_dbus(api);
629 error:
630         return -1;
631 }
632
633 /******************* event structures for server part **********************************/
634
635 static void afb_api_dbus_server_event_add(void *closure, const char *event, int eventid);
636 static void afb_api_dbus_server_event_remove(void *closure, const char *event, int eventid);
637 static void afb_api_dbus_server_event_push(void *closure, const char *event, int eventid, struct json_object *object);
638 static void afb_api_dbus_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object);
639
640 /* the interface for events broadcasting */
641 static const struct afb_evt_itf evt_broadcast_itf = {
642         .broadcast = afb_api_dbus_server_event_broadcast,
643 };
644
645 /* the interface for events pushing */
646 static const struct afb_evt_itf evt_push_itf = {
647         .push = afb_api_dbus_server_event_push,
648         .add = afb_api_dbus_server_event_add,
649         .remove = afb_api_dbus_server_event_remove
650 };
651
652 /******************* origin description part for server *****************************/
653
654 struct origin
655 {
656         /* link to next different origin */
657         struct origin *next;
658
659         /* the server dbus-api */
660         struct api_dbus *api;
661
662         /* count of references */
663         int refcount;
664
665         /* credentials of the origin */
666         struct afb_cred *cred;
667
668         /* the origin */
669         char name[];
670 };
671
672 /* get the credentials for the message */
673 static void init_origin_creds(struct origin *origin)
674 {
675         int rc;
676         sd_bus_creds *c;
677         uid_t uid;
678         gid_t gid;
679         pid_t pid;
680         const char *context;
681
682         rc = sd_bus_get_name_creds(origin->api->sdbus, origin->name,
683                         SD_BUS_CREDS_PID|SD_BUS_CREDS_UID|SD_BUS_CREDS_GID|SD_BUS_CREDS_SELINUX_CONTEXT,
684                         &c);
685         if (rc < 0)
686                 origin->cred = NULL;
687         else {
688                 afb_cred_unref(origin->cred);
689                 sd_bus_creds_get_uid(c, &uid);
690                 sd_bus_creds_get_gid(c, &gid);
691                 sd_bus_creds_get_pid(c, &pid);
692                 sd_bus_creds_get_selinux_context(c, &context);
693                 origin->cred = afb_cred_create(uid, gid, pid, context);
694                 sd_bus_creds_unref(c);
695         }
696 }
697
698 static struct origin *afb_api_dbus_server_origin_get(struct api_dbus *api, const char *sender)
699 {
700         struct origin *origin;
701
702         /* searchs for an existing origin */
703         origin = api->server.origins;
704         while (origin != NULL) {
705                 if (0 == strcmp(origin->name, sender)) {
706                         origin->refcount++;
707                         return origin;
708                 }
709                 origin = origin->next;
710         }
711
712         /* not found, create it */
713         origin = malloc(strlen(sender) + 1 + sizeof *origin);
714         if (origin == NULL)
715                 errno = ENOMEM;
716         else {
717                 origin->api = api;
718                 origin->refcount = 1;
719                 strcpy(origin->name, sender);
720                 init_origin_creds(origin);
721                 origin->next = api->server.origins;
722                 api->server.origins = origin;
723         }
724         return origin;
725 }
726
727 static void afb_api_dbus_server_origin_unref(struct origin *origin)
728 {
729         if (!--origin->refcount) {
730                 struct origin **prv;
731
732                 prv = &origin->api->server.origins;
733                 while(*prv != origin)
734                         prv = &(*prv)->next;
735                 *prv = origin->next;
736                 afb_cred_unref(origin->cred);
737                 free(origin);
738         }
739 }
740
741 struct listener
742 {
743         /* link to next different origin */
744         struct origin *origin;
745
746         /* the listener of events */
747         struct afb_evt_listener *listener;
748 };
749
750 static void afb_api_dbus_server_listener_free(struct listener *listener)
751 {
752         afb_evt_listener_unref(listener->listener);
753         afb_api_dbus_server_origin_unref(listener->origin);
754         free(listener);
755 }
756
757 static struct listener *afb_api_dbus_server_listener_get(struct api_dbus *api, const char *sender, struct afb_session *session)
758 {
759         int rc;
760         struct listener *listener;
761         struct origin *origin;
762
763         /* get the origin */
764         origin = afb_api_dbus_server_origin_get(api, sender);
765         if (origin == NULL)
766                 return NULL;
767
768         /* retrieves the stored listener */
769         listener = afb_session_get_cookie(session, origin);
770         if (listener != NULL) {
771                 /* found */
772                 afb_api_dbus_server_origin_unref(origin);
773                 return listener;
774         }
775
776         /* creates the listener */
777         listener = malloc(sizeof *listener);
778         if (listener == NULL)
779                 errno = ENOMEM;
780         else {
781                 listener->origin = origin;
782                 listener->listener = afb_evt_listener_create(&evt_push_itf, origin);
783                 if (listener->listener != NULL) {
784                         rc = afb_session_set_cookie(session, origin, listener, (void*)afb_api_dbus_server_listener_free);
785                         if (rc == 0)
786                                 return listener;
787                         afb_evt_listener_unref(listener->listener);
788                 }
789                 free(listener);
790         }
791         afb_api_dbus_server_origin_unref(origin);
792         return NULL;
793 }
794
795 /******************* dbus request part for server *****************/
796
797 /**
798  * Structure for a dbus request
799  */
800 struct dbus_req {
801         struct afb_xreq xreq;           /**< the xreq of the request */
802         sd_bus_message *message;        /**< the incoming request message */
803         const char *request;            /**< the readen request as string */
804         struct json_object *json;       /**< the readen request as object */
805         struct listener *listener;      /**< the listener for events */
806 };
807
808 /* decrement the reference count of the request and free/release it on falling to null */
809 static void dbus_req_destroy(struct afb_xreq *xreq)
810 {
811         struct dbus_req *dreq = CONTAINER_OF_XREQ(struct dbus_req, xreq);
812
813         afb_context_disconnect(&dreq->xreq.context);
814         json_object_put(dreq->json);
815         sd_bus_message_unref(dreq->message);
816         free(dreq);
817 }
818
819 /* get the object of the request */
820 static struct json_object *dbus_req_json(struct afb_xreq *xreq)
821 {
822         struct dbus_req *dreq = CONTAINER_OF_XREQ(struct dbus_req, xreq);
823
824         return dreq->json;
825 }
826
827 void dbus_req_raw_reply(struct afb_xreq *xreq, struct json_object *obj, const char *error, const char *info)
828 {
829         struct dbus_req *dreq = CONTAINER_OF_XREQ(struct dbus_req, xreq);
830         int rc;
831
832         rc = sd_bus_reply_method_return(dreq->message, "sss",
833                 obj ? json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN|JSON_C_TO_STRING_NOSLASHESCAPE) : "",
834                 error ? : "",
835                 info ? : "");
836         if (rc < 0)
837                 ERROR("sending the reply failed");
838 }
839
840 static void afb_api_dbus_server_event_send(struct origin *origin, char order, const char *event, int eventid, const char *data, uint64_t msgid);
841
842 static int dbus_req_subscribe(struct afb_xreq *xreq, struct afb_event_x2 *event)
843 {
844         struct dbus_req *dreq = CONTAINER_OF_XREQ(struct dbus_req, xreq);
845         uint64_t msgid;
846         int rc;
847
848         rc = afb_evt_event_x2_add_watch(dreq->listener->listener, event);
849         sd_bus_message_get_cookie(dreq->message, &msgid);
850         afb_api_dbus_server_event_send(dreq->listener->origin, 'S', afb_evt_event_x2_fullname(event), afb_evt_event_x2_id(event), "", msgid);
851         return rc;
852 }
853
854 static int dbus_req_unsubscribe(struct afb_xreq *xreq, struct afb_event_x2 *event)
855 {
856         struct dbus_req *dreq = CONTAINER_OF_XREQ(struct dbus_req, xreq);
857         uint64_t msgid;
858         int rc;
859
860         sd_bus_message_get_cookie(dreq->message, &msgid);
861         afb_api_dbus_server_event_send(dreq->listener->origin, 'U', afb_evt_event_x2_fullname(event), afb_evt_event_x2_id(event), "", msgid);
862         rc = afb_evt_event_x2_remove_watch(dreq->listener->listener, event);
863         return rc;
864 }
865
866 const struct afb_xreq_query_itf afb_api_dbus_xreq_itf = {
867         .json = dbus_req_json,
868         .reply = dbus_req_raw_reply,
869         .unref = dbus_req_destroy,
870         .subscribe = dbus_req_subscribe,
871         .unsubscribe = dbus_req_unsubscribe,
872 };
873
874 /******************* server part **********************************/
875
876 static void afb_api_dbus_server_event_send(struct origin *origin, char order, const char *event, int eventid, const char *data, uint64_t msgid)
877 {
878         int rc;
879         struct api_dbus *api;
880         struct sd_bus_message *msg;
881
882         api = origin->api;
883         msg = NULL;
884
885         rc = sd_bus_message_new_method_call(api->sdbus, &msg, origin->name, api->path, api->name, "event");
886         if (rc < 0)
887                 goto error;
888
889         rc = sd_bus_message_append(msg, "yisst", (uint8_t)order, (int32_t)eventid, event, data, msgid);
890         if (rc < 0)
891                 goto error;
892
893         rc = sd_bus_send(api->sdbus, msg, NULL); /* NULL for cookie implies no expected reply */
894         if (rc >= 0)
895                 goto end;
896
897 error:
898         ERROR("error while send event %c%s(%d) to %s", order, event, eventid, origin->name);
899 end:
900         sd_bus_message_unref(msg);
901 }
902
903 static void afb_api_dbus_server_event_add(void *closure, const char *event, int eventid)
904 {
905         afb_api_dbus_server_event_send(closure, '+', event, eventid, "", 0);
906 }
907
908 static void afb_api_dbus_server_event_remove(void *closure, const char *event, int eventid)
909 {
910         afb_api_dbus_server_event_send(closure, '-', event, eventid, "", 0);
911 }
912
913 static void afb_api_dbus_server_event_push(void *closure, const char *event, int eventid, struct json_object *object)
914 {
915         const char *data = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN|JSON_C_TO_STRING_NOSLASHESCAPE);
916         afb_api_dbus_server_event_send(closure, '!', event, eventid, data, 0);
917         json_object_put(object);
918 }
919
920 static void afb_api_dbus_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object)
921 {
922         int rc;
923         struct api_dbus *api;
924
925         api = closure;
926         rc = sd_bus_emit_signal(api->sdbus, api->path, api->name, "broadcast",
927                         "ss", event, json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN|JSON_C_TO_STRING_NOSLASHESCAPE));
928         if (rc < 0)
929                 ERROR("error while broadcasting event %s", event);
930         json_object_put(object);
931 }
932
933 /* called when the object for the service is called */
934 static int api_dbus_server_on_object_called(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
935 {
936         int rc;
937         const char *method;
938         const char *uuid;
939         const char *creds;
940         struct dbus_req *dreq;
941         struct api_dbus *api = userdata;
942         uint32_t flags;
943         struct afb_session *session;
944         struct listener *listener;
945         enum json_tokener_error jerr;
946
947         /* check the interface */
948         if (strcmp(sd_bus_message_get_interface(message), api->name) != 0)
949                 return 0;
950
951         /* get the method */
952         method = sd_bus_message_get_member(message);
953
954         /* create the request */
955         dreq = calloc(1 , sizeof *dreq);
956         if (dreq == NULL)
957                 goto out_of_memory;
958
959         /* get the data */
960         rc = sd_bus_message_read(message, "ssus", &dreq->request, &uuid, &flags, &creds);
961         if (rc < 0) {
962                 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_INVALID_SIGNATURE, "invalid signature");
963                 goto error;
964         }
965
966         /* connect to the context */
967         afb_xreq_init(&dreq->xreq, &afb_api_dbus_xreq_itf);
968         if (afb_context_connect(&dreq->xreq.context, uuid, NULL) < 0)
969                 goto out_of_memory;
970         session = dreq->xreq.context.session;
971
972         /* get the listener */
973         listener = afb_api_dbus_server_listener_get(api, sd_bus_message_get_sender(message), session);
974         if (listener == NULL)
975                 goto out_of_memory;
976
977         /* fulfill the request and emit it */
978         dreq->xreq.context.flags = flags;
979         dreq->xreq.cred = afb_cred_mixed_on_behalf_import(listener->origin->cred, uuid, creds && creds[0] ? creds : NULL);
980         dreq->message = sd_bus_message_ref(message);
981         dreq->json = json_tokener_parse_verbose(dreq->request, &jerr);
982         if (jerr != json_tokener_success) {
983                 /* lazy error detection of json request. Is it to improve? */
984                 dreq->json = json_object_new_string(dreq->request);
985         }
986         dreq->listener = listener;
987         dreq->xreq.request.called_api = api->api;
988         dreq->xreq.request.called_verb = method;
989         afb_xreq_process(&dreq->xreq, api->server.apiset);
990         return 1;
991
992 out_of_memory:
993         sd_bus_reply_method_errorf(message, SD_BUS_ERROR_NO_MEMORY, "out of memory");
994 error:
995         free(dreq);
996         return 1;
997 }
998
999 /* create the service */
1000 int afb_api_dbus_add_server(const char *path, struct afb_apiset *declare_set, struct afb_apiset *call_set)
1001 {
1002         int rc;
1003         struct api_dbus *api;
1004
1005         /* get the dbus api object connected */
1006         api = make_api_dbus(path);
1007         if (api == NULL)
1008                 goto error;
1009
1010         /* request the service object name */
1011         rc = sd_bus_request_name(api->sdbus, api->name, 0);
1012         if (rc < 0) {
1013                 errno = -rc;
1014                 ERROR("can't register name %s", api->name);
1015                 goto error2;
1016         }
1017
1018         /* connect the service to the dbus object */
1019         rc = sd_bus_add_object(api->sdbus, &api->server.slot_call, api->path, api_dbus_server_on_object_called, api);
1020         if (rc < 0) {
1021                 errno = -rc;
1022                 ERROR("can't add dbus object %s for %s", api->path, api->name);
1023                 goto error3;
1024         }
1025         INFO("afb service over dbus installed, name %s, path %s", api->name, api->path);
1026
1027         api->server.listener = afb_evt_listener_create(&evt_broadcast_itf, api);
1028         api->server.apiset = afb_apiset_addref(call_set);
1029         return 0;
1030 error3:
1031         sd_bus_release_name(api->sdbus, api->name);
1032 error2:
1033         destroy_api_dbus(api);
1034 error:
1035         return -1;
1036 }
1037
1038 #endif
1039