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