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