add log macros for plugins
[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 #define NO_PLUGIN_VERBOSE_MACRO
20
21 #include <stdio.h>
22 #include <assert.h>
23 #include <string.h>
24 #include <dirent.h>
25 #include <dlfcn.h>
26 #include <unistd.h>
27 #include <limits.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30
31 #include <afb/afb-plugin.h>
32 #include <afb/afb-req-itf.h>
33 #include <afb/afb-event-sender-itf.h>
34
35 #include "session.h"
36 #include "afb-common.h"
37 #include "afb-context.h"
38 #include "afb-apis.h"
39 #include "afb-api-so.h"
40 #include "afb-sig-handler.h"
41 #include "verbose.h"
42
43 /*
44  * Description of a plugin
45  */
46 struct api_so_desc {
47         struct AFB_plugin *plugin;      /* descriptor */
48         size_t apilength;               /* length of the API name */
49         void *handle;                   /* context of dlopen */
50         struct AFB_interface interface; /* interface for the plugin */
51 };
52
53 static int api_timeout = 15;
54
55 static const char plugin_register_function_v1[] = "pluginAfbV1Register";
56
57 static void afb_api_so_event_sender_push(struct api_so_desc *desc, const char *name, struct json_object *object)
58 {
59         size_t length;
60         char *event;
61
62         assert(desc->plugin != NULL);
63         length = strlen(name);
64         event = alloca(length + 2 + desc->apilength);
65         memcpy(event, desc->plugin->v1.prefix, desc->apilength);
66         event[desc->apilength] = '/';
67         memcpy(event + desc->apilength + 1, name, length + 1);
68         ctxClientEventSend(NULL, event, object);
69 }
70
71 static const struct afb_event_sender_itf event_sender_itf = {
72         .push = (void*)afb_api_so_event_sender_push
73 };
74
75 static struct afb_event_sender afb_api_so_get_event_sender(struct api_so_desc *desc)
76 {
77         return (struct afb_event_sender){ .itf = &event_sender_itf, .closure = desc };
78 }
79
80 static void afb_api_so_vverbose(struct api_so_desc *desc, int level, const char *file, int line, const char *fmt, va_list args)
81 {
82         char *p;
83
84         if (vasprintf(&p, fmt, args) < 0)
85                 vverbose(level, file, line, fmt, args);
86         else {
87                 verbose(level, file, line, "%s {plugin %s}", p, desc->plugin->v1.prefix);
88                 free(p);
89         }
90 }
91
92 static const struct afb_daemon_itf daemon_itf = {
93         .get_event_sender = (void*)afb_api_so_get_event_sender,
94         .get_event_loop = (void*)afb_common_get_event_loop,
95         .get_user_bus = (void*)afb_common_get_user_bus,
96         .get_system_bus = (void*)afb_common_get_system_bus,
97         .vverbose = (void*)afb_api_so_vverbose
98 };
99
100 struct monitoring {
101         struct afb_req req;
102         void (*action)(struct afb_req);
103 };
104
105 static void monitored_call(int signum, struct monitoring *data)
106 {
107         if (signum != 0)
108                 afb_req_fail_f(data->req, "aborted", "signal %s(%d) caught", strsignal(signum), signum);
109         else
110                 data->action(data->req);
111 }
112
113 static void call_check(struct afb_req req, struct afb_context *context, const struct AFB_verb_desc_v1 *verb)
114 {
115         struct monitoring data;
116
117         int stag = (int)verb->session;
118
119         if ((stag & (AFB_SESSION_CREATE|AFB_SESSION_CLOSE|AFB_SESSION_RENEW|AFB_SESSION_CHECK|AFB_SESSION_LOA_EQ)) != 0) {
120                 if (!afb_context_check(context)) {
121                         afb_context_close(context);
122                         afb_req_fail(req, "failed", "invalid token's identity");
123                         return;
124                 }       
125         }
126
127         if ((stag & AFB_SESSION_CREATE) != 0) {
128                 if (afb_context_check_loa(context, 1)) {
129                         afb_req_fail(req, "failed", "invalid creation state");
130                         return;
131                 }
132                 afb_context_change_loa(context, 1);
133                 afb_context_refresh(context);
134         }
135         
136         if ((stag & (AFB_SESSION_CREATE | AFB_SESSION_RENEW)) != 0)
137                 afb_context_refresh(context);
138
139         if ((stag & AFB_SESSION_CLOSE) != 0) {
140                 afb_context_change_loa(context, 0);
141                 afb_context_close(context);
142         }
143
144         if ((stag & AFB_SESSION_LOA_GE) != 0) {
145                 int loa = (stag >> AFB_SESSION_LOA_SHIFT) & AFB_SESSION_LOA_MASK;
146                 if (!afb_context_check_loa(context, loa)) {
147                         afb_req_fail(req, "failed", "invalid LOA");
148                         return;
149                 }
150         }
151
152         if ((stag & AFB_SESSION_LOA_LE) != 0) {
153                 int loa = (stag >> AFB_SESSION_LOA_SHIFT) & AFB_SESSION_LOA_MASK;
154                 if (afb_context_check_loa(context, loa + 1)) {
155                         afb_req_fail(req, "failed", "invalid LOA");
156                         return;
157                 }
158         }
159
160         data.req = req;
161         data.action = verb->callback;
162         afb_sig_monitor((void*)monitored_call, &data, api_timeout);
163 }
164
165 static void call(struct api_so_desc *desc, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
166 {
167         const struct AFB_verb_desc_v1 *v;
168
169         v = desc->plugin->v1.verbs;
170         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
171                 v++;
172         if (v->name)
173                 call_check(req, context, v);
174         else
175                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->plugin->v1.prefix);
176 }
177
178 int afb_api_so_add_plugin(const char *path)
179 {
180         int rc;
181         void *handle;
182         struct api_so_desc *desc;
183         struct AFB_plugin *(*pluginAfbV1RegisterFct) (const struct AFB_interface *interface);
184
185         // This is a loadable library let's check if it's a plugin
186         rc = 0;
187         handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
188         if (handle == NULL) {
189                 ERROR("plugin [%s] not loadable", path);
190                 goto error;
191         }
192
193         /* retrieves the register function */
194         pluginAfbV1RegisterFct = dlsym(handle, plugin_register_function_v1);
195         if (!pluginAfbV1RegisterFct) {
196                 ERROR("plugin [%s] is not an AFB plugin", path);
197                 goto error2;
198         }
199         INFO("plugin [%s] is a valid AFB plugin", path);
200         rc = -1;
201
202         /* allocates the description */
203         desc = calloc(1, sizeof *desc);
204         if (desc == NULL) {
205                 ERROR("out of memory");
206                 goto error2;
207         }
208         desc->handle = handle;
209
210         /* init the interface */
211         desc->interface.verbosity = verbosity;
212         desc->interface.mode = AFB_MODE_LOCAL;
213         desc->interface.daemon.itf = &daemon_itf;
214         desc->interface.daemon.closure = desc;
215
216         /* init the plugin */
217         desc->plugin = pluginAfbV1RegisterFct(&desc->interface);
218         if (desc->plugin == NULL) {
219                 ERROR("plugin [%s] register function failed. continuing...", path);
220                 goto error3;
221         }
222
223         /* check the returned structure */
224         if (desc->plugin->type != AFB_PLUGIN_VERSION_1) {
225                 ERROR("plugin [%s] invalid type %d...", path, desc->plugin->type);
226                 goto error3;
227         }
228         if (desc->plugin->v1.prefix == NULL || *desc->plugin->v1.prefix == 0) {
229                 ERROR("plugin [%s] bad prefix...", path);
230                 goto error3;
231         }
232         if (!afb_apis_is_valid_api_name(desc->plugin->v1.prefix)) {
233                 ERROR("plugin [%s] invalid prefix...", path);
234                 goto error3;
235         }
236         if (desc->plugin->v1.info == NULL || *desc->plugin->v1.info == 0) {
237                 ERROR("plugin [%s] bad description...", path);
238                 goto error3;
239         }
240         if (desc->plugin->v1.verbs == NULL) {
241                 ERROR("plugin [%s] no APIs...", path);
242                 goto error3;
243         }
244
245         /* records the plugin */
246         desc->apilength = strlen(desc->plugin->v1.prefix);
247         if (afb_apis_add(desc->plugin->v1.prefix, (struct afb_api){
248                         .closure = desc,
249                         .call = (void*)call}) < 0) {
250                 ERROR("plugin [%s] can't be registered...", path);
251                 goto error3;
252         }
253         NOTICE("plugin %s loaded with API prefix %s", path, desc->plugin->v1.prefix);
254         return 0;
255
256 error3:
257         free(desc);
258 error2:
259         dlclose(handle);
260 error:
261         return rc;
262 }
263
264 static int adddirs(char path[PATH_MAX], size_t end)
265 {
266         DIR *dir;
267         struct dirent ent, *result;
268         size_t len;
269
270         /* open the DIR now */
271         dir = opendir(path);
272         if (dir == NULL) {
273                 ERROR("can't scan plugin directory %s, %m", path);
274                 return -1;
275         }
276         INFO("Scanning dir=[%s] for plugins", path);
277
278         /* scan each entry */
279         if (end)
280                 path[end++] = '/';
281         for (;;) {
282                 readdir_r(dir, &ent, &result);
283                 if (result == NULL)
284                         break;
285
286                 len = strlen(ent.d_name);
287                 if (len + end >= PATH_MAX) {
288                         ERROR("path too long while scanning plugins for %s", ent.d_name);
289                         continue;
290                 }
291                 memcpy(&path[end], ent.d_name, len+1);
292                 if (ent.d_type == DT_DIR) {
293                         /* case of directories */
294                         if (ent.d_name[0] == '.') {
295                                 if (len == 1)
296                                         continue;
297                                 if (ent.d_name[1] == '.' && len == 2)
298                                         continue;
299                         }
300                         adddirs(path, end+len);;
301                 } else if (ent.d_type == DT_REG) {
302                         /* case of files */
303                         if (!strstr(ent.d_name, ".so"))
304                                 continue;
305                         if (afb_api_so_add_plugin(path) < 0)
306                                 return -1;
307                 }
308         }
309         closedir(dir);
310         return 0;
311 }
312
313 int afb_api_so_add_directory(const char *path)
314 {
315         size_t length;
316         char buffer[PATH_MAX];
317
318         length = strlen(path);
319         if (length >= sizeof(buffer)) {
320                 ERROR("path too long %lu [%.99s...]", (unsigned long)length, path);
321                 return -1;
322         }
323
324         memcpy(buffer, path, length + 1);
325         return adddirs(buffer, length);
326 }
327
328 int afb_api_so_add_path(const char *path)
329 {
330         struct stat st;
331         int rc;
332
333         rc = stat(path, &st);
334         if (rc < 0)
335                 ERROR("Invalid plugin path [%s]: %m", path);
336         else if (S_ISDIR(st.st_mode))
337                 rc = afb_api_so_add_directory(path);
338         else if (strstr(path, ".so"))
339                 rc = afb_api_so_add_plugin(path);
340         else
341                 INFO("not a plugin [%s], skipped", path);
342         return rc;
343 }
344
345 int afb_api_so_add_pathset(const char *pathset)
346 {
347         static char sep[] = ":";
348         char *ps, *p;
349
350         ps = strdupa(pathset);
351         for (;;) {
352                 p = strsep(&ps, sep);
353                 if (!p)
354                         return 0;
355                 if (afb_api_so_add_path(p) < 0)
356                         return -1;
357         }
358 }
359