evt: handles broadcasting and tracking
[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 /*
46  * The path given are of the form
47  *     system:/org/agl/afb/api/...
48  * or
49  *     user:/org/agl/afb/api/...
50  */
51 struct api_dbus
52 {
53         struct sd_bus *sdbus;   /* the bus */
54         struct sd_bus_slot *slot; /* the slot */
55         char *path;             /* path of the object for the API */
56         char *name;             /* name/interface of the object */
57         char *api;              /* api name of the interface */
58         struct afb_evt_listener *listener;
59 };
60
61 #define RETOK   1
62 #define RETERR  2
63 #define RETRAW  3
64
65 /******************* common part **********************************/
66
67 /*
68  * create a structure api_dbus connected on either the system
69  * bus if 'system' is not null or on the user bus. The connection
70  * is established for either emiting/receiving on 'path' being of length
71  * 'pathlen'.
72  */
73 static struct api_dbus *make_api_dbus_3(int system, const char *path, size_t pathlen)
74 {
75         struct api_dbus *api;
76         struct sd_bus *sdbus;
77         char *ptr;
78
79         /* allocates the structure */
80         api = calloc(1, sizeof *api + 1 + pathlen + pathlen);
81         if (api == NULL) {
82                 errno = ENOMEM;
83                 goto error;
84         }
85
86         /* init the structure's strings */
87
88         /* path is copied after the struct */
89         api->path = (void*)(api+1);
90         strcpy(api->path, path);
91
92         /* api name is at the end of the path */
93         api->api = strrchr(api->path, '/');
94         if (api->api == NULL) {
95                 errno = EINVAL;
96                 goto error2;
97         }
98         api->api++;
99         if (!afb_apis_is_valid_api_name(api->api)) {
100                 errno = EINVAL;
101                 goto error2;
102         }
103
104         /* the name/interface is copied after the path */
105         api->name = &api->path[pathlen + 1];
106         strcpy(api->name, &path[1]);
107         ptr = strchr(api->name, '/');
108         while(ptr != NULL) {
109                 *ptr = '.';
110                 ptr = strchr(ptr, '/');
111         }
112
113         /* choose the bus */
114         sdbus = (system ? afb_common_get_system_bus : afb_common_get_user_bus)();
115         if (sdbus == NULL)
116                 goto error2;
117
118         api->sdbus = sdbus;
119         return api;
120
121 error2:
122         free(api);
123 error:
124         return NULL;
125 }
126
127 /*
128  * create a structure api_dbus connected on either the system
129  * bus if 'system' is not null or on the user bus. The connection
130  * is established for either emiting/receiving on 'path'.
131  * If 'path' is not absolute, it is prefixed with DEFAULT_PATH_PREFIX.
132  */
133 static struct api_dbus *make_api_dbus_2(int system, const char *path)
134 {
135         size_t len;
136         char *ptr;
137
138         /* check the length of the path */
139         len = strlen(path);
140         if (len == 0) {
141                 errno = EINVAL;
142                 return NULL;
143         }
144
145         /* if the path is absolute, creation now */
146         if (path[0] == '/')
147                 return make_api_dbus_3(system, path, len);
148
149         /* compute the path prefixed with DEFAULT_PATH_PREFIX */
150         assert(strlen(DEFAULT_PATH_PREFIX) > 0);
151         assert(DEFAULT_PATH_PREFIX[strlen(DEFAULT_PATH_PREFIX) - 1] == '/');
152         len += strlen(DEFAULT_PATH_PREFIX);
153         ptr = alloca(len + 1);
154         strcpy(stpcpy(ptr, DEFAULT_PATH_PREFIX), path);
155
156         /* creation for prefixed path */
157         return make_api_dbus_3(system, ptr, len);
158 }
159
160 /*
161  * create a structure api_dbus connected either emiting/receiving
162  * on 'path'.
163  * The path can be prefixed with "system:" or "user:" to select
164  * either the user or the system D-Bus. If none is set then user's
165  * bus is selected.
166  * If remaining 'path' is not absolute, it is prefixed with
167  * DEFAULT_PATH_PREFIX.
168  */
169 static struct api_dbus *make_api_dbus(const char *path)
170 {
171         const char *ptr;
172         size_t preflen;
173
174         /* retrieves the prefix "scheme-like" part */
175         ptr = strchr(path, ':');
176         if (ptr == NULL)
177                 return make_api_dbus_2(0, path);
178
179         /* check the prefix part */
180         preflen = (size_t)(ptr - path);
181         if (strncmp(path, "system", preflen) == 0)
182                 return make_api_dbus_2(1, ptr + 1);
183
184         if (strncmp(path, "user", preflen) == 0)
185                 return make_api_dbus_2(0, ptr + 1);
186
187         /* TODO: connect to a foreign D-Bus? */
188         errno = EINVAL;
189         return NULL;
190 }
191
192 static void destroy_api_dbus(struct api_dbus *api)
193 {
194         free(api);
195 }
196
197 /******************* client part **********************************/
198
199 /*
200  * structure for recording query data
201  */
202 struct dbus_memo {
203         struct afb_req req;             /* the request handle */
204         struct afb_context *context;    /* the context of the query */
205 };
206
207 /* allocates and init the memorizing data */
208 static struct dbus_memo *api_dbus_client_make_memo(struct afb_req req, struct afb_context *context)
209 {
210         struct dbus_memo *memo;
211
212         memo = malloc(sizeof *memo);
213         if (memo != NULL) {
214                 afb_req_addref(req);
215                 memo->req = req;
216                 memo->context = context;
217         }
218         return memo;
219 }
220
221 /* free and release the memorizing data */
222 static void api_dbus_client_free_memo(struct dbus_memo *memo)
223 {
224         afb_req_unref(memo->req);
225         free(memo);
226 }
227
228 /* callback when received answer */
229 static int api_dbus_client_on_reply(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
230 {
231         int rc;
232         struct dbus_memo *memo;
233         const char *first, *second;
234         uint8_t type;
235         uint32_t flags;
236
237         /* retrieve the recorded data */
238         memo = userdata;
239
240         /* get the answer */
241         rc = sd_bus_message_read(message, "yssu", &type, &first, &second, &flags);
242         if (rc < 0) {
243                 /* failing to have the answer */
244                 afb_req_fail(memo->req, "error", "dbus error");
245         } else {
246                 /* report the answer */
247                 memo->context->flags = (unsigned)flags;
248                 switch(type) {
249                 case RETOK:
250                         afb_req_success(memo->req, json_tokener_parse(first), second);
251                         break;
252                 case RETERR:
253                         afb_req_fail(memo->req, first, second);
254                         break;
255                 case RETRAW:
256                         afb_req_send(memo->req, first, strlen(first));
257                         break;
258                 default:
259                         afb_req_fail(memo->req, "error", "dbus link broken");
260                         break;
261                 }
262         }
263         api_dbus_client_free_memo(memo);
264         return 1;
265 }
266
267 /* on call, propagate it to the dbus service */
268 static void api_dbus_client_call(struct api_dbus *api, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
269 {
270         size_t size;
271         int rc;
272         char *method = strndupa(verb, lenverb);
273         struct dbus_memo *memo;
274
275         /* create the recording data */
276         memo = api_dbus_client_make_memo(req, context);
277         if (memo == NULL) {
278                 afb_req_fail(req, "error", "out of memory");
279                 return;
280         }
281
282         /* makes the call */
283         rc = sd_bus_call_method_async(api->sdbus, NULL,
284                 api->name, api->path, api->name, method,
285                 api_dbus_client_on_reply, memo,
286                 "ssu",
287                         afb_req_raw(req, &size),
288                         ctxClientGetUuid(context->session),
289                         (uint32_t)context->flags);
290
291         /* if there was an error report it directly */
292         if (rc < 0) {
293                 errno = -rc;
294                 afb_req_fail(req, "error", "dbus error");
295                 api_dbus_client_free_memo(memo);
296         }
297 }
298
299 static int api_dbus_service_start(struct api_dbus *api, int share_session, int onneed)
300 {
301         /* not an error when onneed */
302         if (onneed != 0)
303                 return 0;
304
305         /* already started: it is an error */
306         ERROR("The Dbus binding %s is not a startable service", api->name);
307         return -1;
308 }
309
310 /* receives events */
311 static int api_dbus_client_on_event(sd_bus_message *m, void *userdata, sd_bus_error *ret_error)
312 {
313         struct json_object *object;
314         const char *event, *data;
315         int rc = sd_bus_message_read(m, "ss", &event, &data);
316         if (rc < 0)
317                 ERROR("unreadable event");
318         else {
319                 object = json_tokener_parse(data);
320                 afb_evt_broadcast(event, object);
321                 json_object_put(object);
322         }
323         return 1;
324 }
325
326 /* adds a afb-dbus-service client api */
327 int afb_api_dbus_add_client(const char *path)
328 {
329         int rc;
330         struct api_dbus *api;
331         struct afb_api afb_api;
332         char *match;
333
334         /* create the dbus client api */
335         api = make_api_dbus(path);
336         if (api == NULL)
337                 goto error;
338
339         /* connect to events */
340         rc = asprintf(&match, "type='signal',path='%s',interface='%s',member='event'", api->path, api->name);
341         if (rc < 0) {
342                 errno = ENOMEM;
343                 ERROR("out of memory");
344                 goto error;
345         }
346         rc = sd_bus_add_match(api->sdbus, &api->slot, match, api_dbus_client_on_event, api);
347         free(match);
348         if (rc < 0) {
349                 errno = -rc;
350                 ERROR("can't add dbus object %s for %s", api->path, api->name);
351                 goto error;
352         }
353
354         /* record it as an API */
355         afb_api.closure = api;
356         afb_api.call = (void*)api_dbus_client_call;
357         afb_api.service_start = (void*)api_dbus_service_start;
358         if (afb_apis_add(api->api, afb_api) < 0)
359                 goto error2;
360
361         return 0;
362
363 error2:
364         destroy_api_dbus(api);
365 error:
366         return -1;
367 }
368
369 /******************* dbus request part for server *****************/
370
371 /*
372  * structure for a dbus request
373  */
374 struct dbus_req {
375         struct afb_context context;     /* the context, should be THE FIRST */
376         sd_bus_message *message;        /* the incoming request message */
377         const char *request;            /* the readen request as string */
378         struct json_object *json;       /* the readen request as object */
379         int refcount;                   /* reference count of the request */
380 };
381
382 /* increment the reference count of the request */
383 static void dbus_req_addref(struct dbus_req *dreq)
384 {
385         dreq->refcount++;
386 }
387
388 /* decrement the reference count of the request and free/release it on falling to null */
389 static void dbus_req_unref(struct dbus_req *dreq)
390 {
391         if (dreq == NULL || --dreq->refcount)
392                 return;
393
394         afb_context_disconnect(&dreq->context);
395         json_object_put(dreq->json);
396         sd_bus_message_unref(dreq->message);
397         free(dreq);
398 }
399
400 /* get the object of the request */
401 static struct json_object *dbus_req_json(struct dbus_req *dreq)
402 {
403         if (dreq->json == NULL) {
404                 dreq->json = json_tokener_parse(dreq->request);
405                 if (dreq->json == NULL) {
406                         /* lazy error detection of json request. Is it to improve? */
407                         dreq->json = json_object_new_string(dreq->request);
408                 }
409         }
410         return dreq->json;
411 }
412
413 /* get the argument of the request of 'name' */
414 static struct afb_arg dbus_req_get(struct dbus_req *dreq, const char *name)
415 {
416         return afb_msg_json_get_arg(dbus_req_json(dreq), name);
417 }
418
419 static void dbus_req_reply(struct dbus_req *dreq, uint8_t type, const char *first, const char *second)
420 {
421         int rc;
422         rc = sd_bus_reply_method_return(dreq->message,
423                         "yssu", type, first, second, (uint32_t)dreq->context.flags);
424         if (rc < 0)
425                 ERROR("sending the reply failed");
426 }
427
428 static void dbus_req_success(struct dbus_req *dreq, struct json_object *obj, const char *info)
429 {
430         dbus_req_reply(dreq, RETOK, json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN), info);
431 }
432
433 static void dbus_req_fail(struct dbus_req *dreq, const char *status, const char *info)
434 {
435         dbus_req_reply(dreq, RETERR, status, info);
436 }
437
438 static const char *dbus_req_raw(struct dbus_req *dreq, size_t *size)
439 {
440         if (size != NULL)
441                 *size = strlen(dreq->request);
442         return dreq->request;
443 }
444
445 static void dbus_req_send(struct dbus_req *dreq, const char *buffer, size_t size)
446 {
447         /* TODO: how to put sized buffer as strings? things aren't clear here!!! */
448         dbus_req_reply(dreq, RETRAW, buffer, "");
449 }
450
451 static int dbus_req_subscribe(struct dbus_req *dreq, struct afb_event event)
452 {
453         return -1;
454 }
455
456 static int dbus_req_unsubscribe(struct dbus_req *dreq, struct afb_event event)
457 {
458         return -1;
459 }
460
461 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);
462
463 const struct afb_req_itf afb_api_dbus_req_itf = {
464         .json = (void*)dbus_req_json,
465         .get = (void*)dbus_req_get,
466         .success = (void*)dbus_req_success,
467         .fail = (void*)dbus_req_fail,
468         .raw = (void*)dbus_req_raw,
469         .send = (void*)dbus_req_send,
470         .context_get = (void*)afb_context_get,
471         .context_set = (void*)afb_context_set,
472         .addref = (void*)dbus_req_addref,
473         .unref = (void*)dbus_req_unref,
474         .session_close = (void*)afb_context_close,
475         .session_set_LOA = (void*)afb_context_change_loa,
476         .subscribe = (void*)dbus_req_subscribe,
477         .unsubscribe = (void*)dbus_req_unsubscribe,
478         .subcall = (void*)dbus_req_subcall
479 };
480
481 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)
482 {
483         afb_subcall(&dreq->context, api, verb, args, callback, closure, (struct afb_req){ .itf = &afb_api_dbus_req_itf, .closure = dreq });
484 }
485
486 /******************* server part **********************************/
487
488 /* called when the object for the service is called */
489 static int api_dbus_server_on_object_called(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
490 {
491         int rc;
492         const char *method;
493         const char *uuid;
494         struct dbus_req *dreq;
495         struct api_dbus *api = userdata;
496         struct afb_req areq;
497         uint32_t flags;
498
499         /* check the interface */
500         if (strcmp(sd_bus_message_get_interface(message), api->name) != 0)
501                 return 0;
502
503         /* get the method */
504         method = sd_bus_message_get_member(message);
505
506         /* create the request */
507         dreq = calloc(1 , sizeof *dreq);
508         if (dreq == NULL) {
509                 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_NO_MEMORY, "out of memory");
510                 return 1;
511         }
512
513         /* get the data */
514         rc = sd_bus_message_read(message, "ssu", &dreq->request, &uuid, &flags);
515         if (rc < 0) {
516                 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_INVALID_SIGNATURE, "invalid signature");
517                 free(dreq);
518                 return 1;
519         }
520
521         /* connect to the context */
522         if (afb_context_connect(&dreq->context, uuid, NULL) < 0) {
523                 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_NO_MEMORY, "out of memory");
524                 free(dreq);
525                 return 1;
526         }
527
528         /* fulfill the request and emit it */
529         dreq->context.flags = flags;
530         dreq->message = sd_bus_message_ref(message);
531         dreq->json = NULL;
532         dreq->refcount = 1;
533         areq.itf = &afb_api_dbus_req_itf;
534         areq.closure = dreq;
535         afb_apis_call_(areq, &dreq->context, api->api, method);
536         dbus_req_unref(dreq);
537         return 1;
538 }
539
540 static void afb_api_dbus_server_send_event(struct api_dbus *api, const char *event, int eventid, struct json_object *object)
541 {
542         int rc;
543
544         rc = sd_bus_emit_signal(api->sdbus, api->path, api->name,
545                         "event", "ss", event, json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN));
546         if (rc < 0)
547                 ERROR("error while emiting event %s", event);
548         json_object_put(object);
549 }
550
551 /* the interface for events */
552 static const struct afb_evt_itf evt_itf = {
553         .broadcast = (void*)afb_api_dbus_server_send_event,
554         .push = (void*)afb_api_dbus_server_send_event
555 };
556
557 /* create the service */
558 int afb_api_dbus_add_server(const char *path)
559 {
560         int rc;
561         struct api_dbus *api;
562
563         /* get the dbus api object connected */
564         api = make_api_dbus(path);
565         if (api == NULL)
566                 goto error;
567
568         /* request the service object name */
569         rc = sd_bus_request_name(api->sdbus, api->name, 0);
570         if (rc < 0) {
571                 errno = -rc;
572                 ERROR("can't register name %s", api->name);
573                 goto error2;
574         }
575
576         /* connect the service to the dbus object */
577         rc = sd_bus_add_object(api->sdbus, &api->slot, api->path, api_dbus_server_on_object_called, api);
578         if (rc < 0) {
579                 errno = -rc;
580                 ERROR("can't add dbus object %s for %s", api->path, api->name);
581                 goto error3;
582         }
583         INFO("afb service over dbus installed, name %s, path %s", api->name, api->path);
584
585         api->listener = afb_evt_listener_create(&evt_itf, api);
586
587         return 0;
588 error3:
589         sd_bus_release_name(api->sdbus, api->name);
590 error2:
591         destroy_api_dbus(api);
592 error:
593         return -1;
594 }
595
596