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