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