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