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