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