common code reuse
[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 /* receives events */
300 static int api_dbus_client_on_event(sd_bus_message *m, void *userdata, sd_bus_error *ret_error)
301 {
302         struct json_object *object;
303         const char *event, *data;
304         int rc = sd_bus_message_read(m, "ss", &event, &data);
305         if (rc < 0)
306                 ERROR("unreadable event");
307         else {
308                 object = json_tokener_parse(data);
309                 afb_evt_broadcast(event, object);
310                 json_object_put(object);
311         }
312         return 1;
313 }
314
315 /* adds a afb-dbus-service client api */
316 int afb_api_dbus_add_client(const char *path)
317 {
318         int rc;
319         struct api_dbus *api;
320         struct afb_api afb_api;
321         char *match;
322
323         /* create the dbus client api */
324         api = make_api_dbus(path);
325         if (api == NULL)
326                 goto error;
327
328         /* connect to events */
329         rc = asprintf(&match, "type='signal',path='%s',interface='%s',member='event'", api->path, api->name);
330         if (rc < 0) {
331                 errno = ENOMEM;
332                 ERROR("out of memory");
333                 goto error;
334         }
335         rc = sd_bus_add_match(api->sdbus, &api->slot, match, api_dbus_client_on_event, api);
336         free(match);
337         if (rc < 0) {
338                 errno = -rc;
339                 ERROR("can't add dbus object %s for %s", api->path, api->name);
340                 goto error;
341         }
342
343         /* record it as an API */
344         afb_api.closure = api;
345         afb_api.call = (void*)api_dbus_client_call;
346         if (afb_apis_add(api->api, afb_api) < 0)
347                 goto error2;
348
349         return 0;
350
351 error2:
352         destroy_api_dbus(api);
353 error:
354         return -1;
355 }
356
357 /******************* dbus request part for server *****************/
358
359 /*
360  * structure for a dbus request
361  */
362 struct dbus_req {
363         struct afb_context context;     /* the context, should be THE FIRST */
364         sd_bus_message *message;        /* the incoming request message */
365         const char *request;            /* the readen request as string */
366         struct json_object *json;       /* the readen request as object */
367         int refcount;                   /* reference count of the request */
368 };
369
370 /* increment the reference count of the request */
371 static void dbus_req_addref(struct dbus_req *dreq)
372 {
373         dreq->refcount++;
374 }
375
376 /* decrement the reference count of the request and free/release it on falling to null */
377 static void dbus_req_unref(struct dbus_req *dreq)
378 {
379         if (dreq == NULL || --dreq->refcount)
380                 return;
381
382         afb_context_disconnect(&dreq->context);
383         json_object_put(dreq->json);
384         sd_bus_message_unref(dreq->message);
385         free(dreq);
386 }
387
388 /* get the object of the request */
389 static struct json_object *dbus_req_json(struct dbus_req *dreq)
390 {
391         if (dreq->json == NULL) {
392                 dreq->json = json_tokener_parse(dreq->request);
393                 if (dreq->json == NULL) {
394                         /* lazy error detection of json request. Is it to improve? */
395                         dreq->json = json_object_new_string(dreq->request);
396                 }
397         }
398         return dreq->json;
399 }
400
401 /* get the argument of the request of 'name' */
402 static struct afb_arg dbus_req_get(struct dbus_req *dreq, const char *name)
403 {
404         return afb_msg_json_get_arg(dbus_req_json(dreq), name);
405 }
406
407 static void dbus_req_reply(struct dbus_req *dreq, uint8_t type, const char *first, const char *second)
408 {
409         int rc;
410         rc = sd_bus_reply_method_return(dreq->message,
411                         "yssu", type, first, second, (uint32_t)dreq->context.flags);
412         if (rc < 0)
413                 ERROR("sending the reply failed");
414 }
415
416 static void dbus_req_success(struct dbus_req *dreq, struct json_object *obj, const char *info)
417 {
418         dbus_req_reply(dreq, RETOK, json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN), info);
419 }
420
421 static void dbus_req_fail(struct dbus_req *dreq, const char *status, const char *info)
422 {
423         dbus_req_reply(dreq, RETERR, status, info);
424 }
425
426 static const char *dbus_req_raw(struct dbus_req *dreq, size_t *size)
427 {
428         if (size != NULL)
429                 *size = strlen(dreq->request);
430         return dreq->request;
431 }
432
433 static void dbus_req_send(struct dbus_req *dreq, const char *buffer, size_t size)
434 {
435         /* TODO: how to put sized buffer as strings? things aren't clear here!!! */
436         dbus_req_reply(dreq, RETRAW, buffer, "");
437 }
438
439 static int dbus_req_subscribe(struct dbus_req *dreq, struct afb_event event)
440 {
441         return -1;
442 }
443
444 static int dbus_req_unsubscribe(struct dbus_req *dreq, struct afb_event event)
445 {
446         return -1;
447 }
448
449 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);
450
451 const struct afb_req_itf afb_api_dbus_req_itf = {
452         .json = (void*)dbus_req_json,
453         .get = (void*)dbus_req_get,
454         .success = (void*)dbus_req_success,
455         .fail = (void*)dbus_req_fail,
456         .raw = (void*)dbus_req_raw,
457         .send = (void*)dbus_req_send,
458         .context_get = (void*)afb_context_get,
459         .context_set = (void*)afb_context_set,
460         .addref = (void*)dbus_req_addref,
461         .unref = (void*)dbus_req_unref,
462         .session_close = (void*)afb_context_close,
463         .session_set_LOA = (void*)afb_context_change_loa,
464         .subscribe = (void*)dbus_req_subscribe,
465         .unsubscribe = (void*)dbus_req_unsubscribe,
466         .subcall = (void*)dbus_req_subcall
467 };
468
469 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)
470 {
471         afb_subcall(&dreq->context, api, verb, args, callback, closure, (struct afb_req){ .itf = &afb_api_dbus_req_itf, .closure = dreq });
472 }
473
474 /******************* server part **********************************/
475
476 /* called when the object for the service is called */
477 static int api_dbus_server_on_object_called(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
478 {
479         int rc;
480         const char *method;
481         const char *uuid;
482         struct dbus_req *dreq;
483         struct api_dbus *api = userdata;
484         struct afb_req areq;
485         uint32_t flags;
486
487         /* check the interface */
488         if (strcmp(sd_bus_message_get_interface(message), api->name) != 0)
489                 return 0;
490
491         /* get the method */
492         method = sd_bus_message_get_member(message);
493
494         /* create the request */
495         dreq = calloc(1 , sizeof *dreq);
496         if (dreq == NULL) {
497                 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_NO_MEMORY, "out of memory");
498                 return 1;
499         }
500
501         /* get the data */
502         rc = sd_bus_message_read(message, "ssu", &dreq->request, &uuid, &flags);
503         if (rc < 0) {
504                 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_INVALID_SIGNATURE, "invalid signature");
505                 free(dreq);
506                 return 1;
507         }
508
509         /* connect to the context */
510         if (afb_context_connect(&dreq->context, uuid, NULL) < 0) {
511                 sd_bus_reply_method_errorf(message, SD_BUS_ERROR_NO_MEMORY, "out of memory");
512                 free(dreq);
513                 return 1;
514         }
515
516         /* fulfill the request and emit it */
517         dreq->context.flags = flags;
518         dreq->message = sd_bus_message_ref(message);
519         dreq->json = NULL;
520         dreq->refcount = 1;
521         areq.itf = &afb_api_dbus_req_itf;
522         areq.closure = dreq;
523         afb_apis_call_(areq, &dreq->context, api->api, method);
524         dbus_req_unref(dreq);
525         return 1;
526 }
527
528 static void afb_api_dbus_server_send_event(struct api_dbus *api, const char *event, struct json_object *object)
529 {
530         int rc;
531
532         rc = sd_bus_emit_signal(api->sdbus, api->path, api->name,
533                         "event", "ss", event, json_object_to_json_string_ext(object, JSON_C_TO_STRING_PLAIN));
534         if (rc < 0)
535                 ERROR("error while emiting event %s", event);
536         json_object_put(object);
537 }
538
539 /* create the service */
540 int afb_api_dbus_add_server(const char *path)
541 {
542         int rc;
543         struct api_dbus *api;
544
545         /* get the dbus api object connected */
546         api = make_api_dbus(path);
547         if (api == NULL)
548                 goto error;
549
550         /* request the service object name */
551         rc = sd_bus_request_name(api->sdbus, api->name, 0);
552         if (rc < 0) {
553                 errno = -rc;
554                 ERROR("can't register name %s", api->name);
555                 goto error2;
556         }
557
558         /* connect the service to the dbus object */
559         rc = sd_bus_add_object(api->sdbus, &api->slot, api->path, api_dbus_server_on_object_called, api);
560         if (rc < 0) {
561                 errno = -rc;
562                 ERROR("can't add dbus object %s for %s", api->path, api->name);
563                 goto error3;
564         }
565         INFO("afb service over dbus installed, name %s, path %s", api->name, api->path);
566
567         api->listener = afb_evt_listener_create((void*)afb_api_dbus_server_send_event, api);
568
569         return 0;
570 error3:
571         sd_bus_release_name(api->sdbus, api->name);
572 error2:
573         destroy_api_dbus(api);
574 error:
575         return -1;
576 }
577
578