2 * Copyright (C) 2015-2018 "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.
31 #if !defined(NO_CALL_PERSONALITY)
32 #include <sys/personality.h>
35 #include <json-c/json.h>
37 #include <systemd/sd-daemon.h>
39 #include "afb-config.h"
40 #include "afb-hswitch.h"
41 #include "afb-apiset.h"
42 #include "afb-api-so.h"
43 #if defined(WITH_DBUS_TRANSPARENCY)
44 # include "afb-api-dbus.h"
46 #include "afb-api-ws.h"
51 #include "afb-session.h"
53 #include "afb-common.h"
54 #include "afb-monitor.h"
56 #include "afb-debug.h"
57 #include "process-name.h"
58 #include "afb-supervision.h"
61 if SELF_PGROUP == 0 the launched command is the group leader
62 if SELF_PGROUP != 0 afb-daemon is the group leader
66 struct afb_apiset *main_apiset;
67 struct afb_config *main_config;
69 static pid_t childpid;
71 /*----------------------------------------------------------
72 | helpers for handling list of arguments
73 +--------------------------------------------------------- */
76 * Calls the callback 'run' for each value of the 'list'
77 * until the callback returns 0 or the end of the list is reached.
78 * Returns either NULL if the end of the list is reached or a pointer
79 * to the item whose value made 'run' return 0.
80 * 'closure' is used for passing user data.
82 static struct afb_config_list *run_for_list(struct afb_config_list *list,
83 int (*run) (void *closure, char *value),
86 while (list && run(closure, list->value))
91 static int run_start(void *closure, char *value)
93 int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
94 return starter(value, main_apiset) >= 0;
97 static void apiset_start_list(struct afb_config_list *list,
98 int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
100 list = run_for_list(list, run_start, starter);
102 ERROR("can't start %s %s", message, list->value);
107 /*----------------------------------------------------------
109 | Handles on exit specific actions
110 +--------------------------------------------------------- */
111 static void exit_handler()
113 struct sigaction siga;
115 memset(&siga, 0, sizeof siga);
116 siga.sa_handler = SIG_IGN;
117 sigaction(SIGTERM, &siga, NULL);
121 else if (childpid > 0)
122 killpg(childpid, SIGTERM);
125 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
127 NOTICE("Received SIGTERM");
131 static void on_sighup(int signum, siginfo_t *info, void *uctx)
133 NOTICE("Received SIGHUP");
137 static void setup_daemon()
139 struct sigaction siga;
141 /* install signal handlers */
142 memset(&siga, 0, sizeof siga);
143 siga.sa_flags = SA_SIGINFO;
145 siga.sa_sigaction = on_sigterm;
146 sigaction(SIGTERM, &siga, NULL);
148 siga.sa_sigaction = on_sighup;
149 sigaction(SIGHUP, &siga, NULL);
152 atexit(exit_handler);
154 /* ignore any SIGPIPE */
155 signal(SIGPIPE, SIG_IGN);
158 /*----------------------------------------------------------
160 | set the process in background
161 +--------------------------------------------------------- */
162 static void daemonize()
167 // open /dev/console to redirect output messAFBes
168 consoleFD = open(main_config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
170 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
173 // fork process when running background mode
176 // if fail nothing much to do
178 ERROR("AFB-daemon Failed to fork son process");
181 // if in father process, just leave
185 // son process get all data in standalone mode
186 NOTICE("background mode [pid:%d console:%s]", getpid(),
187 main_config->console);
189 // redirect default I/O on console
191 dup(consoleFD); // redirect stderr
193 dup(consoleFD); // redirect stdout
194 close(0); // no need for stdin
198 setsid(); // allow father process to fully exit
199 sleep(2); // allow main to leave and release port
203 /*---------------------------------------------------------
205 | Handles the HTTP server
206 +--------------------------------------------------------- */
207 static int init_alias(void *closure, char *spec)
209 struct afb_hsrv *hsrv = closure;
210 char *path = strchr(spec, ':');
213 ERROR("Missing ':' in alias %s. Alias ignored", spec);
217 INFO("Alias for url=%s to path=%s", spec, path);
218 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
222 static int init_http_server(struct afb_hsrv *hsrv)
224 if (!afb_hsrv_add_handler
225 (hsrv, main_config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
228 if (!afb_hsrv_add_handler
229 (hsrv, main_config->rootapi, afb_hswitch_apis, main_apiset, 10))
232 if (run_for_list(main_config->aliases, init_alias, hsrv))
235 if (main_config->roothttp != NULL) {
236 if (!afb_hsrv_add_alias
237 (hsrv, "", afb_common_rootdir_get_fd(), main_config->roothttp,
242 if (!afb_hsrv_add_handler
243 (hsrv, main_config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
250 static struct afb_hsrv *start_http_server()
253 struct afb_hsrv *hsrv;
255 if (afb_hreq_init_download_path(main_config->uploaddir)) {
256 ERROR("unable to set the upload directory %s", main_config->uploaddir);
260 hsrv = afb_hsrv_create();
262 ERROR("memory allocation failure");
266 if (!afb_hsrv_set_cache_timeout(hsrv, main_config->cacheTimeout)
267 || !init_http_server(hsrv)) {
268 ERROR("initialisation of httpd failed");
273 NOTICE("Waiting port=%d rootdir=%s", main_config->httpdPort, main_config->rootdir);
274 NOTICE("Browser URL= http://localhost:%d", main_config->httpdPort);
276 rc = afb_hsrv_start(hsrv, (uint16_t) main_config->httpdPort, 15);
278 ERROR("starting of httpd failed");
286 /*---------------------------------------------------------
288 +--------------------------------------------------------- */
290 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
292 if (info->si_pid == childpid) {
293 switch (info->si_code) {
299 killpg(info->si_pid, SIGKILL);
300 waitpid(info->si_pid, NULL, 0);
312 #define SUBST_CHAR '@'
313 #define SUBST_STR "@"
315 static char *instanciate_string(char *arg, const char *port, const char *token)
317 char *resu, *it, *wr;
320 /* get the changes */
323 it = strchrnul(arg, SUBST_CHAR);
326 case 'p': chg++; dif += (int)strlen(port) - 2; break;
327 case 't': chg++; dif += (int)strlen(token) - 2; break;
328 case SUBST_CHAR: it++; chg++; dif--; break;
331 it = strchrnul(it, SUBST_CHAR);
334 /* return arg when no change */
338 /* allocates the result */
339 resu = malloc((it - arg) + dif + 1);
341 ERROR("out of memory");
345 /* instanciate the arguments */
348 it = strchrnul(arg, SUBST_CHAR);
349 wr = mempcpy(wr, arg, it - arg);
353 case 'p': wr = stpcpy(wr, port); break;
354 case 't': wr = stpcpy(wr, token); break;
355 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
356 case SUBST_CHAR: *wr++ = *it;
365 static int instanciate_environ(const char *port, const char *token)
367 extern char **environ;
371 /* instanciate the environment */
372 for (i = 0 ; environ[i] ; i++) {
373 repl = instanciate_string(environ[i], port, token);
381 static int instanciate_command_args(const char *port, const char *token)
386 /* instanciate the arguments */
387 for (i = 0 ; main_config->exec[i] ; i++) {
388 repl = instanciate_string(main_config->exec[i], port, token);
391 main_config->exec[i] = repl;
396 static int execute_command()
398 struct sigaction siga;
403 /* check whether a command is to execute or not */
404 if (!main_config->exec || !main_config->exec[0])
410 /* install signal handler */
411 memset(&siga, 0, sizeof siga);
412 siga.sa_sigaction = on_sigchld;
413 siga.sa_flags = SA_SIGINFO;
414 sigaction(SIGCHLD, &siga, NULL);
421 /* compute the string for port */
422 if (main_config->httpdPort)
423 rc = snprintf(port, sizeof port, "%d", main_config->httpdPort);
425 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
426 if (rc < 0 || rc >= (int)(sizeof port)) {
427 ERROR("port->txt failed");
430 /* instanciate arguments and environment */
431 token = afb_session_initial_token();
432 if (instanciate_command_args(port, token) >= 0
433 && instanciate_environ(port, token) >= 0) {
437 execv(main_config->exec[0], main_config->exec);
438 ERROR("can't launch %s: %m", main_config->exec[0]);
445 /*---------------------------------------------------------
447 +--------------------------------------------------------- */
451 struct afb_xreq xreq;
454 struct afb_config_list *current;
455 struct afb_session *session;
458 static void startup_call_reply(struct afb_xreq *xreq, int status, struct json_object *obj)
460 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
463 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
465 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
470 static void startup_call_current(struct startup_req *sreq);
472 static void startup_call_unref(struct afb_xreq *xreq)
474 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
478 json_object_put(sreq->xreq.json);
479 sreq->current = sreq->current->next;
481 startup_call_current(sreq);
483 afb_session_close(sreq->session);
484 afb_session_unref(sreq->session);
489 static struct afb_xreq_query_itf startup_xreq_itf =
491 .reply = startup_call_reply,
492 .unref = startup_call_unref
495 static void startup_call_current(struct startup_req *sreq)
497 char *api, *verb, *json;
499 api = sreq->current->value;
500 verb = strchr(api, '/');
502 json = strchr(verb, ':');
504 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
505 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
506 sreq->xreq.context.validated = 1;
507 sreq->api = strndup(api, verb - api);
508 sreq->verb = strndup(verb + 1, json - verb - 1);
509 sreq->xreq.request.api = sreq->api;
510 sreq->xreq.request.verb = sreq->verb;
511 sreq->xreq.json = json_tokener_parse(json + 1);
512 if (sreq->api && sreq->verb && sreq->xreq.json) {
513 afb_xreq_process(&sreq->xreq, main_apiset);
518 ERROR("Bad call specification %s", sreq->current->value);
522 static void run_startup_calls()
524 struct afb_config_list *list;
525 struct startup_req *sreq;
527 list = main_config->calls;
529 sreq = calloc(1, sizeof *sreq);
530 sreq->session = afb_session_create(3600);
531 sreq->current = list;
532 startup_call_current(sreq);
536 /*---------------------------------------------------------
537 | job for starting the daemon
538 +--------------------------------------------------------- */
540 static void start(int signum, void *arg)
542 struct afb_hsrv *hsrv;
544 afb_debug("start-entry");
547 ERROR("start aborted: received signal %s", strsignal(signum));
551 /* set the directories */
552 mkdir(main_config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
553 if (chdir(main_config->workdir) < 0) {
554 ERROR("Can't enter working dir %s", main_config->workdir);
557 if (afb_common_rootdir_set(main_config->rootdir) < 0) {
558 ERROR("failed to set common root directory");
562 /* configure the daemon */
563 if (afb_session_init(main_config->nbSessionMax, main_config->cntxTimeout, main_config->token)) {
564 ERROR("initialisation of session manager failed");
567 main_apiset = afb_apiset_create("main", main_config->apiTimeout);
569 ERROR("can't create main api set");
572 if (afb_monitor_init() < 0) {
573 ERROR("failed to setup monitor");
576 if (afb_supervision_init() < 0) {
577 ERROR("failed to setup supervision");
582 if (main_config->tracereq)
583 afb_hook_create_xreq(NULL, NULL, NULL, main_config->tracereq, NULL, NULL);
584 if (main_config->traceditf)
585 afb_hook_create_ditf(NULL, main_config->traceditf, NULL, NULL);
586 if (main_config->tracesvc)
587 afb_hook_create_svc(NULL, main_config->tracesvc, NULL, NULL);
588 if (main_config->traceevt)
589 afb_hook_create_evt(NULL, main_config->traceevt, NULL, NULL);
590 if (main_config->traceses)
591 afb_hook_create_session(NULL, main_config->traceses, NULL, NULL);
594 afb_debug("start-load");
595 apiset_start_list(main_config->so_bindings, afb_api_so_add_binding, "the binding");
596 #if defined(WITH_DBUS_TRANSPARENCY)
597 apiset_start_list(main_config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
599 apiset_start_list(main_config->ws_clients, afb_api_ws_add_client_weak, "the afb-websocket client");
600 apiset_start_list(main_config->ldpaths, afb_api_so_add_pathset_fails, "the binding path set");
601 apiset_start_list(main_config->weak_ldpaths, afb_api_so_add_pathset_nofails, "the weak binding path set");
603 #if defined(WITH_DBUS_TRANSPARENCY)
604 apiset_start_list(main_config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
606 apiset_start_list(main_config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
608 DEBUG("Init config done");
610 /* start the services */
611 afb_debug("start-start");
612 #if !defined(NO_CALL_PERSONALITY)
613 personality((unsigned long)-1L);
615 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
618 /* start the HTTP server */
619 afb_debug("start-http");
620 if (!main_config->noHttpd) {
621 if (main_config->httpdPort <= 0) {
622 ERROR("no port is defined");
626 if (!afb_hreq_init_cookie(main_config->httpdPort, main_config->rootapi, main_config->cntxTimeout)) {
627 ERROR("initialisation of HTTP cookies failed");
631 hsrv = start_http_server();
636 /* run the startup calls */
637 afb_debug("start-call");
640 /* run the command */
641 afb_debug("start-exec");
642 if (execute_command() < 0)
646 sd_notify(1, "READY=1");
652 /*---------------------------------------------------------
654 | Parse option and launch action
655 +--------------------------------------------------------- */
657 int main(int argc, char *argv[])
659 afb_debug("main-entry");
661 // let's run this program with a low priority
664 // ------------- Build session handler & init config -------
665 main_config = afb_config_parse_arguments(argc, argv);
666 if (main_config->name) {
667 verbose_set_name(main_config->name, 0);
668 process_name_set_name(main_config->name);
669 process_name_replace_cmdline(argv, main_config->name);
671 afb_debug("main-args");
673 // --------- run -----------
674 if (main_config->background) {
675 // --------- in background mode -----------
676 INFO("entering background mode");
679 // ---- in foreground mode --------------------
680 INFO("entering foreground mode");
682 INFO("running with pid %d", getpid());
684 /* set the daemon environment */
687 afb_debug("main-start");
689 /* enter job processing */
690 jobs_start(3, 0, 50, start, NULL);
691 WARNING("hoops returned from jobs_enter! [report bug]");