api-dbus: improves 'dbus_req_json'
[src/app-framework-binder.git] / src / afb-api-dbus.c
1 /*
2  * Copyright (C) 2015, 2016 "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 "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(struct api_dbus *api, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
321 {
322         size_t size;
323         int rc;
324         char *method = strndupa(verb, lenverb);
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, method);
338         if (rc < 0)
339                 goto error;
340
341         rc = sd_bus_message_append(msg, "ssu",
342                         afb_req_raw(req, &size),
343                         ctxClientGetUuid(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(struct api_dbus *api, int share_session, int onneed)
367 {
368         /* not an error when onneed */
369         if (onneed != 0)
370                 return 0;
371
372         /* already started: it is an error */
373         ERROR("The Dbus binding %s is not a startable service", api->name);
374         return -1;
375 }
376
377 /* receives broadcasted events */
378 static int api_dbus_client_on_broadcast_event(sd_bus_message *m, void *userdata, sd_bus_error *ret_error)
379 {
380         struct json_object *object;
381         const char *event, *data;
382         int rc = sd_bus_message_read(m, "ss", &event, &data);
383         if (rc < 0)
384                 ERROR("unreadable broadcasted event");
385         else {
386                 object = json_tokener_parse(data);
387                 afb_evt_broadcast(event, object);
388         }
389         return 1;
390 }
391
392 /* search the event */
393 static struct dbus_event *api_dbus_client_event_search(struct api_dbus *api, int id, const char *name)
394 {
395         struct dbus_event *ev;
396
397         ev = api->client.events;
398         while (ev != NULL && (ev->id != id || 0 != strcmp(afb_evt_event_name(ev->event), name)))
399                 ev = ev->next;
400
401         return ev;
402 }
403
404 /* adds an event */
405 static void api_dbus_client_event_create(struct api_dbus *api, int id, const char *name)
406 {
407         struct dbus_event *ev;
408
409         /* check conflicts */
410         ev = api_dbus_client_event_search(api, id, name);
411         if (ev != NULL) {
412                 ev->refcount++;
413                 return;
414         }
415
416         /* no conflict, try to add it */
417         ev = malloc(sizeof *ev);
418         if (ev != NULL) {
419                 ev->event = afb_evt_create_event(name);
420                 if (ev->event.closure == NULL)
421                         free(ev);
422                 else {
423                         ev->refcount = 1;
424                         ev->id = id;
425                         ev->next = api->client.events;
426                         api->client.events = ev;
427                         return;
428                 }
429         }
430         ERROR("can't create event %s, out of memory", name);
431 }
432
433 /* removes an event */
434 static void api_dbus_client_event_drop(struct api_dbus *api, int id, const char *name)
435 {
436         struct dbus_event *ev, **prv;
437
438         /* retrieves the event */
439         ev = api_dbus_client_event_search(api, id, name);
440         if (ev == NULL) {
441                 ERROR("event %s not found", name);
442                 return;
443         }
444
445         /* decrease the reference count */
446         if (--ev->refcount)
447                 return;
448
449         /* unlinks the event */
450         prv = &api->client.events;
451         while (*prv != ev)
452                 prv = &(*prv)->next;
453         *prv = ev->next;
454
455         /* destroys the event */
456         afb_event_drop(ev->event);
457         free(ev);
458 }
459
460 /* pushs an event */
461 static void api_dbus_client_event_push(struct api_dbus *api, int id, const char *name, const char *data)
462 {
463         struct json_object *object;
464         struct dbus_event *ev;
465
466         /* retrieves the event */
467         ev = api_dbus_client_event_search(api, id, name);
468         if (ev == NULL) {
469                 ERROR("event %s not found", name);
470                 return;
471         }
472
473         /* destroys the event */
474         object = json_tokener_parse(data);
475         afb_event_push(ev->event, object);
476 }
477
478 /* subscribes an event */
479 static void api_dbus_client_event_subscribe(struct api_dbus *api, int id, const char *name, uint64_t msgid)
480 {
481         int rc;
482         struct dbus_event *ev;
483         struct dbus_memo *memo;
484
485         /* retrieves the event */
486         ev = api_dbus_client_event_search(api, id, name);
487         if (ev == NULL) {
488                 ERROR("event %s not found", name);
489                 return;
490         }
491
492         /* retrieves the memo */
493         memo = api_dbus_client_memo_search(api, msgid);
494         if (memo == NULL) {
495                 ERROR("message not found");
496                 return;
497         }
498
499         /* subscribe the request to the event */
500         rc = afb_req_subscribe(memo->req, ev->event);
501         if (rc < 0)
502                 ERROR("can't subscribe: %m");
503 }
504
505 /* unsubscribes an event */
506 static void api_dbus_client_event_unsubscribe(struct api_dbus *api, int id, const char *name, uint64_t msgid)
507 {
508         int rc;
509         struct dbus_event *ev;
510         struct dbus_memo *memo;
511
512         /* retrieves the event */
513         ev = api_dbus_client_event_search(api, id, name);
514         if (ev == NULL) {
515                 ERROR("event %s not found", name);
516                 return;
517         }
518
519         /* retrieves the memo */
520         memo = api_dbus_client_memo_search(api, msgid);
521         if (memo == NULL) {
522                 ERROR("message not found");
523                 return;
524         }
525
526         /* unsubscribe the request from the event */
527         rc = afb_req_unsubscribe(memo->req, ev->event);
528         if (rc < 0)
529                 ERROR("can't unsubscribe: %m");
530 }
531
532 /* receives calls for event */
533 static int api_dbus_client_on_manage_event(sd_bus_message *m, void *userdata, sd_bus_error *ret_error)
534 {
535         const char *eventname, *data;
536         int rc;
537         int32_t eventid;
538         uint8_t order;
539         struct api_dbus *api;
540         uint64_t msgid;
541
542         /* check if expected message */
543         api = userdata;
544         if (0 != strcmp(api->name, sd_bus_message_get_interface(m)))
545                 return 0; /* not the expected interface */
546         if (0 != strcmp("event", sd_bus_message_get_member(m)))
547                 return 0; /* not the expected member */
548         if (sd_bus_message_get_expect_reply(m))
549                 return 0; /* not the expected type of message */
550
551         /* reads the message */
552         rc = sd_bus_message_read(m, "yisst", &order, &eventid, &eventname, &data, &msgid);
553         if (rc < 0) {
554                 ERROR("unreadable event");
555                 return 1;
556         }
557
558         /* what is the order ? */
559         switch ((char)order) {
560         case '+': /* creates the event */
561                 api_dbus_client_event_create(api, eventid, eventname);
562                 break;
563         case '-': /* drops the event */
564                 api_dbus_client_event_drop(api, eventid, eventname);
565                 break;
566         case '!': /* pushs the event */
567                 api_dbus_client_event_push(api, eventid, eventname, data);
568                 break;
569         case 'S': /* subscribe event for a request */
570                 api_dbus_client_event_subscribe(api, eventid, eventname, msgid);
571                 break;
572         case 'U': /* unsubscribe event for a request */
573                 api_dbus_client_event_unsubscribe(api, eventid, eventname, msgid);
574                 break;
575         default:
576                 /* unexpected order */
577                 ERROR("unexpected order '%c' received", (char)order);
578                 break;
579         }
580         return 1;
581 }
582
583 /* adds a afb-dbus-service client api */
584 int afb_api_dbus_add_client(const char *path)
585 {
586         int rc;
587         struct api_dbus *api;
588         struct afb_api afb_api;
589         char *match;
590
591         /* create the dbus client api */
592         api = make_api_dbus(path);
593         if (api == NULL)
594                 goto error;
595
596         /* connect to broadcasted events */
597         rc = asprintf(&match, "type='signal',path='%s',interface='%s',member='broadcast'", api->path, api->name);
598         if (rc < 0) {
599                 errno = ENOMEM;
600                 ERROR("out of memory");
601                 goto error;
602         }
603         rc = sd_bus_add_match(api->sdbus, &api->client.slot_broadcast, match, api_dbus_client_on_broadcast_event, api);
604         free(match);
605         if (rc < 0) {
606                 errno = -rc;
607                 ERROR("can't add dbus match %s for %s", api->path, api->name);
608                 goto error;
609         }
610
611         /* connect to event management */
612         rc = sd_bus_add_object(api->sdbus, &api->client.slot_event, api->path, api_dbus_client_on_manage_event, api);
613         if (rc < 0) {
614                 errno = -rc;
615                 ERROR("can't add dbus object %s for %s", api->path, api->name);
616                 goto error;
617         }
618
619         /* record it as an API */
620         afb_api.closure = api;
621         afb_api.call = (void*)api_dbus_client_call;
622         afb_api.service_start = (void*)api_dbus_service_start;
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 /******************* destination description part for server *****************************/
654
655 struct destination
656 {
657         /* link to next different destination */
658         struct destination *next;
659
660         /* the server dbus-api */
661         struct api_dbus *api;
662
663         /* count of references */
664         int refcount;
665
666         /* the destination */
667         char name[1];
668 };
669
670 static struct destination *afb_api_dbus_server_destination_get(struct api_dbus *api, const char *sender)
671 {
672         struct destination *destination;
673
674         /* searchs for an existing destination */
675         destination = api->server.destinations;
676         while (destination != NULL) {
677                 if (0 == strcmp(destination->name, sender)) {
678                         destination->refcount++;
679                         return destination;
680                 }
681                 destination = destination->next;
682         }
683
684         /* not found, create it */
685         destination = malloc(strlen(sender) + sizeof *destination);
686         if (destination == NULL)
687                 errno = ENOMEM;
688         else {
689                 destination->api = api;
690                 destination->refcount = 1;
691                 strcpy(destination->name, sender);
692                 destination->next = api->server.destinations;
693                 api->server.destinations = destination;
694         }
695         return destination;
696 }
697
698 static void afb_api_dbus_server_destination_unref(struct destination *destination)
699 {
700         if (!--destination->refcount) {
701                 struct destination **prv;
702
703                 prv = &destination->api->server.destinations;
704                 while(*prv != destination)
705                         prv = &(*prv)->next;
706                 *prv = destination->next;
707                 free(destination);
708         }
709 }
710
711 struct listener
712 {
713         /* link to next different destination */
714         struct destination *destination;
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_destination_unref(listener->destination);
724         free(listener);
725 }
726
727 static struct listener *afb_api_dbus_server_listerner_get(struct api_dbus *api, const char *sender, struct AFB_clientCtx *session)
728 {
729         int rc;
730         struct listener *listener;
731         struct destination *destination;
732
733         /* get the destination */
734         destination = afb_api_dbus_server_destination_get(api, sender);
735         if (destination == NULL)
736                 return NULL;
737
738         /* retrieves the stored listener */
739         listener = ctxClientCookieGet(session, destination);
740         if (listener != NULL) {
741                 /* found */
742                 afb_api_dbus_server_destination_unref(destination);
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->destination = destination;
752                 listener->listener = afb_evt_listener_create(&evt_push_itf, destination);
753                 if (listener->listener != NULL) {
754                         rc = ctxClientCookieSet(session, destination, 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_destination_unref(destination);
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_context context;     /* the context, should be THE FIRST */
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         int refcount;                   /* reference count of the request */
777 };
778
779 /* increment the reference count of the request */
780 static void dbus_req_addref(struct dbus_req *dreq)
781 {
782         dreq->refcount++;
783 }
784
785 /* decrement the reference count of the request and free/release it on falling to null */
786 static void dbus_req_unref(struct dbus_req *dreq)
787 {
788         if (dreq == NULL || --dreq->refcount)
789                 return;
790
791         afb_context_disconnect(&dreq->context);
792         json_object_put(dreq->json);
793         sd_bus_message_unref(dreq->message);
794         free(dreq);
795 }
796
797 /* get the object of the request */
798 static struct json_object *dbus_req_json(struct dbus_req *dreq)
799 {
800         if (dreq->json == NULL) {
801                 dreq->json = json_tokener_parse(dreq->request);
802                 if (dreq->json == NULL && strcmp(dreq->request, "null")) {
803                         /* lazy error detection of json request. Is it to improve? */
804                         dreq->json = json_object_new_string(dreq->request);
805                 }
806         }
807         return dreq->json;
808 }
809
810 /* get the argument of the request of 'name' */
811 static struct afb_arg dbus_req_get(struct dbus_req *dreq, const char *name)
812 {
813         return afb_msg_json_get_arg(dbus_req_json(dreq), name);
814 }
815
816 static void dbus_req_reply(struct dbus_req *dreq, uint8_t type, const char *first, const char *second)
817 {
818         int rc;
819         rc = sd_bus_reply_method_return(dreq->message,
820                         "yssu", type, first ? : "", second ? : "", (uint32_t)dreq->context.flags);
821         if (rc < 0)
822                 ERROR("sending the reply failed");
823 }
824
825 static void dbus_req_success(struct dbus_req *dreq, struct json_object *obj, const char *info)
826 {
827         dbus_req_reply(dreq, RETOK, json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN), info);
828 }
829
830 static void dbus_req_fail(struct dbus_req *dreq, const char *status, const char *info)
831 {
832         dbus_req_reply(dreq, RETERR, status, info);
833 }
834
835 static const char *dbus_req_raw(struct dbus_req *dreq, size_t *size)
836 {
837         if (size != NULL)
838                 *size = strlen(dreq->request);
839         return dreq->request;
840 }
841
842 static void dbus_req_send(struct dbus_req *dreq, const char *buffer, size_t size)
843 {
844         /* TODO: how to put sized buffer as strings? things aren't clear here!!! */
845         dbus_req_reply(dreq, RETRAW, buffer, "");
846 }
847
848 static void afb_api_dbus_server_event_send(struct destination *destination, char order, const char *event, int eventid, const char *data, uint64_t msgid);
849
850 static int dbus_req_subscribe(struct dbus_req *dreq, struct afb_event event)
851 {
852         uint64_t msgid;
853         int rc;
854
855         rc = afb_evt_add_watch(dreq->listener->listener, event);
856         sd_bus_message_get_cookie(dreq->message, &msgid);
857         afb_api_dbus_server_event_send(dreq->listener->destination, 'S', afb_evt_event_name(event), afb_evt_event_id(event), "", msgid);
858         return rc;
859 }
860
861 static int dbus_req_unsubscribe(struct dbus_req *dreq, struct afb_event event)
862 {
863         uint64_t msgid;
864         int rc;
865
866         sd_bus_message_get_cookie(dreq->message, &msgid);
867         afb_api_dbus_server_event_send(dreq->listener->destination, 'U', afb_evt_event_name(event), afb_evt_event_id(event), "", msgid);
868         rc = afb_evt_remove_watch(dreq->listener->listener, event);
869         return rc;
870 }
871
872 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);
873
874 const struct afb_req_itf afb_api_dbus_req_itf = {
875         .json = (void*)dbus_req_json,
876         .get = (void*)dbus_req_get,
877         .success = (void*)dbus_req_success,
878         .fail = (void*)dbus_req_fail,
879         .raw = (void*)dbus_req_raw,
880         .send = (void*)dbus_req_send,
881         .context_get = (void*)afb_context_get,
882         .context_set = (void*)afb_context_set,
883         .addref = (void*)dbus_req_addref,
884         .unref = (void*)dbus_req_unref,
885         .session_close = (void*)afb_context_close,
886         .session_set_LOA = (void*)afb_context_change_loa,
887         .subscribe = (void*)dbus_req_subscribe,
888         .unsubscribe = (void*)dbus_req_unsubscribe,
889         .subcall = (void*)dbus_req_subcall
890 };
891
892 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)
893 {
894         afb_subcall(&dreq->context, api, verb, args, callback, closure, (struct afb_req){ .itf = &afb_api_dbus_req_itf, .closure = dreq });
895 }
896
897 /******************* server part **********************************/
898
899 static void afb_api_dbus_server_event_send(struct destination *destination, char order, const char *event, int eventid, const char *data, uint64_t msgid)
900 {
901         int rc;
902         struct api_dbus *api;
903         struct sd_bus_message *msg;
904
905         api = destination->api;
906         msg = NULL;
907
908         rc = sd_bus_message_new_method_call(api->sdbus, &msg, destination->name, api->path, api->name, "event");
909         if (rc < 0)
910                 goto error;
911
912         rc = sd_bus_message_append(msg, "yisst", (uint8_t)order, (int32_t)eventid, event, data, msgid);
913         if (rc < 0)
914                 goto error;
915
916         rc = sd_bus_send(api->sdbus, msg, NULL); /* NULL for cookie implies no expected reply */
917         if (rc >= 0)
918                 goto end;
919
920 error:
921         ERROR("error while send event %c%s(%d) to %s", order, event, eventid, destination->name);
922 end:
923         sd_bus_message_unref(msg);
924 }
925
926 static void afb_api_dbus_server_event_add(void *closure, const char *event, int eventid)
927 {
928         afb_api_dbus_server_event_send(closure, '+', event, eventid, "", 0);
929 }
930
931 static void afb_api_dbus_server_event_remove(void *closure, const char *event, int eventid)
932 {
933         afb_api_dbus_server_event_send(closure, '-', event, eventid, "", 0);
934 }
935
936 static void afb_api_dbus_server_event_push(void *closure, const char *event, int eventid, struct json_object *object)
937 {
938         const char *data = json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN);
939         afb_api_dbus_server_event_send(closure, '!', event, eventid, data, 0);
940         json_object_put(object);
941 }
942
943 static void afb_api_dbus_server_event_broadcast(void *closure, const char *event, int eventid, struct json_object *object)
944 {
945         int rc;
946         struct api_dbus *api;
947
948         api = closure;
949         rc = sd_bus_emit_signal(api->sdbus, api->path, api->name, "broadcast",
950                         "ss", event, json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN));
951         if (rc < 0)
952                 ERROR("error while broadcasting event %s", event);
953         json_object_put(object);
954 }
955
956 /* called when the object for the service is called */
957 static int api_dbus_server_on_object_called(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
958 {
959         int rc;
960         const char *method;
961         const char *uuid;
962         struct dbus_req *dreq;
963         struct api_dbus *api = userdata;
964         struct afb_req areq;
965         uint32_t flags;
966         struct AFB_clientCtx *session;
967         struct listener *listener;
968
969         /* check the interface */
970         if (strcmp(sd_bus_message_get_interface(message), api->name) != 0)
971                 return 0;
972
973         /* get the method */
974         method = sd_bus_message_get_member(message);
975
976         /* create the request */
977         dreq = calloc(1 , sizeof *dreq);
978         if (dreq == NULL)
979                 goto out_of_memory;
980
981         /* get the data */
982         rc = sd_bus_message_read(message, "ssu", &dreq->request, &uuid, &flags);
983         if (rc < 0) {
984                 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_INVALID_SIGNATURE, "invalid signature");
985                 goto error;
986         }
987
988         /* connect to the context */
989         if (afb_context_connect(&dreq->context, uuid, NULL) < 0)
990                 goto out_of_memory;
991         session = dreq->context.session;
992
993         /* get the listener */
994         listener = afb_api_dbus_server_listerner_get(api, sd_bus_message_get_sender(message), session);
995         if (listener == NULL)
996                 goto out_of_memory;
997
998         /* fulfill the request and emit it */
999         dreq->context.flags = flags;
1000         dreq->message = sd_bus_message_ref(message);
1001         dreq->json = NULL;
1002         dreq->listener = listener;
1003         dreq->refcount = 1;
1004         areq.itf = &afb_api_dbus_req_itf;
1005         areq.closure = dreq;
1006         afb_apis_call_(areq, &dreq->context, api->api, method);
1007         dbus_req_unref(dreq);
1008         return 1;
1009
1010 out_of_memory:
1011         sd_bus_reply_method_errorf(message, SD_BUS_ERROR_NO_MEMORY, "out of memory");
1012 error:
1013         free(dreq);
1014         return 1;
1015 }
1016
1017 /* create the service */
1018 int afb_api_dbus_add_server(const char *path)
1019 {
1020         int rc;
1021         struct api_dbus *api;
1022
1023         /* get the dbus api object connected */
1024         api = make_api_dbus(path);
1025         if (api == NULL)
1026                 goto error;
1027
1028         /* request the service object name */
1029         rc = sd_bus_request_name(api->sdbus, api->name, 0);
1030         if (rc < 0) {
1031                 errno = -rc;
1032                 ERROR("can't register name %s", api->name);
1033                 goto error2;
1034         }
1035
1036         /* connect the service to the dbus object */
1037         rc = sd_bus_add_object(api->sdbus, &api->server.slot_call, api->path, api_dbus_server_on_object_called, api);
1038         if (rc < 0) {
1039                 errno = -rc;
1040                 ERROR("can't add dbus object %s for %s", api->path, api->name);
1041                 goto error3;
1042         }
1043         INFO("afb service over dbus installed, name %s, path %s", api->name, api->path);
1044
1045         api->server.listener = afb_evt_listener_create(&evt_broadcast_itf, api);
1046         return 0;
1047 error3:
1048         sd_bus_release_name(api->sdbus, api->name);
1049 error2:
1050         destroy_api_dbus(api);
1051 error:
1052         return -1;
1053 }
1054
1055