2 * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3 * Author "Fulup Ar Foll"
4 * Author José Bollo <jose.bollo@iot.bzh>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
20 #define NO_BINDING_VERBOSE_MACRO
30 #include <json-c/json.h>
32 #include <systemd/sd-event.h>
33 #include <systemd/sd-daemon.h>
35 #include <afb/afb-binding.h>
37 #include "afb-config.h"
38 #include "afb-hswitch.h"
39 #include "afb-apiset.h"
40 #include "afb-api-so.h"
41 #include "afb-api-dbus.h"
42 #include "afb-api-ws.h"
44 #include "afb-context.h"
49 #include "afb-session.h"
51 #include "afb-common.h"
56 if SELF_PGROUP == 0 the launched command is the group leader
57 if SELF_PGROUP != 0 afb-daemon is the group leader
61 struct afb_apiset *main_apiset;
63 static struct afb_config *config;
64 static pid_t childpid;
66 /*----------------------------------------------------------
67 | helpers for handling list of arguments
68 +--------------------------------------------------------- */
71 * Calls the callback 'run' for each value of the 'list'
72 * until the callback returns 0 or the end of the list is reached.
73 * Returns either NULL if the end of the list is reached or a pointer
74 * to the item whose value made 'run' return 0.
75 * 'closure' is used for passing user data.
77 static struct afb_config_list *run_for_list(struct afb_config_list *list,
78 int (*run) (void *closure, char *value),
81 while (list && run(closure, list->value))
86 static int run_start(void *closure, char *value)
88 int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
89 return starter(value, main_apiset) >= 0;
92 static void apiset_start_list(struct afb_config_list *list,
93 int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
95 list = run_for_list(list, run_start, starter);
97 ERROR("can't start %s %s", message, list->value);
102 /*----------------------------------------------------------
104 | Handles on exit specific actions
105 +--------------------------------------------------------- */
106 static void exit_handler()
108 struct sigaction siga;
110 memset(&siga, 0, sizeof siga);
111 siga.sa_handler = SIG_IGN;
112 sigaction(SIGTERM, &siga, NULL);
116 else if (childpid > 0)
117 killpg(childpid, SIGTERM);
121 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
123 NOTICE("Received SIGTERM");
127 static void on_sighup(int signum, siginfo_t *info, void *uctx)
129 NOTICE("Received SIGHUP");
133 static void setup_daemon()
135 struct sigaction siga;
137 /* install signal handlers */
138 memset(&siga, 0, sizeof siga);
139 siga.sa_flags = SA_SIGINFO;
141 siga.sa_sigaction = on_sigterm;
142 sigaction(SIGTERM, &siga, NULL);
144 siga.sa_sigaction = on_sighup;
145 sigaction(SIGHUP, &siga, NULL);
148 atexit(exit_handler);
150 /* ignore any SIGPIPE */
151 signal(SIGPIPE, SIG_IGN);
154 /*----------------------------------------------------------
156 | set the process in background
157 +--------------------------------------------------------- */
158 static void daemonize()
163 // open /dev/console to redirect output messAFBes
164 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
166 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
169 // fork process when running background mode
172 // if fail nothing much to do
174 ERROR("AFB-daemon Failed to fork son process");
177 // if in father process, just leave
181 // son process get all data in standalone mode
182 NOTICE("background mode [pid:%d console:%s]", getpid(),
185 // redirect default I/O on console
187 dup(consoleFD); // redirect stderr
189 dup(consoleFD); // redirect stdout
190 close(0); // no need for stdin
194 setsid(); // allow father process to fully exit
195 sleep(2); // allow main to leave and release port
199 /*---------------------------------------------------------
201 | Handles the HTTP server
202 +--------------------------------------------------------- */
203 static int init_alias(void *closure, char *spec)
205 struct afb_hsrv *hsrv = closure;
206 char *path = strchr(spec, ':');
209 ERROR("Missing ':' in alias %s. Alias ignored", spec);
213 INFO("Alias for url=%s to path=%s", spec, path);
214 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
218 static int init_http_server(struct afb_hsrv *hsrv)
220 if (!afb_hsrv_add_handler
221 (hsrv, config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
224 if (!afb_hsrv_add_handler
225 (hsrv, config->rootapi, afb_hswitch_apis, main_apiset, 10))
228 if (run_for_list(config->aliases, init_alias, hsrv))
231 if (config->roothttp != NULL) {
232 if (!afb_hsrv_add_alias
233 (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
238 if (!afb_hsrv_add_handler
239 (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
246 static struct afb_hsrv *start_http_server()
249 struct afb_hsrv *hsrv;
251 if (afb_hreq_init_download_path(config->uploaddir)) {
252 ERROR("unable to set the upload directory %s", config->uploaddir);
256 hsrv = afb_hsrv_create();
258 ERROR("memory allocation failure");
262 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
263 || !init_http_server(hsrv)) {
264 ERROR("initialisation of httpd failed");
269 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
270 NOTICE("Browser URL= http://localhost:%d", config->httpdPort);
272 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
274 ERROR("starting of httpd failed");
282 /*---------------------------------------------------------
285 +--------------------------------------------------------- */
287 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
289 if (info->si_pid == childpid) {
290 switch (info->si_code) {
296 killpg(info->si_pid, SIGKILL);
297 waitpid(info->si_pid, NULL, 0);
309 #define SUBST_CHAR '@'
310 #define SUBST_STR "@"
312 static char *instanciate_string(char *arg, const char *port, const char *token)
314 char *resu, *it, *wr;
317 /* get the changes */
320 it = strchrnul(arg, SUBST_CHAR);
323 case 'p': chg++; dif += (int)strlen(port) - 2; break;
324 case 't': chg++; dif += (int)strlen(token) - 2; break;
325 case SUBST_CHAR: it++; chg++; dif--; break;
328 it = strchrnul(it, SUBST_CHAR);
331 /* return arg when no change */
335 /* allocates the result */
336 resu = malloc((it - arg) + dif + 1);
338 ERROR("out of memory");
342 /* instanciate the arguments */
345 it = strchrnul(arg, SUBST_CHAR);
346 wr = mempcpy(wr, arg, it - arg);
350 case 'p': wr = stpcpy(wr, port); break;
351 case 't': wr = stpcpy(wr, token); break;
352 default: *wr++ = SUBST_CHAR;
353 case SUBST_CHAR: *wr++ = *it;
362 static int instanciate_environ(const char *port, const char *token)
364 extern char **environ;
368 /* instanciate the environment */
369 for (i = 0 ; environ[i] ; i++) {
370 repl = instanciate_string(environ[i], port, token);
378 static int instanciate_command_args(const char *port, const char *token)
383 /* instanciate the arguments */
384 for (i = 0 ; config->exec[i] ; i++) {
385 repl = instanciate_string(config->exec[i], port, token);
388 config->exec[i] = repl;
393 static int execute_command()
395 struct sigaction siga;
399 /* check whether a command is to execute or not */
400 if (!config->exec || !config->exec[0])
406 /* install signal handler */
407 memset(&siga, 0, sizeof siga);
408 siga.sa_sigaction = on_sigchld;
409 siga.sa_flags = SA_SIGINFO;
410 sigaction(SIGCHLD, &siga, NULL);
417 /* compute the string for port */
418 if (config->httpdPort)
419 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
421 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
422 if (rc < 0 || rc >= (int)(sizeof port)) {
423 ERROR("port->txt failed");
426 /* instanciate arguments and environment */
427 if (instanciate_command_args(port, config->token) >= 0
428 && instanciate_environ(port, config->token) >= 0) {
432 execv(config->exec[0], config->exec);
433 ERROR("can't launch %s: %m", config->exec[0]);
440 /*---------------------------------------------------------
442 +--------------------------------------------------------- */
446 struct afb_xreq xreq;
449 struct afb_config_list *current;
450 struct afb_session *session;
453 static void startup_call_reply(struct afb_xreq *xreq, int iserror, struct json_object *obj)
455 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
458 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
460 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
465 static void startup_call_current(struct startup_req *sreq);
467 static void startup_call_unref(struct afb_xreq *xreq)
469 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
473 json_object_put(sreq->xreq.json);
474 afb_cred_unref(sreq->xreq.cred);
475 sreq->current = sreq->current->next;
477 startup_call_current(sreq);
479 afb_session_close(sreq->session);
480 afb_session_unref(sreq->session);
485 static struct afb_xreq_query_itf startup_xreq_itf =
487 .reply = startup_call_reply,
488 .unref = startup_call_unref
491 static void startup_call_current(struct startup_req *sreq)
493 char *api, *verb, *json;
495 api = sreq->current->value;
496 verb = strchr(api, '/');
498 json = strchr(verb, ':');
500 memset(&sreq->xreq, 0, sizeof sreq->xreq);
501 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
502 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
503 sreq->xreq.context.validated = 1;
504 sreq->xreq.cred = afb_cred_current();
505 sreq->api = strndup(api, verb - api);
506 sreq->verb = strndup(verb + 1, json - verb - 1);
507 sreq->xreq.api = sreq->api;
508 sreq->xreq.verb = sreq->verb;
509 sreq->xreq.json = json_tokener_parse(json + 1);
510 if (sreq->api && sreq->verb && sreq->xreq.json) {
511 afb_xreq_process(&sreq->xreq, main_apiset);
516 ERROR("Bad call specification %s", sreq->current->value);
520 static void run_startup_calls()
522 struct afb_config_list *list;
523 struct startup_req *sreq;
525 list = config->calls;
527 sreq = calloc(1, sizeof *sreq);
528 sreq->session = afb_session_create("startup", 3600);
529 sreq->current = list;
530 startup_call_current(sreq);
534 /*---------------------------------------------------------
535 | job for starting the daemon
536 +--------------------------------------------------------- */
540 struct afb_hsrv *hsrv;
542 // ------------------ sanity check ----------------------------------------
543 if (config->httpdPort <= 0) {
544 ERROR("no port is defined");
548 /* set the directories */
549 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
550 if (chdir(config->workdir) < 0) {
551 ERROR("Can't enter working dir %s", config->workdir);
554 if (afb_common_rootdir_set(config->rootdir) < 0) {
555 ERROR("failed to set common root directory");
559 /* configure the daemon */
560 main_apiset = afb_apiset_create("main", config->apiTimeout, NULL);
562 ERROR("can't create main api set");
565 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
566 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
567 ERROR("initialisation of cookies failed");
572 if (config->tracereq)
573 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
574 if (config->traceditf)
575 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
578 apiset_start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
579 apiset_start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
580 apiset_start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
581 apiset_start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
583 apiset_start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
584 apiset_start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
586 DEBUG("Init config done");
588 /* start the services */
589 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
592 /* start the HTTP server */
593 if (!config->noHttpd) {
594 hsrv = start_http_server();
599 /* run the command */
600 if (execute_command() < 0)
604 sd_notify(1, "READY=1");
606 /* run the startup calls */
613 /*---------------------------------------------------------
615 | Parse option and launch action
616 +--------------------------------------------------------- */
618 int main(int argc, char *argv[])
620 // let's run this program with a low priority
625 // ------------- Build session handler & init config -------
626 config = afb_config_parse_arguments(argc, argv);
627 INFO("running with pid %d", getpid());
629 // --------- run -----------
630 if (config->background) {
631 // --------- in background mode -----------
632 INFO("entering background mode");
635 // ---- in foreground mode --------------------
636 INFO("entering foreground mode");
639 /* set the daemon environment */
642 /* enter job processing */
643 jobs_start(3, 0, 50, start);
644 WARNING("hoops returned from jobs_enter! [report bug]");