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