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