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