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