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