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