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