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