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