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