changing the license to apache 2
[src/app-framework-binder.git] / src / afb-api-so.c
1 /*
2  * Copyright (C) 2016 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdio.h>
21 #include <assert.h>
22 #include <string.h>
23 #include <dirent.h>
24 #include <dlfcn.h>
25 #include <unistd.h>
26 #include <limits.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <signal.h>
30 #include <time.h>
31 #include <sys/syscall.h>
32 #include <setjmp.h>
33
34 #include "afb-plugin.h"
35 #include "afb-req-itf.h"
36 #include "afb-poll-itf.h"
37
38 #include "session.h"
39 #include "afb-apis.h"
40 #include "afb-api-so.h"
41 #include "verbose.h"
42 #include "utils-upoll.h"
43
44 struct api_so_desc {
45         struct AFB_plugin *plugin;       /* descriptor */
46         void *handle;                    /* context of dlopen */
47         struct AFB_interface interface;
48 };
49
50 static int api_timeout = 15;
51
52 static const char plugin_register_function[] = "pluginRegister";
53
54 static const struct afb_pollitf upollitf = {
55         .wait = (void*)upoll_wait,
56         .open = (void*)upoll_open,
57         .on_readable = (void*)upoll_on_readable,
58         .on_writable = (void*)upoll_on_writable,
59         .on_hangup = (void*)upoll_on_hangup,
60         .close = (void*)upoll_close
61 };
62
63 static void free_context(struct api_so_desc *desc, void *context)
64 {
65         void (*cb)(void*);
66
67         cb = desc->plugin->freeCtxCB;
68         if (cb)
69                 cb(context);
70         else
71                 free(context);
72 }
73
74
75 // Check of apiurl is declare in this plugin and call it
76 extern __thread sigjmp_buf *error_handler;
77 static void trapping_call(struct afb_req req, void(*cb)(struct afb_req))
78 {
79         volatile int signum, timerset;
80         timer_t timerid;
81         sigjmp_buf jmpbuf, *older;
82         struct sigevent sevp;
83         struct itimerspec its;
84
85         // save context before calling the API
86         timerset = 0;
87         older = error_handler;
88         signum = setjmp(jmpbuf);
89         if (signum != 0) {
90                 afb_req_fail_f(req, "aborted", "signal %d caught", signum);
91         }
92         else {
93                 error_handler = &jmpbuf;
94                 if (api_timeout > 0) {
95                         timerset = 1; /* TODO: check statuses */
96                         sevp.sigev_notify = SIGEV_THREAD_ID;
97                         sevp.sigev_signo = SIGALRM;
98                         sevp.sigev_value.sival_ptr = NULL;
99 #if defined(sigev_notify_thread_id)
100                         sevp.sigev_notify_thread_id = (pid_t)syscall(SYS_gettid);
101 #else
102                         sevp._sigev_un._tid = (pid_t)syscall(SYS_gettid);
103 #endif
104                         timer_create(CLOCK_THREAD_CPUTIME_ID, &sevp, &timerid);
105                         its.it_interval.tv_sec = 0;
106                         its.it_interval.tv_nsec = 0;
107                         its.it_value.tv_sec = api_timeout;
108                         its.it_value.tv_nsec = 0;
109                         timer_settime(timerid, 0, &its, NULL);
110                 }
111
112                 cb(req);
113         }
114         if (timerset)
115                 timer_delete(timerid);
116         error_handler = older;
117 }
118
119 static void call_check(struct afb_req req, const struct AFB_restapi *verb)
120 {
121         switch(verb->session) {
122         case AFB_SESSION_CREATE:
123                 if (!afb_req_session_create(req))
124                         return;
125                 break;
126         case AFB_SESSION_RENEW:
127                 if (!afb_req_session_check(req, 1))
128                         return;
129                 break;
130         case AFB_SESSION_CLOSE:
131         case AFB_SESSION_CHECK:
132                 if (!afb_req_session_check(req, 0))
133                         return;
134                 break;
135         case AFB_SESSION_NONE:
136         default:
137                 break;
138         }
139         trapping_call(req, verb->callback);
140
141         if (verb->session == AFB_SESSION_CLOSE)
142                 afb_req_session_close(req);
143 }
144
145 static void call(struct api_so_desc *desc, struct afb_req req, const char *verb, size_t lenverb)
146 {
147         const struct AFB_restapi *v;
148
149         v = desc->plugin->apis;
150         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
151                 v++;
152         if (v->name)
153                 call_check(req, v);
154         else
155                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->plugin->prefix);
156 }
157
158
159
160 int afb_api_so_add_plugin(const char *path)
161 {
162         struct api_so_desc *desc;
163         struct AFB_plugin *(*pluginRegisterFct) (const struct AFB_interface *interface);
164
165         desc = calloc(1, sizeof *desc);
166         if (desc == NULL) {
167                 fprintf(stderr, "[%s] out of memory\n", path);
168                 goto error;
169         }
170
171         // This is a loadable library let's check if it's a plugin
172         desc->handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
173         if (desc->handle == NULL) {
174                 fprintf(stderr, "[%s] not loadable, continuing...\n", path);
175                 goto error2;
176         }
177
178         /* retrieves the register function */
179         pluginRegisterFct = dlsym(desc->handle, plugin_register_function);
180         if (!pluginRegisterFct) {
181                 fprintf(stderr, "[%s] not an AFB plugin, continuing...\n", path);
182                 goto error3;
183         }
184         if (verbosity)
185                 fprintf(stderr, "[%s] is a valid AFB plugin\n", path);
186
187         /* init the interface */
188         desc->interface.verbosity = 0;
189         desc->interface.mode = AFB_MODE_LOCAL;
190         desc->interface.pollitf = &upollitf;
191         desc->interface.pollclosure = NULL;
192
193         /* init the plugin */
194         desc->plugin = pluginRegisterFct(&desc->interface);
195         if (desc->plugin == NULL) {
196                 fprintf(stderr, "ERROR: plugin [%s] register function failed. continuing...\n", path);
197                 goto error3;
198         }
199
200         /* check the returned structure */
201         if (desc->plugin->type != AFB_PLUGIN_JSON) {
202                 fprintf(stderr, "ERROR: plugin [%s] invalid type %d...\n", path, desc->plugin->type);
203                 goto error3;
204         }
205         if (desc->plugin->prefix == NULL || *desc->plugin->prefix == 0) {
206                 fprintf(stderr, "ERROR: plugin [%s] bad prefix...\n", path);
207                 goto error3;
208         }
209         if (desc->plugin->info == NULL || *desc->plugin->info == 0) {
210                 fprintf(stderr, "ERROR: plugin [%s] bad description...\n", path);
211                 goto error3;
212         }
213         if (desc->plugin->apis == NULL) {
214                 fprintf(stderr, "ERROR: plugin [%s] no APIs...\n", path);
215                 goto error3;
216         }
217
218         /* records the plugin */
219         if (afb_apis_add(desc->plugin->prefix, (struct afb_api){
220                         .closure = desc,
221                         .call = (void*)call,
222                         .free_context = (void*)free_context}) < 0) {
223                 fprintf(stderr, "ERROR: plugin [%s] can't be registered...\n", path);
224                 goto error3;
225         }
226
227         return 0;
228
229 error3:
230         dlclose(desc->handle);
231 error2:
232         free(desc);
233 error:
234         return -1;
235 }
236
237 static int adddirs(char path[PATH_MAX], size_t end)
238 {
239         DIR *dir;
240         struct dirent ent, *result;
241         size_t len;
242
243         /* open the DIR now */
244         dir = opendir(path);
245         if (dir == NULL) {
246                 fprintf(stderr, "ERROR in scanning plugin directory %s, %m\n", path);
247                 return -1;
248         }
249         if (verbosity)
250                 fprintf(stderr, "Scanning dir=[%s] for plugins\n", path);
251
252         /* scan each entry */
253         if (end)
254                 path[end++] = '/';
255         for (;;) {
256                 readdir_r(dir, &ent, &result);
257                 if (result == NULL)
258                         break;
259
260                 len = strlen(ent.d_name);
261                 if (len + end >= PATH_MAX) {
262                         fprintf(stderr, "path too long for %s\n", ent.d_name);
263                         continue;
264                 }
265                 memcpy(&path[end], ent.d_name, len+1);
266                 if (ent.d_type == DT_DIR) {
267                         /* case of directories */
268                         if (ent.d_name[0] == '.') {
269                                 if (len == 1)
270                                         continue;
271                                 if (ent.d_name[1] == '.' && len == 2)
272                                         continue;
273                         }
274                         adddirs(path, end+len);;
275                 } else if (ent.d_type == DT_REG) {
276                         /* case of files */
277                         if (!strstr(ent.d_name, ".so"))
278                                 continue;
279                         afb_api_so_add_plugin(path);
280                 }
281         }
282         closedir(dir);
283         return 0;
284 }
285
286 int afb_api_so_add_directory(const char *path)
287 {
288         size_t length;
289         char buffer[PATH_MAX];
290
291         length = strlen(path);
292         if (length >= sizeof(buffer)) {
293                 fprintf(stderr, "path too long %lu [%.99s...]\n", (unsigned long)length, path);
294                 return -1;
295         }
296
297         memcpy(buffer, path, length + 1);
298         return adddirs(buffer, length);
299 }
300
301 int afb_api_so_add_path(const char *path)
302 {
303         struct stat st;
304         int rc;
305
306         rc = stat(path, &st);
307         if (rc < 0)
308                 fprintf(stderr, "Invalid plugin path [%s]: %m\n", path);
309         else if (S_ISDIR(st.st_mode))
310                 rc = afb_api_so_add_directory(path);
311         else
312                 rc = afb_api_so_add_plugin(path);
313         return rc;
314 }
315
316 int afb_api_so_add_pathset(const char *pathset)
317 {
318         static char sep[] = ":";
319         char *ps, *p;
320
321         ps = strdupa(pathset);
322         for (;;) {
323                 p = strsep(&ps, sep);
324                 if (!p)
325                         return 0;
326                 afb_api_so_add_path(p);
327         };
328 }
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349