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