bindings: adds ability to use data of applications
[src/app-framework-binder.git] / src / afb-api-so.c
1 /*
2  * Copyright (C) 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_BINDING_VERBOSE_MACRO
20
21 #include <stdio.h>
22 #include <assert.h>
23 #include <string.h>
24 #include <dirent.h>
25 #include <dlfcn.h>
26 #include <unistd.h>
27 #include <limits.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30
31 #include <afb/afb-binding.h>
32 #include <afb/afb-req-itf.h>
33 #include <afb/afb-event-itf.h>
34
35 #include "session.h"
36 #include "afb-common.h"
37 #include "afb-context.h"
38 #include "afb-apis.h"
39 #include "afb-api-so.h"
40 #include "afb-sig-handler.h"
41 #include "afb-evt.h"
42 #include "afb-svc.h"
43 #include "verbose.h"
44
45 /*
46  * Description of a binding
47  */
48 struct api_so_desc {
49         struct afb_binding *binding;    /* descriptor */
50         size_t apilength;               /* length of the API name */
51         void *handle;                   /* context of dlopen */
52         struct afb_svc *service;        /* handler for service started */
53         struct afb_binding_interface interface; /* interface for the binding */
54 };
55
56 struct monitoring {
57         struct afb_req req;
58         void (*action)(struct afb_req);
59 };
60
61 static const char binding_register_function_v1[] = "afbBindingV1Register";
62 static const char binding_service_init_function_v1[] = "afbBindingV1ServiceInit";
63 static const char binding_service_event_function_v1[] = "afbBindingV1ServiceEvent";
64
65 static int api_timeout = 15;
66
67 static struct afb_event afb_api_so_event_make_cb(void *closure, const char *name);
68 static int afb_api_so_event_broadcast_cb(void *closure, const char *name, struct json_object *object);
69 static void afb_api_so_vverbose_cb(void *closure, int level, const char *file, int line, const char *fmt, va_list args);
70 static int afb_api_so_rootdir_get_fd(void *closure);
71 static int afb_api_so_rootdir_open_locale(void *closure, const char *filename, int flags, const char *locale);
72
73 static const struct afb_daemon_itf daemon_itf = {
74         .event_broadcast = afb_api_so_event_broadcast_cb,
75         .get_event_loop = afb_common_get_event_loop,
76         .get_user_bus = afb_common_get_user_bus,
77         .get_system_bus = afb_common_get_system_bus,
78         .vverbose = afb_api_so_vverbose_cb,
79         .event_make = afb_api_so_event_make_cb,
80         .rootdir_get_fd = afb_api_so_rootdir_get_fd,
81         .rootdir_open_locale = afb_api_so_rootdir_open_locale
82 };
83
84 static struct afb_event afb_api_so_event_make_cb(void *closure, const char *name)
85 {
86         size_t length;
87         char *event;
88         struct api_so_desc *desc = closure;
89
90         /* makes the event name */
91         assert(desc->binding != NULL);
92         length = strlen(name);
93         event = alloca(length + 2 + desc->apilength);
94         memcpy(event, desc->binding->v1.prefix, desc->apilength);
95         event[desc->apilength] = '/';
96         memcpy(event + desc->apilength + 1, name, length + 1);
97
98         /* crate the event */
99         return afb_evt_create_event(event);
100 }
101
102 static int afb_api_so_event_broadcast_cb(void *closure, const char *name, struct json_object *object)
103 {
104         size_t length;
105         char *event;
106         struct api_so_desc *desc = closure;
107
108         /* makes the event name */
109         assert(desc->binding != NULL);
110         length = strlen(name);
111         event = alloca(length + 2 + desc->apilength);
112         memcpy(event, desc->binding->v1.prefix, desc->apilength);
113         event[desc->apilength] = '/';
114         memcpy(event + desc->apilength + 1, name, length + 1);
115
116         return afb_evt_broadcast(event, object);
117 }
118
119 static void afb_api_so_vverbose_cb(void *closure, int level, const char *file, int line, const char *fmt, va_list args)
120 {
121         char *p;
122         struct api_so_desc *desc = closure;
123
124         if (vasprintf(&p, fmt, args) < 0)
125                 vverbose(level, file, line, fmt, args);
126         else {
127                 verbose(level, file, line, "%s {binding %s}", p, desc->binding->v1.prefix);
128                 free(p);
129         }
130 }
131
132 static int afb_api_so_rootdir_get_fd(void *closure)
133 {
134         return afb_common_rootdir_get_fd();
135 }
136
137 static int afb_api_so_rootdir_open_locale(void *closure, const char *filename, int flags, const char *locale)
138 {
139         return afb_common_rootdir_open_locale(filename, flags, locale);
140 }
141
142 static void monitored_call(int signum, void *arg)
143 {
144         struct monitoring *data = arg;
145         if (signum != 0)
146                 afb_req_fail_f(data->req, "aborted", "signal %s(%d) caught", strsignal(signum), signum);
147         else
148                 data->action(data->req);
149 }
150
151 static void call_check(struct afb_req req, struct afb_context *context, const struct afb_verb_desc_v1 *verb)
152 {
153         struct monitoring data;
154
155         int stag = (int)verb->session;
156
157         if ((stag & (AFB_SESSION_CREATE|AFB_SESSION_CLOSE|AFB_SESSION_RENEW|AFB_SESSION_CHECK|AFB_SESSION_LOA_EQ)) != 0) {
158                 if (!afb_context_check(context)) {
159                         afb_context_close(context);
160                         afb_req_fail(req, "failed", "invalid token's identity");
161                         return;
162                 }
163         }
164
165         if ((stag & AFB_SESSION_CREATE) != 0) {
166                 if (afb_context_check_loa(context, 1)) {
167                         afb_req_fail(req, "failed", "invalid creation state");
168                         return;
169                 }
170                 afb_context_change_loa(context, 1);
171                 afb_context_refresh(context);
172         }
173
174         if ((stag & (AFB_SESSION_CREATE | AFB_SESSION_RENEW)) != 0)
175                 afb_context_refresh(context);
176
177         if ((stag & AFB_SESSION_CLOSE) != 0) {
178                 afb_context_change_loa(context, 0);
179                 afb_context_close(context);
180         }
181
182         if ((stag & AFB_SESSION_LOA_GE) != 0) {
183                 int loa = (stag >> AFB_SESSION_LOA_SHIFT) & AFB_SESSION_LOA_MASK;
184                 if (!afb_context_check_loa(context, loa)) {
185                         afb_req_fail(req, "failed", "invalid LOA");
186                         return;
187                 }
188         }
189
190         if ((stag & AFB_SESSION_LOA_LE) != 0) {
191                 int loa = (stag >> AFB_SESSION_LOA_SHIFT) & AFB_SESSION_LOA_MASK;
192                 if (afb_context_check_loa(context, loa + 1)) {
193                         afb_req_fail(req, "failed", "invalid LOA");
194                         return;
195                 }
196         }
197
198         data.req = req;
199         data.action = verb->callback;
200         afb_sig_monitor(monitored_call, &data, api_timeout);
201 }
202
203 static void call_cb(void *closure, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
204 {
205         const struct afb_verb_desc_v1 *v;
206         struct api_so_desc *desc = closure;
207
208         v = desc->binding->v1.verbs;
209         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
210                 v++;
211         if (v->name)
212                 call_check(req, context, v);
213         else
214                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->binding->v1.prefix);
215 }
216
217 static int service_start_cb(void *closure, int share_session, int onneed)
218 {
219         int (*init)(struct afb_service service);
220         void (*onevent)(const char *event, struct json_object *object);
221
222         struct api_so_desc *desc = closure;
223
224         /* check state */
225         if (desc->service != NULL) {
226                 /* not an error when onneed */
227                 if (onneed != 0)
228                         return 0;
229
230                 /* already started: it is an error */
231                 ERROR("Service %s already started", desc->binding->v1.prefix);
232                 return -1;
233         }
234
235         /* get the initialisation */
236         init = dlsym(desc->handle, binding_service_init_function_v1);
237         if (init == NULL) {
238                 /* not an error when onneed */
239                 if (onneed != 0)
240                         return 0;
241
242                 /* no initialisation method */
243                 ERROR("Binding %s is not a service", desc->binding->v1.prefix);
244                 return -1;
245         }
246
247         /* get the event handler if any */
248         onevent = dlsym(desc->handle, binding_service_event_function_v1);
249         desc->service = afb_svc_create(share_session, init, onevent);
250         if (desc->service == NULL) {
251                 /* starting error */
252                 ERROR("Starting service %s failed", desc->binding->v1.prefix);
253                 return -1;
254         }
255
256         return 0;
257 }
258
259 void afb_api_so_set_timeout(int to)
260 {
261         api_timeout = to;
262 }
263
264 int afb_api_so_add_binding(const char *path)
265 {
266         int rc;
267         void *handle;
268         struct api_so_desc *desc;
269         struct afb_binding *(*register_function) (const struct afb_binding_interface *interface);
270         struct afb_verb_desc_v1 fake_verb;
271         struct afb_binding fake_binding;
272
273         // This is a loadable library let's check if it's a binding
274         rc = 0;
275         handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
276         if (handle == NULL) {
277                 ERROR("binding [%s] not loadable", path);
278                 goto error;
279         }
280
281         /* retrieves the register function */
282         register_function = dlsym(handle, binding_register_function_v1);
283         if (!register_function) {
284                 ERROR("binding [%s] is not an AFB binding", path);
285                 goto error2;
286         }
287         INFO("binding [%s] is a valid AFB binding", path);
288         rc = -1;
289
290         /* allocates the description */
291         desc = calloc(1, sizeof *desc);
292         if (desc == NULL) {
293                 ERROR("out of memory");
294                 goto error2;
295         }
296         desc->handle = handle;
297
298         /* init the interface */
299         desc->interface.verbosity = verbosity;
300         desc->interface.mode = AFB_MODE_LOCAL;
301         desc->interface.daemon.itf = &daemon_itf;
302         desc->interface.daemon.closure = desc;
303
304         /* for log purpose, a fake binding is needed here */
305         desc->binding = &fake_binding;
306         fake_binding.type = AFB_BINDING_VERSION_1;
307         fake_binding.v1.info = path;
308         fake_binding.v1.prefix = path;
309         fake_binding.v1.verbs = &fake_verb;
310         fake_verb.name = NULL;
311
312         /* init the binding */
313         NOTICE("binding [%s] calling registering function %s", path, binding_register_function_v1);
314         desc->binding = register_function(&desc->interface);
315         if (desc->binding == NULL) {
316                 ERROR("binding [%s] register function failed. continuing...", path);
317                 goto error3;
318         }
319
320         /* check the returned structure */
321         if (desc->binding->type != AFB_BINDING_VERSION_1) {
322                 ERROR("binding [%s] invalid type %d...", path, desc->binding->type);
323                 goto error3;
324         }
325         if (desc->binding->v1.prefix == NULL || *desc->binding->v1.prefix == 0) {
326                 ERROR("binding [%s] bad prefix...", path);
327                 goto error3;
328         }
329         if (!afb_apis_is_valid_api_name(desc->binding->v1.prefix)) {
330                 ERROR("binding [%s] invalid prefix...", path);
331                 goto error3;
332         }
333         if (desc->binding->v1.info == NULL || *desc->binding->v1.info == 0) {
334                 ERROR("binding [%s] bad description...", path);
335                 goto error3;
336         }
337         if (desc->binding->v1.verbs == NULL) {
338                 ERROR("binding [%s] no APIs...", path);
339                 goto error3;
340         }
341
342         /* records the binding */
343         desc->apilength = strlen(desc->binding->v1.prefix);
344         if (afb_apis_add(desc->binding->v1.prefix, (struct afb_api){
345                         .closure = desc,
346                         .call = call_cb,
347                         .service_start = service_start_cb }) < 0) {
348                 ERROR("binding [%s] can't be registered...", path);
349                 goto error3;
350         }
351         NOTICE("binding %s loaded with API prefix %s", path, desc->binding->v1.prefix);
352         return 0;
353
354 error3:
355         free(desc);
356 error2:
357         dlclose(handle);
358 error:
359         return rc;
360 }
361
362 static int adddirs(char path[PATH_MAX], size_t end)
363 {
364         DIR *dir;
365         struct dirent ent, *result;
366         size_t len;
367
368         /* open the DIR now */
369         dir = opendir(path);
370         if (dir == NULL) {
371                 ERROR("can't scan binding directory %s, %m", path);
372                 return -1;
373         }
374         INFO("Scanning dir=[%s] for bindings", path);
375
376         /* scan each entry */
377         if (end)
378                 path[end++] = '/';
379         for (;;) {
380                 readdir_r(dir, &ent, &result);
381                 if (result == NULL)
382                         break;
383
384                 len = strlen(ent.d_name);
385                 if (len + end >= PATH_MAX) {
386                         ERROR("path too long while scanning bindings for %s", ent.d_name);
387                         continue;
388                 }
389                 memcpy(&path[end], ent.d_name, len+1);
390                 if (ent.d_type == DT_DIR) {
391                         /* case of directories */
392                         if (ent.d_name[0] == '.') {
393                                 if (len == 1)
394                                         continue;
395                                 if (ent.d_name[1] == '.' && len == 2)
396                                         continue;
397                         }
398                         adddirs(path, end+len);;
399                 } else if (ent.d_type == DT_REG) {
400                         /* case of files */
401                         if (!strstr(ent.d_name, ".so"))
402                                 continue;
403                         if (afb_api_so_add_binding(path) < 0)
404                                 return -1;
405                 }
406         }
407         closedir(dir);
408         return 0;
409 }
410
411 int afb_api_so_add_directory(const char *path)
412 {
413         size_t length;
414         char buffer[PATH_MAX];
415
416         length = strlen(path);
417         if (length >= sizeof(buffer)) {
418                 ERROR("path too long %lu [%.99s...]", (unsigned long)length, path);
419                 return -1;
420         }
421
422         memcpy(buffer, path, length + 1);
423         return adddirs(buffer, length);
424 }
425
426 int afb_api_so_add_path(const char *path)
427 {
428         struct stat st;
429         int rc;
430
431         rc = stat(path, &st);
432         if (rc < 0)
433                 ERROR("Invalid binding path [%s]: %m", path);
434         else if (S_ISDIR(st.st_mode))
435                 rc = afb_api_so_add_directory(path);
436         else if (strstr(path, ".so"))
437                 rc = afb_api_so_add_binding(path);
438         else
439                 INFO("not a binding [%s], skipped", path);
440         return rc;
441 }
442
443 int afb_api_so_add_pathset(const char *pathset)
444 {
445         static char sep[] = ":";
446         char *ps, *p;
447
448         ps = strdupa(pathset);
449         for (;;) {
450                 p = strsep(&ps, sep);
451                 if (!p)
452                         return 0;
453                 if (afb_api_so_add_path(p) < 0)
454                         return -1;
455         }
456 }
457