use upoll for event loop
[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_pollitf upollitf = {
60         .wait = (void*)upoll_wait,
61         .open = (void*)upoll_open,
62         .on_readable = (void*)upoll_on_readable,
63         .on_writable = (void*)upoll_on_writable,
64         .on_hangup = (void*)upoll_on_hangup,
65         .close = (void*)upoll_close
66 };
67
68 static void free_context(struct api_so_desc *desc, void *context)
69 {
70         void (*cb)(void*);
71
72         cb = desc->plugin->freeCtxCB;
73         if (cb)
74                 cb(context);
75         else
76                 free(context);
77 }
78
79
80 // Check of apiurl is declare in this plugin and call it
81 extern __thread sigjmp_buf *error_handler;
82 static void trapping_call(struct afb_req req, void(*cb)(struct afb_req))
83 {
84         volatile int signum, timerset;
85         timer_t timerid;
86         sigjmp_buf jmpbuf, *older;
87         struct sigevent sevp;
88         struct itimerspec its;
89
90         // save context before calling the API
91         timerset = 0;
92         older = error_handler;
93         signum = setjmp(jmpbuf);
94         if (signum != 0) {
95                 afb_req_fail_f(req, "aborted", "signal %d caught", signum);
96         }
97         else {
98                 error_handler = &jmpbuf;
99                 if (api_timeout > 0) {
100                         timerset = 1; /* TODO: check statuses */
101                         sevp.sigev_notify = SIGEV_THREAD_ID;
102                         sevp.sigev_signo = SIGALRM;
103                         sevp.sigev_value.sival_ptr = NULL;
104 #if defined(sigev_notify_thread_id)
105                         sevp.sigev_notify_thread_id = (pid_t)syscall(SYS_gettid);
106 #else
107                         sevp._sigev_un._tid = (pid_t)syscall(SYS_gettid);
108 #endif
109                         timer_create(CLOCK_THREAD_CPUTIME_ID, &sevp, &timerid);
110                         its.it_interval.tv_sec = 0;
111                         its.it_interval.tv_nsec = 0;
112                         its.it_value.tv_sec = api_timeout;
113                         its.it_value.tv_nsec = 0;
114                         timer_settime(timerid, 0, &its, NULL);
115                 }
116
117                 cb(req);
118         }
119         if (timerset)
120                 timer_delete(timerid);
121         error_handler = older;
122 }
123
124 static void call_check(struct afb_req req, const struct AFB_restapi *verb)
125 {
126         switch(verb->session) {
127         case AFB_SESSION_CREATE:
128                 if (!afb_req_session_create(req))
129                         return;
130                 break;
131         case AFB_SESSION_RENEW:
132                 if (!afb_req_session_check(req, 1))
133                         return;
134                 break;
135         case AFB_SESSION_CLOSE:
136         case AFB_SESSION_CHECK:
137                 if (!afb_req_session_check(req, 0))
138                         return;
139                 break;
140         case AFB_SESSION_NONE:
141         default:
142                 break;
143         }
144         trapping_call(req, verb->callback);
145
146         if (verb->session == AFB_SESSION_CLOSE)
147                 afb_req_session_close(req);
148 }
149
150 static void call(struct api_so_desc *desc, struct afb_req req, const char *verb, size_t lenverb)
151 {
152         const struct AFB_restapi *v;
153
154         v = desc->plugin->apis;
155         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
156                 v++;
157         if (v->name)
158                 call_check(req, v);
159         else
160                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->plugin->prefix);
161 }
162
163
164
165 int afb_api_so_add_plugin(const char *path)
166 {
167         struct api_so_desc *desc;
168         struct AFB_plugin *(*pluginRegisterFct) (const struct AFB_interface *interface);
169
170         desc = calloc(1, sizeof *desc);
171         if (desc == NULL) {
172                 fprintf(stderr, "[%s] out of memory\n", path);
173                 goto error;
174         }
175
176         // This is a loadable library let's check if it's a plugin
177         desc->handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
178         if (desc->handle == NULL) {
179                 fprintf(stderr, "[%s] not loadable, continuing...\n", path);
180                 goto error2;
181         }
182
183         /* retrieves the register function */
184         pluginRegisterFct = dlsym(desc->handle, plugin_register_function);
185         if (!pluginRegisterFct) {
186                 fprintf(stderr, "[%s] not an AFB plugin, continuing...\n", path);
187                 goto error3;
188         }
189         if (verbosity)
190                 fprintf(stderr, "[%s] is a valid AFB plugin\n", path);
191
192         /* init the interface */
193         desc->interface.verbosity = 0;
194         desc->interface.mode = AFB_MODE_LOCAL;
195         desc->interface.pollitf = &upollitf;
196         desc->interface.pollclosure = NULL;
197
198         /* init the plugin */
199         desc->plugin = pluginRegisterFct(&desc->interface);
200         if (desc->plugin == NULL) {
201                 fprintf(stderr, "ERROR: plugin [%s] register function failed. continuing...\n", path);
202                 goto error3;
203         }
204
205         /* check the returned structure */
206         if (desc->plugin->type != AFB_PLUGIN_JSON) {
207                 fprintf(stderr, "ERROR: plugin [%s] invalid type %d...\n", path, desc->plugin->type);
208                 goto error3;
209         }
210         if (desc->plugin->prefix == NULL || *desc->plugin->prefix == 0) {
211                 fprintf(stderr, "ERROR: plugin [%s] bad prefix...\n", path);
212                 goto error3;
213         }
214         if (desc->plugin->info == NULL || *desc->plugin->info == 0) {
215                 fprintf(stderr, "ERROR: plugin [%s] bad description...\n", path);
216                 goto error3;
217         }
218         if (desc->plugin->apis == NULL) {
219                 fprintf(stderr, "ERROR: plugin [%s] no APIs...\n", path);
220                 goto error3;
221         }
222
223         /* records the plugin */
224         if (afb_apis_add(desc->plugin->prefix, (struct afb_api){
225                         .closure = desc,
226                         .call = (void*)call,
227                         .free_context = (void*)free_context}) < 0) {
228                 fprintf(stderr, "ERROR: plugin [%s] can't be registered...\n", path);
229                 goto error3;
230         }
231
232         return 0;
233
234 error3:
235         dlclose(desc->handle);
236 error2:
237         free(desc);
238 error:
239         return -1;
240 }
241
242 static int adddirs(char path[PATH_MAX], size_t end)
243 {
244         DIR *dir;
245         struct dirent ent, *result;
246         size_t len;
247
248         /* open the DIR now */
249         dir = opendir(path);
250         if (dir == NULL) {
251                 fprintf(stderr, "ERROR in scanning plugin directory %s, %m\n", path);
252                 return -1;
253         }
254         if (verbosity)
255                 fprintf(stderr, "Scanning dir=[%s] for plugins\n", path);
256
257         /* scan each entry */
258         if (end)
259                 path[end++] = '/';
260         for (;;) {
261                 readdir_r(dir, &ent, &result);
262                 if (result == NULL)
263                         break;
264
265                 len = strlen(ent.d_name);
266                 if (len + end >= PATH_MAX) {
267                         fprintf(stderr, "path too long for %s\n", ent.d_name);
268                         continue;
269                 }
270                 memcpy(&path[end], ent.d_name, len+1);
271                 if (ent.d_type == DT_DIR) {
272                         /* case of directories */
273                         if (ent.d_name[0] == '.') {
274                                 if (len == 1)
275                                         continue;
276                                 if (ent.d_name[1] == '.' && len == 2)
277                                         continue;
278                         }
279                         adddirs(path, end+len);;
280                 } else if (ent.d_type == DT_REG) {
281                         /* case of files */
282                         if (!strstr(ent.d_name, ".so"))
283                                 continue;
284                         afb_api_so_add_plugin(path);
285                 }
286         }
287         closedir(dir);
288         return 0;
289 }
290
291 int afb_api_so_add_directory(const char *path)
292 {
293         size_t length;
294         char buffer[PATH_MAX];
295
296         length = strlen(path);
297         if (length >= sizeof(buffer)) {
298                 fprintf(stderr, "path too long %lu [%.99s...]\n", (unsigned long)length, path);
299                 return -1;
300         }
301
302         memcpy(buffer, path, length + 1);
303         return adddirs(buffer, length);
304 }
305
306 int afb_api_so_add_path(const char *path)
307 {
308         struct stat st;
309         int rc;
310
311         rc = stat(path, &st);
312         if (rc < 0)
313                 fprintf(stderr, "Invalid plugin path [%s]: %m\n", path);
314         else if (S_ISDIR(st.st_mode))
315                 rc = afb_api_so_add_directory(path);
316         else
317                 rc = afb_api_so_add_plugin(path);
318         return rc;
319 }
320
321 int afb_api_so_add_pathset(const char *pathset)
322 {
323         static char sep[] = ":";
324         char *ps, *p;
325
326         ps = strdupa(pathset);
327         for (;;) {
328                 p = strsep(&ps, sep);
329                 if (!p)
330                         return 0;
331                 afb_api_so_add_path(p);
332         };
333 }
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354