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