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