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