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