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