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