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