minor reordering of code
[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_PLUGIN_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-plugin.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 plugin
47  */
48 struct api_so_desc {
49         struct AFB_plugin *plugin;      /* 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_interface interface; /* interface for the plugin */
54 };
55
56 struct monitoring {
57         struct afb_req req;
58         void (*action)(struct afb_req);
59 };
60
61 static const char plugin_register_function_v1[] = "pluginAfbV1Register";
62 static const char plugin_service_init_function_v1[] = "pluginAfbV1ServiceInit";
63 static const char plugin_service_event_function_v1[] = "pluginAfbV1ServiceEvent";
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->plugin != NULL);
87         length = strlen(name);
88         event = alloca(length + 2 + desc->apilength);
89         memcpy(event, desc->plugin->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->plugin != NULL);
104         length = strlen(name);
105         event = alloca(length + 2 + desc->apilength);
106         memcpy(event, desc->plugin->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 {plugin %s}", p, desc->plugin->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->plugin->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->plugin->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->plugin->v1.prefix);
211                 return -1;
212         }
213
214         /* get the initialisation */
215         init = dlsym(desc->handle, plugin_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->plugin->v1.prefix);
223                 return -1;
224         }
225
226         /* get the event handler if any */
227         onevent = dlsym(desc->handle, plugin_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->plugin->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_plugin(const char *path)
244 {
245         int rc;
246         void *handle;
247         struct api_so_desc *desc;
248         struct AFB_plugin *(*pluginAfbV1RegisterFct) (const struct AFB_interface *interface);
249
250         // This is a loadable library let's check if it's a plugin
251         rc = 0;
252         handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
253         if (handle == NULL) {
254                 ERROR("plugin [%s] not loadable", path);
255                 goto error;
256         }
257
258         /* retrieves the register function */
259         pluginAfbV1RegisterFct = dlsym(handle, plugin_register_function_v1);
260         if (!pluginAfbV1RegisterFct) {
261                 ERROR("plugin [%s] is not an AFB plugin", path);
262                 goto error2;
263         }
264         INFO("plugin [%s] is a valid AFB plugin", path);
265         rc = -1;
266
267         /* allocates the description */
268         desc = calloc(1, sizeof *desc);
269         if (desc == NULL) {
270                 ERROR("out of memory");
271                 goto error2;
272         }
273         desc->handle = handle;
274
275         /* init the interface */
276         desc->interface.verbosity = verbosity;
277         desc->interface.mode = AFB_MODE_LOCAL;
278         desc->interface.daemon.itf = &daemon_itf;
279         desc->interface.daemon.closure = desc;
280
281         /* init the plugin */
282         NOTICE("plugin [%s] calling registering function %s", path, plugin_register_function_v1);
283         desc->plugin = pluginAfbV1RegisterFct(&desc->interface);
284         if (desc->plugin == NULL) {
285                 ERROR("plugin [%s] register function failed. continuing...", path);
286                 goto error3;
287         }
288
289         /* check the returned structure */
290         if (desc->plugin->type != AFB_PLUGIN_VERSION_1) {
291                 ERROR("plugin [%s] invalid type %d...", path, desc->plugin->type);
292                 goto error3;
293         }
294         if (desc->plugin->v1.prefix == NULL || *desc->plugin->v1.prefix == 0) {
295                 ERROR("plugin [%s] bad prefix...", path);
296                 goto error3;
297         }
298         if (!afb_apis_is_valid_api_name(desc->plugin->v1.prefix)) {
299                 ERROR("plugin [%s] invalid prefix...", path);
300                 goto error3;
301         }
302         if (desc->plugin->v1.info == NULL || *desc->plugin->v1.info == 0) {
303                 ERROR("plugin [%s] bad description...", path);
304                 goto error3;
305         }
306         if (desc->plugin->v1.verbs == NULL) {
307                 ERROR("plugin [%s] no APIs...", path);
308                 goto error3;
309         }
310
311         /* records the plugin */
312         desc->apilength = strlen(desc->plugin->v1.prefix);
313         if (afb_apis_add(desc->plugin->v1.prefix, (struct afb_api){
314                         .closure = desc,
315                         .call = (void*)call,
316                         .service_start = (void*)service_start }) < 0) {
317                 ERROR("plugin [%s] can't be registered...", path);
318                 goto error3;
319         }
320         NOTICE("plugin %s loaded with API prefix %s", path, desc->plugin->v1.prefix);
321         return 0;
322
323 error3:
324         free(desc);
325 error2:
326         dlclose(handle);
327 error:
328         return rc;
329 }
330
331 static int adddirs(char path[PATH_MAX], size_t end)
332 {
333         DIR *dir;
334         struct dirent ent, *result;
335         size_t len;
336
337         /* open the DIR now */
338         dir = opendir(path);
339         if (dir == NULL) {
340                 ERROR("can't scan plugin directory %s, %m", path);
341                 return -1;
342         }
343         INFO("Scanning dir=[%s] for plugins", path);
344
345         /* scan each entry */
346         if (end)
347                 path[end++] = '/';
348         for (;;) {
349                 readdir_r(dir, &ent, &result);
350                 if (result == NULL)
351                         break;
352
353                 len = strlen(ent.d_name);
354                 if (len + end >= PATH_MAX) {
355                         ERROR("path too long while scanning plugins for %s", ent.d_name);
356                         continue;
357                 }
358                 memcpy(&path[end], ent.d_name, len+1);
359                 if (ent.d_type == DT_DIR) {
360                         /* case of directories */
361                         if (ent.d_name[0] == '.') {
362                                 if (len == 1)
363                                         continue;
364                                 if (ent.d_name[1] == '.' && len == 2)
365                                         continue;
366                         }
367                         adddirs(path, end+len);;
368                 } else if (ent.d_type == DT_REG) {
369                         /* case of files */
370                         if (!strstr(ent.d_name, ".so"))
371                                 continue;
372                         if (afb_api_so_add_plugin(path) < 0)
373                                 return -1;
374                 }
375         }
376         closedir(dir);
377         return 0;
378 }
379
380 int afb_api_so_add_directory(const char *path)
381 {
382         size_t length;
383         char buffer[PATH_MAX];
384
385         length = strlen(path);
386         if (length >= sizeof(buffer)) {
387                 ERROR("path too long %lu [%.99s...]", (unsigned long)length, path);
388                 return -1;
389         }
390
391         memcpy(buffer, path, length + 1);
392         return adddirs(buffer, length);
393 }
394
395 int afb_api_so_add_path(const char *path)
396 {
397         struct stat st;
398         int rc;
399
400         rc = stat(path, &st);
401         if (rc < 0)
402                 ERROR("Invalid plugin path [%s]: %m", path);
403         else if (S_ISDIR(st.st_mode))
404                 rc = afb_api_so_add_directory(path);
405         else if (strstr(path, ".so"))
406                 rc = afb_api_so_add_plugin(path);
407         else
408                 INFO("not a plugin [%s], skipped", path);
409         return rc;
410 }
411
412 int afb_api_so_add_pathset(const char *pathset)
413 {
414         static char sep[] = ":";
415         char *ps, *p;
416
417         ps = strdupa(pathset);
418         for (;;) {
419                 p = strsep(&ps, sep);
420                 if (!p)
421                         return 0;
422                 if (afb_api_so_add_path(p) < 0)
423                         return -1;
424         }
425 }
426