Service instanciation
[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-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 "afb-evt.h"
42 #include "afb-svc.h"
43 #include "verbose.h"
44
45 /*
46  * Description of a plugin
47  */
48 struct api_so_desc {
49         struct AFB_plugin *plugin;      /* descriptor */
50         size_t apilength;               /* length of the API name */
51         void *handle;                   /* context of dlopen */
52         struct afb_svc *service;        /* handler for service started */
53         struct AFB_interface interface; /* interface for the plugin */
54 };
55
56 static int api_timeout = 15;
57
58 static const char plugin_register_function_v1[] = "pluginAfbV1Register";
59 static const char plugin_service_init_function_v1[] = "pluginAfbV1ServiceInit";
60 static const char plugin_service_event_function_v1[] = "pluginAfbV1ServiceEvent";
61
62 void afb_api_so_set_timeout(int to)
63 {
64         api_timeout = to;
65 }
66
67 static struct afb_event afb_api_so_event_make(struct api_so_desc *desc, const char *name)
68 {
69         size_t length;
70         char *event;
71
72         /* makes the event name */
73         assert(desc->plugin != NULL);
74         length = strlen(name);
75         event = alloca(length + 2 + desc->apilength);
76         memcpy(event, desc->plugin->v1.prefix, desc->apilength);
77         event[desc->apilength] = '/';
78         memcpy(event + desc->apilength + 1, name, length + 1);
79
80         /* crate the event */
81         return afb_evt_create_event(event);
82 }
83
84 static int afb_api_so_event_broadcast(struct api_so_desc *desc, const char *name, struct json_object *object)
85 {
86         size_t length;
87         char *event;
88
89         /* makes the event name */
90         assert(desc->plugin != NULL);
91         length = strlen(name);
92         event = alloca(length + 2 + desc->apilength);
93         memcpy(event, desc->plugin->v1.prefix, desc->apilength);
94         event[desc->apilength] = '/';
95         memcpy(event + desc->apilength + 1, name, length + 1);
96
97         return afb_evt_broadcast(event, object);
98 }
99
100 static void afb_api_so_vverbose(struct api_so_desc *desc, int level, const char *file, int line, const char *fmt, va_list args)
101 {
102         char *p;
103
104         if (vasprintf(&p, fmt, args) < 0)
105                 vverbose(level, file, line, fmt, args);
106         else {
107                 verbose(level, file, line, "%s {plugin %s}", p, desc->plugin->v1.prefix);
108                 free(p);
109         }
110 }
111
112 static const struct afb_daemon_itf daemon_itf = {
113         .event_broadcast = (void*)afb_api_so_event_broadcast,
114         .get_event_loop = (void*)afb_common_get_event_loop,
115         .get_user_bus = (void*)afb_common_get_user_bus,
116         .get_system_bus = (void*)afb_common_get_system_bus,
117         .vverbose = (void*)afb_api_so_vverbose,
118         .event_make = (void*)afb_api_so_event_make
119 };
120
121 struct monitoring {
122         struct afb_req req;
123         void (*action)(struct afb_req);
124 };
125
126 static void monitored_call(int signum, struct monitoring *data)
127 {
128         if (signum != 0)
129                 afb_req_fail_f(data->req, "aborted", "signal %s(%d) caught", strsignal(signum), signum);
130         else
131                 data->action(data->req);
132 }
133
134 static void call_check(struct afb_req req, struct afb_context *context, const struct AFB_verb_desc_v1 *verb)
135 {
136         struct monitoring data;
137
138         int stag = (int)verb->session;
139
140         if ((stag & (AFB_SESSION_CREATE|AFB_SESSION_CLOSE|AFB_SESSION_RENEW|AFB_SESSION_CHECK|AFB_SESSION_LOA_EQ)) != 0) {
141                 if (!afb_context_check(context)) {
142                         afb_context_close(context);
143                         afb_req_fail(req, "failed", "invalid token's identity");
144                         return;
145                 }       
146         }
147
148         if ((stag & AFB_SESSION_CREATE) != 0) {
149                 if (afb_context_check_loa(context, 1)) {
150                         afb_req_fail(req, "failed", "invalid creation state");
151                         return;
152                 }
153                 afb_context_change_loa(context, 1);
154                 afb_context_refresh(context);
155         }
156         
157         if ((stag & (AFB_SESSION_CREATE | AFB_SESSION_RENEW)) != 0)
158                 afb_context_refresh(context);
159
160         if ((stag & AFB_SESSION_CLOSE) != 0) {
161                 afb_context_change_loa(context, 0);
162                 afb_context_close(context);
163         }
164
165         if ((stag & AFB_SESSION_LOA_GE) != 0) {
166                 int loa = (stag >> AFB_SESSION_LOA_SHIFT) & AFB_SESSION_LOA_MASK;
167                 if (!afb_context_check_loa(context, loa)) {
168                         afb_req_fail(req, "failed", "invalid LOA");
169                         return;
170                 }
171         }
172
173         if ((stag & AFB_SESSION_LOA_LE) != 0) {
174                 int loa = (stag >> AFB_SESSION_LOA_SHIFT) & AFB_SESSION_LOA_MASK;
175                 if (afb_context_check_loa(context, loa + 1)) {
176                         afb_req_fail(req, "failed", "invalid LOA");
177                         return;
178                 }
179         }
180
181         data.req = req;
182         data.action = verb->callback;
183         afb_sig_monitor((void*)monitored_call, &data, api_timeout);
184 }
185
186 static void call(struct api_so_desc *desc, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
187 {
188         const struct AFB_verb_desc_v1 *v;
189
190         v = desc->plugin->v1.verbs;
191         while (v->name && (strncasecmp(v->name, verb, lenverb) || v->name[lenverb]))
192                 v++;
193         if (v->name)
194                 call_check(req, context, v);
195         else
196                 afb_req_fail_f(req, "unknown-verb", "verb %.*s unknown within api %s", (int)lenverb, verb, desc->plugin->v1.prefix);
197 }
198
199 static int service_start(struct api_so_desc *desc, int share_session, int onneed)
200 {
201         int (*init)(struct afb_service service);
202         void (*onevent)(const char *event, struct json_object *object);
203
204         /* check state */
205         if (desc->service != NULL) {
206                 /* not an error when onneed */
207                 if (onneed != 0)
208                         return 0;
209
210                 /* already started: it is an error */
211                 ERROR("Service %s already started", desc->plugin->v1.prefix);
212                 return -1;
213         }
214
215         /* get the initialisation */
216         init = dlsym(desc->handle, plugin_service_init_function_v1);
217         if (init == NULL) {
218                 /* not an error when onneed */
219                 if (onneed != 0)
220                         return 0;
221
222                 /* no initialisation method */
223                 ERROR("Binding %s is not a service", desc->plugin->v1.prefix);
224                 return -1;
225         }
226
227         /* get the event handler if any */
228         onevent = dlsym(desc->handle, plugin_service_event_function_v1);
229         desc->service = afb_svc_create(share_session, init, onevent);
230         if (desc->service == NULL) {
231                 /* starting error */
232                 ERROR("Starting service %s failed", desc->plugin->v1.prefix);
233                 return -1;
234         }
235
236         return 0;
237 }
238
239 int afb_api_so_add_plugin(const char *path)
240 {
241         int rc;
242         void *handle;
243         struct api_so_desc *desc;
244         struct AFB_plugin *(*pluginAfbV1RegisterFct) (const struct AFB_interface *interface);
245
246         // This is a loadable library let's check if it's a plugin
247         rc = 0;
248         handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
249         if (handle == NULL) {
250                 ERROR("plugin [%s] not loadable", path);
251                 goto error;
252         }
253
254         /* retrieves the register function */
255         pluginAfbV1RegisterFct = dlsym(handle, plugin_register_function_v1);
256         if (!pluginAfbV1RegisterFct) {
257                 ERROR("plugin [%s] is not an AFB plugin", path);
258                 goto error2;
259         }
260         INFO("plugin [%s] is a valid AFB plugin", path);
261         rc = -1;
262
263         /* allocates the description */
264         desc = calloc(1, sizeof *desc);
265         if (desc == NULL) {
266                 ERROR("out of memory");
267                 goto error2;
268         }
269         desc->handle = handle;
270
271         /* init the interface */
272         desc->interface.verbosity = verbosity;
273         desc->interface.mode = AFB_MODE_LOCAL;
274         desc->interface.daemon.itf = &daemon_itf;
275         desc->interface.daemon.closure = desc;
276
277         /* init the plugin */
278         NOTICE("plugin [%s] calling registering function %s", path, plugin_register_function_v1);
279         desc->plugin = pluginAfbV1RegisterFct(&desc->interface);
280         if (desc->plugin == NULL) {
281                 ERROR("plugin [%s] register function failed. continuing...", path);
282                 goto error3;
283         }
284
285         /* check the returned structure */
286         if (desc->plugin->type != AFB_PLUGIN_VERSION_1) {
287                 ERROR("plugin [%s] invalid type %d...", path, desc->plugin->type);
288                 goto error3;
289         }
290         if (desc->plugin->v1.prefix == NULL || *desc->plugin->v1.prefix == 0) {
291                 ERROR("plugin [%s] bad prefix...", path);
292                 goto error3;
293         }
294         if (!afb_apis_is_valid_api_name(desc->plugin->v1.prefix)) {
295                 ERROR("plugin [%s] invalid prefix...", path);
296                 goto error3;
297         }
298         if (desc->plugin->v1.info == NULL || *desc->plugin->v1.info == 0) {
299                 ERROR("plugin [%s] bad description...", path);
300                 goto error3;
301         }
302         if (desc->plugin->v1.verbs == NULL) {
303                 ERROR("plugin [%s] no APIs...", path);
304                 goto error3;
305         }
306
307         /* records the plugin */
308         desc->apilength = strlen(desc->plugin->v1.prefix);
309         if (afb_apis_add(desc->plugin->v1.prefix, (struct afb_api){
310                         .closure = desc,
311                         .call = (void*)call,
312                         .service_start = (void*)service_start }) < 0) {
313                 ERROR("plugin [%s] can't be registered...", path);
314                 goto error3;
315         }
316         NOTICE("plugin %s loaded with API prefix %s", path, desc->plugin->v1.prefix);
317         return 0;
318
319 error3:
320         free(desc);
321 error2:
322         dlclose(handle);
323 error:
324         return rc;
325 }
326
327 static int adddirs(char path[PATH_MAX], size_t end)
328 {
329         DIR *dir;
330         struct dirent ent, *result;
331         size_t len;
332
333         /* open the DIR now */
334         dir = opendir(path);
335         if (dir == NULL) {
336                 ERROR("can't scan plugin directory %s, %m", path);
337                 return -1;
338         }
339         INFO("Scanning dir=[%s] for plugins", path);
340
341         /* scan each entry */
342         if (end)
343                 path[end++] = '/';
344         for (;;) {
345                 readdir_r(dir, &ent, &result);
346                 if (result == NULL)
347                         break;
348
349                 len = strlen(ent.d_name);
350                 if (len + end >= PATH_MAX) {
351                         ERROR("path too long while scanning plugins for %s", ent.d_name);
352                         continue;
353                 }
354                 memcpy(&path[end], ent.d_name, len+1);
355                 if (ent.d_type == DT_DIR) {
356                         /* case of directories */
357                         if (ent.d_name[0] == '.') {
358                                 if (len == 1)
359                                         continue;
360                                 if (ent.d_name[1] == '.' && len == 2)
361                                         continue;
362                         }
363                         adddirs(path, end+len);;
364                 } else if (ent.d_type == DT_REG) {
365                         /* case of files */
366                         if (!strstr(ent.d_name, ".so"))
367                                 continue;
368                         if (afb_api_so_add_plugin(path) < 0)
369                                 return -1;
370                 }
371         }
372         closedir(dir);
373         return 0;
374 }
375
376 int afb_api_so_add_directory(const char *path)
377 {
378         size_t length;
379         char buffer[PATH_MAX];
380
381         length = strlen(path);
382         if (length >= sizeof(buffer)) {
383                 ERROR("path too long %lu [%.99s...]", (unsigned long)length, path);
384                 return -1;
385         }
386
387         memcpy(buffer, path, length + 1);
388         return adddirs(buffer, length);
389 }
390
391 int afb_api_so_add_path(const char *path)
392 {
393         struct stat st;
394         int rc;
395
396         rc = stat(path, &st);
397         if (rc < 0)
398                 ERROR("Invalid plugin path [%s]: %m", path);
399         else if (S_ISDIR(st.st_mode))
400                 rc = afb_api_so_add_directory(path);
401         else if (strstr(path, ".so"))
402                 rc = afb_api_so_add_plugin(path);
403         else
404                 INFO("not a plugin [%s], skipped", path);
405         return rc;
406 }
407
408 int afb_api_so_add_pathset(const char *pathset)
409 {
410         static char sep[] = ":";
411         char *ps, *p;
412
413         ps = strdupa(pathset);
414         for (;;) {
415                 p = strsep(&ps, sep);
416                 if (!p)
417                         return 0;
418                 if (afb_api_so_add_path(p) < 0)
419                         return -1;
420         }
421 }
422