afb-api-so: adds verbosity on dlopen error
[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 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                 if (0)
197                         /* not threaded */
198                         afb_sig_req_timeout(req, verb->callback, api_timeout);
199                 else
200                         /* threaded */
201                         afb_thread_call(req, verb->callback, api_timeout, desc);
202         }
203 }
204
205 static int service_start_cb(void *closure, int share_session, int onneed)
206 {
207         int (*init)(struct afb_service service);
208         void (*onevent)(const char *event, struct json_object *object);
209
210         struct api_so_desc *desc = closure;
211
212         /* check state */
213         if (desc->service != NULL) {
214                 /* not an error when onneed */
215                 if (onneed != 0)
216                         return 0;
217
218                 /* already started: it is an error */
219                 ERROR("Service %s already started", desc->binding->v1.prefix);
220                 return -1;
221         }
222
223         /* get the initialisation */
224         init = dlsym(desc->handle, binding_service_init_function_v1);
225         if (init == NULL) {
226                 /* not an error when onneed */
227                 if (onneed != 0)
228                         return 0;
229
230                 /* no initialisation method */
231                 ERROR("Binding %s is not a service", desc->binding->v1.prefix);
232                 return -1;
233         }
234
235         /* get the event handler if any */
236         onevent = dlsym(desc->handle, binding_service_event_function_v1);
237         desc->service = afb_svc_create(share_session, init, onevent);
238         if (desc->service == NULL) {
239                 /* starting error */
240                 ERROR("Starting service %s failed", desc->binding->v1.prefix);
241                 return -1;
242         }
243
244         return 0;
245 }
246
247 void afb_api_so_set_timeout(int to)
248 {
249         api_timeout = to;
250 }
251
252 int afb_api_so_add_binding(const char *path)
253 {
254         int rc;
255         void *handle;
256         struct api_so_desc *desc;
257         struct afb_binding *(*register_function) (const struct afb_binding_interface *interface);
258         struct afb_verb_desc_v1 fake_verb;
259         struct afb_binding fake_binding;
260
261         // This is a loadable library let's check if it's a binding
262         rc = 0;
263         handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
264         if (handle == NULL) {
265                 ERROR("binding [%s] not loadable: %s", path, dlerror());
266                 goto error;
267         }
268
269         /* retrieves the register function */
270         register_function = dlsym(handle, binding_register_function_v1);
271         if (!register_function) {
272                 ERROR("binding [%s] is not an AFB binding", path);
273                 goto error2;
274         }
275         INFO("binding [%s] is a valid AFB binding", path);
276         rc = -1;
277
278         /* allocates the description */
279         desc = calloc(1, sizeof *desc);
280         if (desc == NULL) {
281                 ERROR("out of memory");
282                 goto error2;
283         }
284         desc->handle = handle;
285
286         /* init the interface */
287         desc->interface.verbosity = verbosity;
288         desc->interface.mode = AFB_MODE_LOCAL;
289         desc->interface.daemon.itf = &daemon_itf;
290         desc->interface.daemon.closure = desc;
291
292         /* for log purpose, a fake binding is needed here */
293         desc->binding = &fake_binding;
294         fake_binding.type = AFB_BINDING_VERSION_1;
295         fake_binding.v1.info = path;
296         fake_binding.v1.prefix = path;
297         fake_binding.v1.verbs = &fake_verb;
298         fake_verb.name = NULL;
299
300         /* init the binding */
301         NOTICE("binding [%s] calling registering function %s", path, binding_register_function_v1);
302         desc->binding = register_function(&desc->interface);
303         if (desc->binding == NULL) {
304                 ERROR("binding [%s] register function failed. continuing...", path);
305                 goto error3;
306         }
307
308         /* check the returned structure */
309         if (desc->binding->type != AFB_BINDING_VERSION_1) {
310                 ERROR("binding [%s] invalid type %d...", path, desc->binding->type);
311                 goto error3;
312         }
313         if (desc->binding->v1.prefix == NULL || *desc->binding->v1.prefix == 0) {
314                 ERROR("binding [%s] bad prefix...", path);
315                 goto error3;
316         }
317         if (!afb_apis_is_valid_api_name(desc->binding->v1.prefix)) {
318                 ERROR("binding [%s] invalid prefix...", path);
319                 goto error3;
320         }
321         if (desc->binding->v1.info == NULL || *desc->binding->v1.info == 0) {
322                 ERROR("binding [%s] bad description...", path);
323                 goto error3;
324         }
325         if (desc->binding->v1.verbs == NULL) {
326                 ERROR("binding [%s] no APIs...", path);
327                 goto error3;
328         }
329
330         /* records the binding */
331         desc->apilength = strlen(desc->binding->v1.prefix);
332         if (afb_apis_add(desc->binding->v1.prefix, (struct afb_api){
333                         .closure = desc,
334                         .call = call_cb,
335                         .service_start = service_start_cb }) < 0) {
336                 ERROR("binding [%s] can't be registered...", path);
337                 goto error3;
338         }
339         NOTICE("binding %s loaded with API prefix %s", path, desc->binding->v1.prefix);
340         return 0;
341
342 error3:
343         free(desc);
344 error2:
345         dlclose(handle);
346 error:
347         return rc;
348 }
349
350 static int adddirs(char path[PATH_MAX], size_t end)
351 {
352         DIR *dir;
353         struct dirent ent, *result;
354         size_t len;
355
356         /* open the DIR now */
357         dir = opendir(path);
358         if (dir == NULL) {
359                 ERROR("can't scan binding directory %s, %m", path);
360                 return -1;
361         }
362         INFO("Scanning dir=[%s] for bindings", path);
363
364         /* scan each entry */
365         if (end)
366                 path[end++] = '/';
367         for (;;) {
368                 readdir_r(dir, &ent, &result);
369                 if (result == NULL)
370                         break;
371
372                 len = strlen(ent.d_name);
373                 if (len + end >= PATH_MAX) {
374                         ERROR("path too long while scanning bindings for %s", ent.d_name);
375                         continue;
376                 }
377                 memcpy(&path[end], ent.d_name, len+1);
378                 if (ent.d_type == DT_DIR) {
379                         /* case of directories */
380                         if (ent.d_name[0] == '.') {
381                                 if (len == 1)
382                                         continue;
383                                 if (ent.d_name[1] == '.' && len == 2)
384                                         continue;
385                         }
386                         adddirs(path, end+len);;
387                 } else if (ent.d_type == DT_REG) {
388                         /* case of files */
389                         if (!strstr(ent.d_name, ".so"))
390                                 continue;
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