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