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