removing casts to (void*)
[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_cb(void *closure, const char *name);
68 static int afb_api_so_event_broadcast_cb(void *closure, const char *name, struct json_object *object);
69 static void afb_api_so_vverbose_cb(void *closure, 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 = afb_api_so_event_broadcast_cb,
73         .get_event_loop = afb_common_get_event_loop,
74         .get_user_bus = afb_common_get_user_bus,
75         .get_system_bus = afb_common_get_system_bus,
76         .vverbose = afb_api_so_vverbose_cb,
77         .event_make = afb_api_so_event_make_cb
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 void monitored_call(int signum, void *arg)
129 {
130         struct monitoring *data = arg;
131         if (signum != 0)
132                 afb_req_fail_f(data->req, "aborted", "signal %s(%d) caught", strsignal(signum), signum);
133         else
134                 data->action(data->req);
135 }
136
137 static void call_check(struct afb_req req, struct afb_context *context, const struct afb_verb_desc_v1 *verb)
138 {
139         struct monitoring data;
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;
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;
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;
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;
181                 }
182         }
183
184         data.req = req;
185         data.action = verb->callback;
186         afb_sig_monitor(monitored_call, &data, api_timeout);
187 }
188
189 static void call_cb(void *closure, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
190 {
191         const struct afb_verb_desc_v1 *v;
192         struct api_so_desc *desc = closure;
193
194         v = desc->binding->v1.verbs;
195         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
196                 v++;
197         if (v->name)
198                 call_check(req, context, v);
199         else
200                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->binding->v1.prefix);
201 }
202
203 static int service_start_cb(void *closure, int share_session, int onneed)
204 {
205         int (*init)(struct afb_service service);
206         void (*onevent)(const char *event, struct json_object *object);
207
208         struct api_so_desc *desc = closure;
209
210         /* check state */
211         if (desc->service != NULL) {
212                 /* not an error when onneed */
213                 if (onneed != 0)
214                         return 0;
215
216                 /* already started: it is an error */
217                 ERROR("Service %s already started", desc->binding->v1.prefix);
218                 return -1;
219         }
220
221         /* get the initialisation */
222         init = dlsym(desc->handle, binding_service_init_function_v1);
223         if (init == NULL) {
224                 /* not an error when onneed */
225                 if (onneed != 0)
226                         return 0;
227
228                 /* no initialisation method */
229                 ERROR("Binding %s is not a service", desc->binding->v1.prefix);
230                 return -1;
231         }
232
233         /* get the event handler if any */
234         onevent = dlsym(desc->handle, binding_service_event_function_v1);
235         desc->service = afb_svc_create(share_session, init, onevent);
236         if (desc->service == NULL) {
237                 /* starting error */
238                 ERROR("Starting service %s failed", desc->binding->v1.prefix);
239                 return -1;
240         }
241
242         return 0;
243 }
244
245 void afb_api_so_set_timeout(int to)
246 {
247         api_timeout = to;
248 }
249
250 int afb_api_so_add_binding(const char *path)
251 {
252         int rc;
253         void *handle;
254         struct api_so_desc *desc;
255         struct afb_binding *(*register_function) (const struct afb_binding_interface *interface);
256         struct afb_verb_desc_v1 fake_verb;
257         struct afb_binding fake_binding;
258
259         // This is a loadable library let's check if it's a binding
260         rc = 0;
261         handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
262         if (handle == NULL) {
263                 ERROR("binding [%s] not loadable", path);
264                 goto error;
265         }
266
267         /* retrieves the register function */
268         register_function = dlsym(handle, binding_register_function_v1);
269         if (!register_function) {
270                 ERROR("binding [%s] is not an AFB binding", path);
271                 goto error2;
272         }
273         INFO("binding [%s] is a valid AFB binding", path);
274         rc = -1;
275
276         /* allocates the description */
277         desc = calloc(1, sizeof *desc);
278         if (desc == NULL) {
279                 ERROR("out of memory");
280                 goto error2;
281         }
282         desc->handle = handle;
283
284         /* init the interface */
285         desc->interface.verbosity = verbosity;
286         desc->interface.mode = AFB_MODE_LOCAL;
287         desc->interface.daemon.itf = &daemon_itf;
288         desc->interface.daemon.closure = desc;
289
290         /* for log purpose, a fake binding is needed here */
291         desc->binding = &fake_binding;
292         fake_binding.type = AFB_BINDING_VERSION_1;
293         fake_binding.v1.info = path;
294         fake_binding.v1.prefix = path;
295         fake_binding.v1.verbs = &fake_verb;
296         fake_verb.name = NULL;
297
298         /* init the binding */
299         NOTICE("binding [%s] calling registering function %s", path, binding_register_function_v1);
300         desc->binding = register_function(&desc->interface);
301         if (desc->binding == NULL) {
302                 ERROR("binding [%s] register function failed. continuing...", path);
303                 goto error3;
304         }
305
306         /* check the returned structure */
307         if (desc->binding->type != AFB_BINDING_VERSION_1) {
308                 ERROR("binding [%s] invalid type %d...", path, desc->binding->type);
309                 goto error3;
310         }
311         if (desc->binding->v1.prefix == NULL || *desc->binding->v1.prefix == 0) {
312                 ERROR("binding [%s] bad prefix...", path);
313                 goto error3;
314         }
315         if (!afb_apis_is_valid_api_name(desc->binding->v1.prefix)) {
316                 ERROR("binding [%s] invalid prefix...", path);
317                 goto error3;
318         }
319         if (desc->binding->v1.info == NULL || *desc->binding->v1.info == 0) {
320                 ERROR("binding [%s] bad description...", path);
321                 goto error3;
322         }
323         if (desc->binding->v1.verbs == NULL) {
324                 ERROR("binding [%s] no APIs...", path);
325                 goto error3;
326         }
327
328         /* records the binding */
329         desc->apilength = strlen(desc->binding->v1.prefix);
330         if (afb_apis_add(desc->binding->v1.prefix, (struct afb_api){
331                         .closure = desc,
332                         .call = call_cb,
333                         .service_start = service_start_cb }) < 0) {
334                 ERROR("binding [%s] can't be registered...", path);
335                 goto error3;
336         }
337         NOTICE("binding %s loaded with API prefix %s", path, desc->binding->v1.prefix);
338         return 0;
339
340 error3:
341         free(desc);
342 error2:
343         dlclose(handle);
344 error:
345         return rc;
346 }
347
348 static int adddirs(char path[PATH_MAX], size_t end)
349 {
350         DIR *dir;
351         struct dirent ent, *result;
352         size_t len;
353
354         /* open the DIR now */
355         dir = opendir(path);
356         if (dir == NULL) {
357                 ERROR("can't scan binding directory %s, %m", path);
358                 return -1;
359         }
360         INFO("Scanning dir=[%s] for bindings", path);
361
362         /* scan each entry */
363         if (end)
364                 path[end++] = '/';
365         for (;;) {
366                 readdir_r(dir, &ent, &result);
367                 if (result == NULL)
368                         break;
369
370                 len = strlen(ent.d_name);
371                 if (len + end >= PATH_MAX) {
372                         ERROR("path too long while scanning bindings for %s", ent.d_name);
373                         continue;
374                 }
375                 memcpy(&path[end], ent.d_name, len+1);
376                 if (ent.d_type == DT_DIR) {
377                         /* case of directories */
378                         if (ent.d_name[0] == '.') {
379                                 if (len == 1)
380                                         continue;
381                                 if (ent.d_name[1] == '.' && len == 2)
382                                         continue;
383                         }
384                         adddirs(path, end+len);;
385                 } else if (ent.d_type == DT_REG) {
386                         /* case of files */
387                         if (!strstr(ent.d_name, ".so"))
388                                 continue;
389                         if (afb_api_so_add_binding(path) < 0)
390                                 return -1;
391                 }
392         }
393         closedir(dir);
394         return 0;
395 }
396
397 int afb_api_so_add_directory(const char *path)
398 {
399         size_t length;
400         char buffer[PATH_MAX];
401
402         length = strlen(path);
403         if (length >= sizeof(buffer)) {
404                 ERROR("path too long %lu [%.99s...]", (unsigned long)length, path);
405                 return -1;
406         }
407
408         memcpy(buffer, path, length + 1);
409         return adddirs(buffer, length);
410 }
411
412 int afb_api_so_add_path(const char *path)
413 {
414         struct stat st;
415         int rc;
416
417         rc = stat(path, &st);
418         if (rc < 0)
419                 ERROR("Invalid binding path [%s]: %m", path);
420         else if (S_ISDIR(st.st_mode))
421                 rc = afb_api_so_add_directory(path);
422         else if (strstr(path, ".so"))
423                 rc = afb_api_so_add_binding(path);
424         else
425                 INFO("not a binding [%s], skipped", path);
426         return rc;
427 }
428
429 int afb_api_so_add_pathset(const char *pathset)
430 {
431         static char sep[] = ":";
432         char *ps, *p;
433
434         ps = strdupa(pathset);
435         for (;;) {
436                 p = strsep(&ps, sep);
437                 if (!p)
438                         return 0;
439                 if (afb_api_so_add_path(p) < 0)
440                         return -1;
441         }
442 }
443