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