only one context
[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  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  * 
18  * Contain all generic part to handle REST/API
19  * 
20  *  https://www.gnu.org/software/libmicrohttpd/tutorial.html [search 'largepost.c']
21  */
22
23 #define _GNU_SOURCE
24
25 #include <stdio.h>
26 #include <assert.h>
27 #include <string.h>
28 #include <dirent.h>
29 #include <dlfcn.h>
30 #include <unistd.h>
31 #include <limits.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <signal.h>
35 #include <time.h>
36 #include <sys/syscall.h>
37 #include <setjmp.h>
38
39 #include "afb-plugin.h"
40 #include "afb-req-itf.h"
41 #include "afb-poll-itf.h"
42
43 #include "session.h"
44 #include "afb-apis.h"
45 #include "afb-api-so.h"
46 #include "verbose.h"
47 #include "utils-upoll.h"
48
49 struct api_so_desc {
50         struct AFB_plugin *plugin;       /* descriptor */
51         void *handle;                    /* context of dlopen */
52         struct AFB_interface interface;
53 };
54
55 static int api_timeout = 15;
56
57 static const char plugin_register_function[] = "pluginRegister";
58
59 static const struct afb_poll_itf upoll_itf = {
60         .on_readable = (void*)upoll_on_readable,
61         .on_writable = (void*)upoll_on_writable,
62         .on_hangup = (void*)upoll_on_hangup,
63         .close = (void*)upoll_close
64 };
65
66 static struct afb_poll itf_poll_open(int fd, void *closure)
67 {
68         struct afb_poll result;
69         result.data = upoll_open(fd, closure);
70         result.itf = result.data ? &upoll_itf : NULL;
71         return result;
72 }
73
74 static void free_context(struct api_so_desc *desc, void *context)
75 {
76         void (*cb)(void*);
77
78         cb = desc->plugin->freeCtxCB;
79         if (cb)
80                 cb(context);
81         else
82                 free(context);
83 }
84
85
86 // Check of apiurl is declare in this plugin and call it
87 extern __thread sigjmp_buf *error_handler;
88 static void trapping_call(struct afb_req req, void(*cb)(struct afb_req))
89 {
90         volatile int signum, timerset;
91         timer_t timerid;
92         sigjmp_buf jmpbuf, *older;
93         struct sigevent sevp;
94         struct itimerspec its;
95
96         // save context before calling the API
97         timerset = 0;
98         older = error_handler;
99         signum = setjmp(jmpbuf);
100         if (signum != 0) {
101                 afb_req_fail_f(req, "aborted", "signal %d caught", signum);
102         }
103         else {
104                 error_handler = &jmpbuf;
105                 if (api_timeout > 0) {
106                         timerset = 1; /* TODO: check statuses */
107                         sevp.sigev_notify = SIGEV_THREAD_ID;
108                         sevp.sigev_signo = SIGALRM;
109                         sevp.sigev_value.sival_ptr = NULL;
110 #if defined(sigev_notify_thread_id)
111                         sevp.sigev_notify_thread_id = (pid_t)syscall(SYS_gettid);
112 #else
113                         sevp._sigev_un._tid = (pid_t)syscall(SYS_gettid);
114 #endif
115                         timer_create(CLOCK_THREAD_CPUTIME_ID, &sevp, &timerid);
116                         its.it_interval.tv_sec = 0;
117                         its.it_interval.tv_nsec = 0;
118                         its.it_value.tv_sec = api_timeout;
119                         its.it_value.tv_nsec = 0;
120                         timer_settime(timerid, 0, &its, NULL);
121                 }
122
123                 cb(req);
124         }
125         if (timerset)
126                 timer_delete(timerid);
127         error_handler = older;
128 }
129
130 static void call_check(struct afb_req req, const struct AFB_restapi *verb)
131 {
132         switch(verb->session) {
133         case AFB_SESSION_CREATE:
134                 if (!afb_req_session_create(req))
135                         return;
136                 break;
137         case AFB_SESSION_RENEW:
138                 if (!afb_req_session_check(req, 1))
139                         return;
140                 break;
141         case AFB_SESSION_CLOSE:
142         case AFB_SESSION_CHECK:
143                 if (!afb_req_session_check(req, 0))
144                         return;
145                 break;
146         case AFB_SESSION_NONE:
147         default:
148                 break;
149         }
150         trapping_call(req, verb->callback);
151
152         if (verb->session == AFB_SESSION_CLOSE)
153                 afb_req_session_close(req);
154 }
155
156 static void call(struct api_so_desc *desc, struct afb_req req, const char *verb, size_t lenverb)
157 {
158         const struct AFB_restapi *v;
159
160         v = desc->plugin->apis;
161         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
162                 v++;
163         if (v->name)
164                 call_check(req, v);
165         else
166                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->plugin->prefix);
167 }
168
169
170
171 int afb_api_so_add_plugin(const char *path)
172 {
173         struct api_so_desc *desc;
174         struct AFB_plugin *(*pluginRegisterFct) (const struct AFB_interface *interface);
175
176         desc = calloc(1, sizeof *desc);
177         if (desc == NULL) {
178                 fprintf(stderr, "[%s] out of memory\n", path);
179                 goto error;
180         }
181
182         // This is a loadable library let's check if it's a plugin
183         desc->handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
184         if (desc->handle == NULL) {
185                 fprintf(stderr, "[%s] not loadable, continuing...\n", path);
186                 goto error2;
187         }
188
189         /* retrieves the register function */
190         pluginRegisterFct = dlsym(desc->handle, plugin_register_function);
191         if (!pluginRegisterFct) {
192                 fprintf(stderr, "[%s] not an AFB plugin, continuing...\n", path);
193                 goto error3;
194         }
195         if (verbosity)
196                 fprintf(stderr, "[%s] is a valid AFB plugin\n", path);
197
198         /* init the interface */
199         desc->interface.verbosity = 0;
200         desc->interface.mode = AFB_MODE_LOCAL;
201         desc->interface.poll_open = itf_poll_open;
202
203         /* init the plugin */
204         desc->plugin = pluginRegisterFct(&desc->interface);
205         if (desc->plugin == NULL) {
206                 fprintf(stderr, "ERROR: plugin [%s] register function failed. continuing...\n", path);
207                 goto error3;
208         }
209
210         /* check the returned structure */
211         if (desc->plugin->type != AFB_PLUGIN_JSON) {
212                 fprintf(stderr, "ERROR: plugin [%s] invalid type %d...\n", path, desc->plugin->type);
213                 goto error3;
214         }
215         if (desc->plugin->prefix == NULL || *desc->plugin->prefix == 0) {
216                 fprintf(stderr, "ERROR: plugin [%s] bad prefix...\n", path);
217                 goto error3;
218         }
219         if (desc->plugin->info == NULL || *desc->plugin->info == 0) {
220                 fprintf(stderr, "ERROR: plugin [%s] bad description...\n", path);
221                 goto error3;
222         }
223         if (desc->plugin->apis == NULL) {
224                 fprintf(stderr, "ERROR: plugin [%s] no APIs...\n", path);
225                 goto error3;
226         }
227
228         /* records the plugin */
229         if (afb_apis_add(desc->plugin->prefix, (struct afb_api){
230                         .closure = desc,
231                         .call = (void*)call,
232                         .free_context = (void*)free_context}) < 0) {
233                 fprintf(stderr, "ERROR: plugin [%s] can't be registered...\n", path);
234                 goto error3;
235         }
236
237         return 0;
238
239 error3:
240         dlclose(desc->handle);
241 error2:
242         free(desc);
243 error:
244         return -1;
245 }
246
247 static int adddirs(char path[PATH_MAX], size_t end)
248 {
249         DIR *dir;
250         struct dirent ent, *result;
251         size_t len;
252
253         /* open the DIR now */
254         dir = opendir(path);
255         if (dir == NULL) {
256                 fprintf(stderr, "ERROR in scanning plugin directory %s, %m\n", path);
257                 return -1;
258         }
259         if (verbosity)
260                 fprintf(stderr, "Scanning dir=[%s] for plugins\n", path);
261
262         /* scan each entry */
263         if (end)
264                 path[end++] = '/';
265         for (;;) {
266                 readdir_r(dir, &ent, &result);
267                 if (result == NULL)
268                         break;
269
270                 len = strlen(ent.d_name);
271                 if (len + end >= PATH_MAX) {
272                         fprintf(stderr, "path too long for %s\n", ent.d_name);
273                         continue;
274                 }
275                 memcpy(&path[end], ent.d_name, len+1);
276                 if (ent.d_type == DT_DIR) {
277                         /* case of directories */
278                         if (ent.d_name[0] == '.') {
279                                 if (len == 1)
280                                         continue;
281                                 if (ent.d_name[1] == '.' && len == 2)
282                                         continue;
283                         }
284                         adddirs(path, end+len);;
285                 } else if (ent.d_type == DT_REG) {
286                         /* case of files */
287                         if (!strstr(ent.d_name, ".so"))
288                                 continue;
289                         afb_api_so_add_plugin(path);
290                 }
291         }
292         closedir(dir);
293         return 0;
294 }
295
296 int afb_api_so_add_directory(const char *path)
297 {
298         size_t length;
299         char buffer[PATH_MAX];
300
301         length = strlen(path);
302         if (length >= sizeof(buffer)) {
303                 fprintf(stderr, "path too long %lu [%.99s...]\n", (unsigned long)length, path);
304                 return -1;
305         }
306
307         memcpy(buffer, path, length + 1);
308         return adddirs(buffer, length);
309 }
310
311 int afb_api_so_add_path(const char *path)
312 {
313         struct stat st;
314         int rc;
315
316         rc = stat(path, &st);
317         if (rc < 0)
318                 fprintf(stderr, "Invalid plugin path [%s]: %m\n", path);
319         else if (S_ISDIR(st.st_mode))
320                 rc = afb_api_so_add_directory(path);
321         else
322                 rc = afb_api_so_add_plugin(path);
323         return rc;
324 }
325
326 int afb_api_so_add_pathset(const char *pathset)
327 {
328         static char sep[] = ":";
329         char *ps, *p;
330
331         ps = strdupa(pathset);
332         for (;;) {
333                 p = strsep(&ps, sep);
334                 if (!p)
335                         return 0;
336                 afb_api_so_add_path(p);
337         };
338 }
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359