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