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