refactored logging
[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-evmgr-itf.h"
37
38 #include "session.h"
39 #include "afb-common.h"
40 #include "afb-context.h"
41 #include "afb-apis.h"
42 #include "afb-api-so.h"
43 #include "verbose.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 void afb_api_so_evmgr_push(struct api_so_desc *desc, const char *name, struct json_object *object)
59 {
60         size_t length;
61         char *event;
62
63         assert(desc->plugin != NULL);
64         length = strlen(name);
65         event = alloca(length + 2 + desc->apilength);
66         memcpy(event, desc->plugin->prefix, desc->apilength);
67         event[desc->apilength] = '/';
68         memcpy(event + desc->apilength + 1, name, length + 1);
69         ctxClientEventSend(NULL, event, object);
70 }
71
72 static const struct afb_evmgr_itf evmgr_itf = {
73         .push = (void*)afb_api_so_evmgr_push
74 };
75
76 static struct afb_evmgr afb_api_so_get_evmgr(struct api_so_desc *desc)
77 {
78         return (struct afb_evmgr){ .itf = &evmgr_itf, .closure = desc };
79 }
80
81 static const struct afb_daemon_itf daemon_itf = {
82         .get_evmgr = (void*)afb_api_so_get_evmgr,
83         .get_event_loop = (void*)afb_common_get_event_loop,
84         .get_user_bus = (void*)afb_common_get_user_bus,
85         .get_system_bus = (void*)afb_common_get_system_bus
86 };
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, struct afb_context *context, const struct AFB_restapi *verb)
131 {
132         int stag = (int)(verb->session & AFB_SESSION_MASK);
133
134         if (stag != AFB_SESSION_NONE) {
135                 if (!afb_context_check(context)) {
136                         afb_context_close(context);
137                         afb_req_fail(req, "failed", "invalid token's identity");
138                         return;
139                 }       
140         }
141
142         if ((stag & AFB_SESSION_CREATE) != 0) {
143                 if (!afb_context_create(context)) {
144                         afb_context_close(context);
145                         afb_req_fail(req, "failed", "invalid creation state");
146                         return;
147                 }
148         }
149         
150         if ((stag & (AFB_SESSION_CREATE | AFB_SESSION_RENEW)) != 0)
151                 afb_context_refresh(context);
152
153         if ((stag & AFB_SESSION_CLOSE) != 0)
154                 afb_context_close(context);
155
156         trapping_call(req, verb->callback);
157 }
158
159 static void call(struct api_so_desc *desc, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
160 {
161         const struct AFB_restapi *v;
162
163         v = desc->plugin->apis;
164         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
165                 v++;
166         if (v->name)
167                 call_check(req, context, v);
168         else
169                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->plugin->prefix);
170 }
171
172 int afb_api_so_add_plugin(const char *path)
173 {
174         struct api_so_desc *desc;
175         struct AFB_plugin *(*pluginRegisterFct) (const struct AFB_interface *interface);
176
177         desc = calloc(1, sizeof *desc);
178         if (desc == NULL) {
179                 ERROR("out of memory");
180                 goto error;
181         }
182
183         // This is a loadable library let's check if it's a plugin
184         desc->handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
185         if (desc->handle == NULL) {
186                 ERROR("plugin [%s] not loadable", path);
187                 goto error2;
188         }
189
190         /* retrieves the register function */
191         pluginRegisterFct = dlsym(desc->handle, plugin_register_function);
192         if (!pluginRegisterFct) {
193                 ERROR("plugin [%s] is not an AFB plugin", path);
194                 goto error3;
195         }
196         INFO("plugin [%s] is a valid AFB plugin", path);
197
198         /* init the interface */
199         desc->interface.verbosity = 0;
200         desc->interface.mode = AFB_MODE_LOCAL;
201         desc->interface.daemon.itf = &daemon_itf;
202         desc->interface.daemon.closure = desc;
203
204         /* init the plugin */
205         desc->plugin = pluginRegisterFct(&desc->interface);
206         if (desc->plugin == NULL) {
207                 ERROR("plugin [%s] register function failed. continuing...", path);
208                 goto error3;
209         }
210
211         /* check the returned structure */
212         if (desc->plugin->type != AFB_PLUGIN_JSON) {
213                 ERROR("plugin [%s] invalid type %d...", path, desc->plugin->type);
214                 goto error3;
215         }
216         if (desc->plugin->prefix == NULL || *desc->plugin->prefix == 0) {
217                 ERROR("plugin [%s] bad prefix...", path);
218                 goto error3;
219         }
220         if (desc->plugin->info == NULL || *desc->plugin->info == 0) {
221                 ERROR("plugin [%s] bad description...", path);
222                 goto error3;
223         }
224         if (desc->plugin->apis == NULL) {
225                 ERROR("plugin [%s] no APIs...", path);
226                 goto error3;
227         }
228
229         /* records the plugin */
230         desc->apilength = strlen(desc->plugin->prefix);
231         if (afb_apis_add(desc->plugin->prefix, (struct afb_api){
232                         .closure = desc,
233                         .call = (void*)call}) < 0) {
234                 ERROR("plugin [%s] can't be registered...", path);
235                 goto error3;
236         }
237         NOTICE("plugin %s loaded with API prefix %s", path, desc->plugin->prefix);
238         return 0;
239
240 error3:
241         dlclose(desc->handle);
242 error2:
243         free(desc);
244 error:
245         return -1;
246 }
247
248 static int adddirs(char path[PATH_MAX], size_t end)
249 {
250         DIR *dir;
251         struct dirent ent, *result;
252         size_t len;
253
254         /* open the DIR now */
255         dir = opendir(path);
256         if (dir == NULL) {
257                 ERROR("can't scan plugin directory %s, %m", path);
258                 return -1;
259         }
260         INFO("Scanning dir=[%s] for plugins", path);
261
262         /* scan each entry */
263         if (end)
264                 path[end++] = '/';
265         for (;;) {
266                 readdir_r(dir, &ent, &result);
267                 if (result == NULL)
268                         break;
269
270                 len = strlen(ent.d_name);
271                 if (len + end >= PATH_MAX) {
272                         ERROR("path too long while scanning plugins for %s", ent.d_name);
273                         continue;
274                 }
275                 memcpy(&path[end], ent.d_name, len+1);
276                 if (ent.d_type == DT_DIR) {
277                         /* case of directories */
278                         if (ent.d_name[0] == '.') {
279                                 if (len == 1)
280                                         continue;
281                                 if (ent.d_name[1] == '.' && len == 2)
282                                         continue;
283                         }
284                         adddirs(path, end+len);;
285                 } else if (ent.d_type == DT_REG) {
286                         /* case of files */
287                         if (!strstr(ent.d_name, ".so"))
288                                 continue;
289                         afb_api_so_add_plugin(path);
290                 }
291         }
292         closedir(dir);
293         return 0;
294 }
295
296 int afb_api_so_add_directory(const char *path)
297 {
298         size_t length;
299         char buffer[PATH_MAX];
300
301         length = strlen(path);
302         if (length >= sizeof(buffer)) {
303                 ERROR("path too long %lu [%.99s...]", (unsigned long)length, path);
304                 return -1;
305         }
306
307         memcpy(buffer, path, length + 1);
308         return adddirs(buffer, length);
309 }
310
311 int afb_api_so_add_path(const char *path)
312 {
313         struct stat st;
314         int rc;
315
316         rc = stat(path, &st);
317         if (rc < 0)
318                 ERROR("Invalid plugin path [%s]: %m", path);
319         else if (S_ISDIR(st.st_mode))
320                 rc = afb_api_so_add_directory(path);
321         else if (strstr(path, ".so"))
322                 rc = afb_api_so_add_plugin(path);
323         else
324                 INFO("not a plugin [%s], skipped", path);
325         return rc;
326 }
327
328 int afb_api_so_add_pathset(const char *pathset)
329 {
330         static char sep[] = ":";
331         char *ps, *p;
332
333         ps = strdupa(pathset);
334         for (;;) {
335                 p = strsep(&ps, sep);
336                 if (!p)
337                         return 0;
338                 afb_api_so_add_path(p);
339         };
340 }
341