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