Events: refactoring
[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 "verbose.h"
43
44 /*
45  * Description of a plugin
46  */
47 struct api_so_desc {
48         struct AFB_plugin *plugin;      /* descriptor */
49         size_t apilength;               /* length of the API name */
50         void *handle;                   /* context of dlopen */
51         struct AFB_interface interface; /* interface for the plugin */
52 };
53
54 static int api_timeout = 15;
55
56 static const char plugin_register_function_v1[] = "pluginAfbV1Register";
57
58 void afb_api_so_set_timeout(int to)
59 {
60         api_timeout = to;
61 }
62
63 static struct afb_event afb_api_so_event_make(struct api_so_desc *desc, const char *name)
64 {
65         size_t length;
66         char *event;
67
68         /* makes the event name */
69         assert(desc->plugin != NULL);
70         length = strlen(name);
71         event = alloca(length + 2 + desc->apilength);
72         memcpy(event, desc->plugin->v1.prefix, desc->apilength);
73         event[desc->apilength] = '/';
74         memcpy(event + desc->apilength + 1, name, length + 1);
75
76         /* crate the event */
77         return afb_evt_create_event(event);
78 }
79
80 static int afb_api_so_event_broadcast(struct api_so_desc *desc, const char *name, struct json_object *object)
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         return afb_evt_broadcast(event, object);
94 }
95
96 static void afb_api_so_vverbose(struct api_so_desc *desc, int level, const char *file, int line, const char *fmt, va_list args)
97 {
98         char *p;
99
100         if (vasprintf(&p, fmt, args) < 0)
101                 vverbose(level, file, line, fmt, args);
102         else {
103                 verbose(level, file, line, "%s {plugin %s}", p, desc->plugin->v1.prefix);
104                 free(p);
105         }
106 }
107
108 static const struct afb_daemon_itf daemon_itf = {
109         .event_broadcast = (void*)afb_api_so_event_broadcast,
110         .get_event_loop = (void*)afb_common_get_event_loop,
111         .get_user_bus = (void*)afb_common_get_user_bus,
112         .get_system_bus = (void*)afb_common_get_system_bus,
113         .vverbose = (void*)afb_api_so_vverbose,
114         .event_make = (void*)afb_api_so_event_make
115 };
116
117 struct monitoring {
118         struct afb_req req;
119         void (*action)(struct afb_req);
120 };
121
122 static void monitored_call(int signum, struct monitoring *data)
123 {
124         if (signum != 0)
125                 afb_req_fail_f(data->req, "aborted", "signal %s(%d) caught", strsignal(signum), signum);
126         else
127                 data->action(data->req);
128 }
129
130 static void call_check(struct afb_req req, struct afb_context *context, const struct AFB_verb_desc_v1 *verb)
131 {
132         struct monitoring data;
133
134         int stag = (int)verb->session;
135
136         if ((stag & (AFB_SESSION_CREATE|AFB_SESSION_CLOSE|AFB_SESSION_RENEW|AFB_SESSION_CHECK|AFB_SESSION_LOA_EQ)) != 0) {
137                 if (!afb_context_check(context)) {
138                         afb_context_close(context);
139                         afb_req_fail(req, "failed", "invalid token's identity");
140                         return;
141                 }       
142         }
143
144         if ((stag & AFB_SESSION_CREATE) != 0) {
145                 if (afb_context_check_loa(context, 1)) {
146                         afb_req_fail(req, "failed", "invalid creation state");
147                         return;
148                 }
149                 afb_context_change_loa(context, 1);
150                 afb_context_refresh(context);
151         }
152         
153         if ((stag & (AFB_SESSION_CREATE | AFB_SESSION_RENEW)) != 0)
154                 afb_context_refresh(context);
155
156         if ((stag & AFB_SESSION_CLOSE) != 0) {
157                 afb_context_change_loa(context, 0);
158                 afb_context_close(context);
159         }
160
161         if ((stag & AFB_SESSION_LOA_GE) != 0) {
162                 int loa = (stag >> AFB_SESSION_LOA_SHIFT) & AFB_SESSION_LOA_MASK;
163                 if (!afb_context_check_loa(context, loa)) {
164                         afb_req_fail(req, "failed", "invalid LOA");
165                         return;
166                 }
167         }
168
169         if ((stag & AFB_SESSION_LOA_LE) != 0) {
170                 int loa = (stag >> AFB_SESSION_LOA_SHIFT) & AFB_SESSION_LOA_MASK;
171                 if (afb_context_check_loa(context, loa + 1)) {
172                         afb_req_fail(req, "failed", "invalid LOA");
173                         return;
174                 }
175         }
176
177         data.req = req;
178         data.action = verb->callback;
179         afb_sig_monitor((void*)monitored_call, &data, api_timeout);
180 }
181
182 static void call(struct api_so_desc *desc, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
183 {
184         const struct AFB_verb_desc_v1 *v;
185
186         v = desc->plugin->v1.verbs;
187         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
188                 v++;
189         if (v->name)
190                 call_check(req, context, v);
191         else
192                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->plugin->v1.prefix);
193 }
194
195 int afb_api_so_add_plugin(const char *path)
196 {
197         int rc;
198         void *handle;
199         struct api_so_desc *desc;
200         struct AFB_plugin *(*pluginAfbV1RegisterFct) (const struct AFB_interface *interface);
201
202         // This is a loadable library let's check if it's a plugin
203         rc = 0;
204         handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
205         if (handle == NULL) {
206                 ERROR("plugin [%s] not loadable", path);
207                 goto error;
208         }
209
210         /* retrieves the register function */
211         pluginAfbV1RegisterFct = dlsym(handle, plugin_register_function_v1);
212         if (!pluginAfbV1RegisterFct) {
213                 ERROR("plugin [%s] is not an AFB plugin", path);
214                 goto error2;
215         }
216         INFO("plugin [%s] is a valid AFB plugin", path);
217         rc = -1;
218
219         /* allocates the description */
220         desc = calloc(1, sizeof *desc);
221         if (desc == NULL) {
222                 ERROR("out of memory");
223                 goto error2;
224         }
225         desc->handle = handle;
226
227         /* init the interface */
228         desc->interface.verbosity = verbosity;
229         desc->interface.mode = AFB_MODE_LOCAL;
230         desc->interface.daemon.itf = &daemon_itf;
231         desc->interface.daemon.closure = desc;
232
233         /* init the plugin */
234         NOTICE("plugin [%s] calling registering function %s", path, plugin_register_function_v1);
235         desc->plugin = pluginAfbV1RegisterFct(&desc->interface);
236         if (desc->plugin == NULL) {
237                 ERROR("plugin [%s] register function failed. continuing...", path);
238                 goto error3;
239         }
240
241         /* check the returned structure */
242         if (desc->plugin->type != AFB_PLUGIN_VERSION_1) {
243                 ERROR("plugin [%s] invalid type %d...", path, desc->plugin->type);
244                 goto error3;
245         }
246         if (desc->plugin->v1.prefix == NULL || *desc->plugin->v1.prefix == 0) {
247                 ERROR("plugin [%s] bad prefix...", path);
248                 goto error3;
249         }
250         if (!afb_apis_is_valid_api_name(desc->plugin->v1.prefix)) {
251                 ERROR("plugin [%s] invalid prefix...", path);
252                 goto error3;
253         }
254         if (desc->plugin->v1.info == NULL || *desc->plugin->v1.info == 0) {
255                 ERROR("plugin [%s] bad description...", path);
256                 goto error3;
257         }
258         if (desc->plugin->v1.verbs == NULL) {
259                 ERROR("plugin [%s] no APIs...", path);
260                 goto error3;
261         }
262
263         /* records the plugin */
264         desc->apilength = strlen(desc->plugin->v1.prefix);
265         if (afb_apis_add(desc->plugin->v1.prefix, (struct afb_api){
266                         .closure = desc,
267                         .call = (void*)call}) < 0) {
268                 ERROR("plugin [%s] can't be registered...", path);
269                 goto error3;
270         }
271         NOTICE("plugin %s loaded with API prefix %s", path, desc->plugin->v1.prefix);
272         return 0;
273
274 error3:
275         free(desc);
276 error2:
277         dlclose(handle);
278 error:
279         return rc;
280 }
281
282 static int adddirs(char path[PATH_MAX], size_t end)
283 {
284         DIR *dir;
285         struct dirent ent, *result;
286         size_t len;
287
288         /* open the DIR now */
289         dir = opendir(path);
290         if (dir == NULL) {
291                 ERROR("can't scan plugin directory %s, %m", path);
292                 return -1;
293         }
294         INFO("Scanning dir=[%s] for plugins", path);
295
296         /* scan each entry */
297         if (end)
298                 path[end++] = '/';
299         for (;;) {
300                 readdir_r(dir, &ent, &result);
301                 if (result == NULL)
302                         break;
303
304                 len = strlen(ent.d_name);
305                 if (len + end >= PATH_MAX) {
306                         ERROR("path too long while scanning plugins for %s", ent.d_name);
307                         continue;
308                 }
309                 memcpy(&path[end], ent.d_name, len+1);
310                 if (ent.d_type == DT_DIR) {
311                         /* case of directories */
312                         if (ent.d_name[0] == '.') {
313                                 if (len == 1)
314                                         continue;
315                                 if (ent.d_name[1] == '.' && len == 2)
316                                         continue;
317                         }
318                         adddirs(path, end+len);;
319                 } else if (ent.d_type == DT_REG) {
320                         /* case of files */
321                         if (!strstr(ent.d_name, ".so"))
322                                 continue;
323                         if (afb_api_so_add_plugin(path) < 0)
324                                 return -1;
325                 }
326         }
327         closedir(dir);
328         return 0;
329 }
330
331 int afb_api_so_add_directory(const char *path)
332 {
333         size_t length;
334         char buffer[PATH_MAX];
335
336         length = strlen(path);
337         if (length >= sizeof(buffer)) {
338                 ERROR("path too long %lu [%.99s...]", (unsigned long)length, path);
339                 return -1;
340         }
341
342         memcpy(buffer, path, length + 1);
343         return adddirs(buffer, length);
344 }
345
346 int afb_api_so_add_path(const char *path)
347 {
348         struct stat st;
349         int rc;
350
351         rc = stat(path, &st);
352         if (rc < 0)
353                 ERROR("Invalid plugin path [%s]: %m", path);
354         else if (S_ISDIR(st.st_mode))
355                 rc = afb_api_so_add_directory(path);
356         else if (strstr(path, ".so"))
357                 rc = afb_api_so_add_plugin(path);
358         else
359                 INFO("not a plugin [%s], skipped", path);
360         return rc;
361 }
362
363 int afb_api_so_add_pathset(const char *pathset)
364 {
365         static char sep[] = ":";
366         char *ps, *p;
367
368         ps = strdupa(pathset);
369         for (;;) {
370                 p = strsep(&ps, sep);
371                 if (!p)
372                         return 0;
373                 if (afb_api_so_add_path(p) < 0)
374                         return -1;
375         }
376 }
377