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