indicates the call to initialisation function
[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         NOTICE("plugin [%s] calling registering function %s", path, plugin_register_function_v1);
218         desc->plugin = pluginAfbV1RegisterFct(&desc->interface);
219         if (desc->plugin == NULL) {
220                 ERROR("plugin [%s] register function failed. continuing...", path);
221                 goto error3;
222         }
223
224         /* check the returned structure */
225         if (desc->plugin->type != AFB_PLUGIN_VERSION_1) {
226                 ERROR("plugin [%s] invalid type %d...", path, desc->plugin->type);
227                 goto error3;
228         }
229         if (desc->plugin->v1.prefix == NULL || *desc->plugin->v1.prefix == 0) {
230                 ERROR("plugin [%s] bad prefix...", path);
231                 goto error3;
232         }
233         if (!afb_apis_is_valid_api_name(desc->plugin->v1.prefix)) {
234                 ERROR("plugin [%s] invalid prefix...", path);
235                 goto error3;
236         }
237         if (desc->plugin->v1.info == NULL || *desc->plugin->v1.info == 0) {
238                 ERROR("plugin [%s] bad description...", path);
239                 goto error3;
240         }
241         if (desc->plugin->v1.verbs == NULL) {
242                 ERROR("plugin [%s] no APIs...", path);
243                 goto error3;
244         }
245
246         /* records the plugin */
247         desc->apilength = strlen(desc->plugin->v1.prefix);
248         if (afb_apis_add(desc->plugin->v1.prefix, (struct afb_api){
249                         .closure = desc,
250                         .call = (void*)call}) < 0) {
251                 ERROR("plugin [%s] can't be registered...", path);
252                 goto error3;
253         }
254         NOTICE("plugin %s loaded with API prefix %s", path, desc->plugin->v1.prefix);
255         return 0;
256
257 error3:
258         free(desc);
259 error2:
260         dlclose(handle);
261 error:
262         return rc;
263 }
264
265 static int adddirs(char path[PATH_MAX], size_t end)
266 {
267         DIR *dir;
268         struct dirent ent, *result;
269         size_t len;
270
271         /* open the DIR now */
272         dir = opendir(path);
273         if (dir == NULL) {
274                 ERROR("can't scan plugin directory %s, %m", path);
275                 return -1;
276         }
277         INFO("Scanning dir=[%s] for plugins", path);
278
279         /* scan each entry */
280         if (end)
281                 path[end++] = '/';
282         for (;;) {
283                 readdir_r(dir, &ent, &result);
284                 if (result == NULL)
285                         break;
286
287                 len = strlen(ent.d_name);
288                 if (len + end >= PATH_MAX) {
289                         ERROR("path too long while scanning plugins for %s", ent.d_name);
290                         continue;
291                 }
292                 memcpy(&path[end], ent.d_name, len+1);
293                 if (ent.d_type == DT_DIR) {
294                         /* case of directories */
295                         if (ent.d_name[0] == '.') {
296                                 if (len == 1)
297                                         continue;
298                                 if (ent.d_name[1] == '.' && len == 2)
299                                         continue;
300                         }
301                         adddirs(path, end+len);;
302                 } else if (ent.d_type == DT_REG) {
303                         /* case of files */
304                         if (!strstr(ent.d_name, ".so"))
305                                 continue;
306                         if (afb_api_so_add_plugin(path) < 0)
307                                 return -1;
308                 }
309         }
310         closedir(dir);
311         return 0;
312 }
313
314 int afb_api_so_add_directory(const char *path)
315 {
316         size_t length;
317         char buffer[PATH_MAX];
318
319         length = strlen(path);
320         if (length >= sizeof(buffer)) {
321                 ERROR("path too long %lu [%.99s...]", (unsigned long)length, path);
322                 return -1;
323         }
324
325         memcpy(buffer, path, length + 1);
326         return adddirs(buffer, length);
327 }
328
329 int afb_api_so_add_path(const char *path)
330 {
331         struct stat st;
332         int rc;
333
334         rc = stat(path, &st);
335         if (rc < 0)
336                 ERROR("Invalid plugin path [%s]: %m", path);
337         else if (S_ISDIR(st.st_mode))
338                 rc = afb_api_so_add_directory(path);
339         else if (strstr(path, ".so"))
340                 rc = afb_api_so_add_plugin(path);
341         else
342                 INFO("not a plugin [%s], skipped", path);
343         return rc;
344 }
345
346 int afb_api_so_add_pathset(const char *pathset)
347 {
348         static char sep[] = ":";
349         char *ps, *p;
350
351         ps = strdupa(pathset);
352         for (;;) {
353                 p = strsep(&ps, sep);
354                 if (!p)
355                         return 0;
356                 if (afb_api_so_add_path(p) < 0)
357                         return -1;
358         }
359 }
360