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 AFB_BINDING_PRAGMA_NO_VERBOSE_MACRO
32 #if !defined(NO_CALL_PERSONALITY)
33 #include <sys/personality.h>
36 #include <json-c/json.h>
38 #include <systemd/sd-daemon.h>
40 #include "afb-config.h"
41 #include "afb-hswitch.h"
42 #include "afb-apiset.h"
43 #include "afb-api-so.h"
44 #include "afb-api-dbus.h"
45 #include "afb-api-ws.h"
50 #include "afb-session.h"
52 #include "afb-common.h"
53 #include "afb-monitor.h"
56 #include "afb-debug.h"
57 #include "process-name.h"
60 if SELF_PGROUP == 0 the launched command is the group leader
61 if SELF_PGROUP != 0 afb-daemon is the group leader
65 struct afb_apiset *main_apiset;
67 static struct afb_config *config;
68 static pid_t childpid;
70 /*----------------------------------------------------------
71 | helpers for handling list of arguments
72 +--------------------------------------------------------- */
75 * Calls the callback 'run' for each value of the 'list'
76 * until the callback returns 0 or the end of the list is reached.
77 * Returns either NULL if the end of the list is reached or a pointer
78 * to the item whose value made 'run' return 0.
79 * 'closure' is used for passing user data.
81 static struct afb_config_list *run_for_list(struct afb_config_list *list,
82 int (*run) (void *closure, char *value),
85 while (list && run(closure, list->value))
90 static int run_start(void *closure, char *value)
92 int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
93 return starter(value, main_apiset) >= 0;
96 static void apiset_start_list(struct afb_config_list *list,
97 int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
99 list = run_for_list(list, run_start, starter);
101 ERROR("can't start %s %s", message, list->value);
106 /*----------------------------------------------------------
108 | Handles on exit specific actions
109 +--------------------------------------------------------- */
110 static void exit_handler()
112 struct sigaction siga;
114 memset(&siga, 0, sizeof siga);
115 siga.sa_handler = SIG_IGN;
116 sigaction(SIGTERM, &siga, NULL);
120 else if (childpid > 0)
121 killpg(childpid, SIGTERM);
124 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
126 NOTICE("Received SIGTERM");
130 static void on_sighup(int signum, siginfo_t *info, void *uctx)
132 NOTICE("Received SIGHUP");
136 static void setup_daemon()
138 struct sigaction siga;
140 /* install signal handlers */
141 memset(&siga, 0, sizeof siga);
142 siga.sa_flags = SA_SIGINFO;
144 siga.sa_sigaction = on_sigterm;
145 sigaction(SIGTERM, &siga, NULL);
147 siga.sa_sigaction = on_sighup;
148 sigaction(SIGHUP, &siga, NULL);
151 atexit(exit_handler);
153 /* ignore any SIGPIPE */
154 signal(SIGPIPE, SIG_IGN);
157 /*----------------------------------------------------------
159 | set the process in background
160 +--------------------------------------------------------- */
161 static void daemonize()
166 // open /dev/console to redirect output messAFBes
167 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
169 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
172 // fork process when running background mode
175 // if fail nothing much to do
177 ERROR("AFB-daemon Failed to fork son process");
180 // if in father process, just leave
184 // son process get all data in standalone mode
185 NOTICE("background mode [pid:%d console:%s]", getpid(),
188 // redirect default I/O on console
190 dup(consoleFD); // redirect stderr
192 dup(consoleFD); // redirect stdout
193 close(0); // no need for stdin
197 setsid(); // allow father process to fully exit
198 sleep(2); // allow main to leave and release port
202 /*---------------------------------------------------------
204 | Handles the HTTP server
205 +--------------------------------------------------------- */
206 static int init_alias(void *closure, char *spec)
208 struct afb_hsrv *hsrv = closure;
209 char *path = strchr(spec, ':');
212 ERROR("Missing ':' in alias %s. Alias ignored", spec);
216 INFO("Alias for url=%s to path=%s", spec, path);
217 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
221 static int init_http_server(struct afb_hsrv *hsrv)
223 if (!afb_hsrv_add_handler
224 (hsrv, config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
227 if (!afb_hsrv_add_handler
228 (hsrv, config->rootapi, afb_hswitch_apis, main_apiset, 10))
231 if (run_for_list(config->aliases, init_alias, hsrv))
234 if (config->roothttp != NULL) {
235 if (!afb_hsrv_add_alias
236 (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
241 if (!afb_hsrv_add_handler
242 (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
249 static struct afb_hsrv *start_http_server()
252 struct afb_hsrv *hsrv;
254 if (afb_hreq_init_download_path(config->uploaddir)) {
255 ERROR("unable to set the upload directory %s", config->uploaddir);
259 hsrv = afb_hsrv_create();
261 ERROR("memory allocation failure");
265 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
266 || !init_http_server(hsrv)) {
267 ERROR("initialisation of httpd failed");
272 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
273 NOTICE("Browser URL= http://localhost:%d", config->httpdPort);
275 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
277 ERROR("starting of httpd failed");
285 /*---------------------------------------------------------
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 ; config->exec[i] ; i++) {
388 repl = instanciate_string(config->exec[i], port, token);
391 config->exec[i] = repl;
396 static int execute_command()
398 struct sigaction siga;
402 /* check whether a command is to execute or not */
403 if (!config->exec || !config->exec[0])
409 /* install signal handler */
410 memset(&siga, 0, sizeof siga);
411 siga.sa_sigaction = on_sigchld;
412 siga.sa_flags = SA_SIGINFO;
413 sigaction(SIGCHLD, &siga, NULL);
420 /* compute the string for port */
421 if (config->httpdPort)
422 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
424 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
425 if (rc < 0 || rc >= (int)(sizeof port)) {
426 ERROR("port->txt failed");
429 /* instanciate arguments and environment */
430 if (instanciate_command_args(port, config->token) >= 0
431 && instanciate_environ(port, config->token) >= 0) {
435 execv(config->exec[0], config->exec);
436 ERROR("can't launch %s: %m", config->exec[0]);
443 /*---------------------------------------------------------
445 +--------------------------------------------------------- */
449 struct afb_xreq xreq;
452 struct afb_config_list *current;
453 struct afb_session *session;
456 static void startup_call_reply(struct afb_xreq *xreq, int status, struct json_object *obj)
458 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
461 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
463 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
468 static void startup_call_current(struct startup_req *sreq);
470 static void startup_call_unref(struct afb_xreq *xreq)
472 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
476 json_object_put(sreq->xreq.json);
477 sreq->current = sreq->current->next;
479 startup_call_current(sreq);
481 afb_session_close(sreq->session);
482 afb_session_unref(sreq->session);
487 static struct afb_xreq_query_itf startup_xreq_itf =
489 .reply = startup_call_reply,
490 .unref = startup_call_unref
493 static void startup_call_current(struct startup_req *sreq)
495 char *api, *verb, *json;
497 api = sreq->current->value;
498 verb = strchr(api, '/');
500 json = strchr(verb, ':');
502 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
503 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
504 sreq->xreq.context.validated = 1;
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 +--------------------------------------------------------- */
538 static void start(int signum)
540 struct afb_hsrv *hsrv;
542 afb_debug("start-entry");
545 ERROR("start aborted: received signal %s", strsignal(signum));
549 // ------------------ sanity check ----------------------------------------
550 if (config->httpdPort <= 0) {
551 ERROR("no port is defined");
555 /* set the directories */
556 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
557 if (chdir(config->workdir) < 0) {
558 ERROR("Can't enter working dir %s", config->workdir);
561 if (afb_common_rootdir_set(config->rootdir) < 0) {
562 ERROR("failed to set common root directory");
566 /* configure the daemon */
567 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
568 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
569 ERROR("initialisation of cookies failed");
572 main_apiset = afb_apiset_create("main", config->apiTimeout);
574 ERROR("can't create main api set");
577 if (afb_monitor_init() < 0) {
578 ERROR("failed to setup monitor");
583 if (config->tracereq)
584 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
585 if (config->traceditf)
586 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
587 if (config->tracesvc)
588 afb_hook_create_svc(NULL, config->tracesvc, NULL, NULL);
589 if (config->traceevt)
590 afb_hook_create_evt(NULL, config->traceevt, NULL, NULL);
593 afb_debug("start-load");
594 apiset_start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
595 apiset_start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
596 apiset_start_list(config->ldpaths, afb_api_so_add_pathset_fails, "the binding path set");
597 apiset_start_list(config->weak_ldpaths, afb_api_so_add_pathset_nofails, "the weak binding path set");
598 apiset_start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
600 apiset_start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
601 apiset_start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
603 DEBUG("Init config done");
605 /* start the services */
606 afb_debug("start-start");
607 #if !defined(NO_CALL_PERSONALITY)
608 personality((unsigned long)-1L);
610 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
613 /* start the HTTP server */
614 afb_debug("start-http");
615 if (!config->noHttpd) {
616 hsrv = start_http_server();
621 /* run the startup calls */
622 afb_debug("start-call");
625 /* run the command */
626 afb_debug("start-exec");
627 if (execute_command() < 0)
631 sd_notify(1, "READY=1");
637 /*---------------------------------------------------------
639 | Parse option and launch action
640 +--------------------------------------------------------- */
642 int main(int argc, char *argv[])
644 afb_debug("main-entry");
646 // let's run this program with a low priority
651 // ------------- Build session handler & init config -------
652 config = afb_config_parse_arguments(argc, argv);
654 verbose_set_name(config->name, 0);
655 process_name_set_name(config->name);
656 process_name_replace_cmdline(argv, config->name);
658 afb_debug("main-args");
660 // --------- run -----------
661 if (config->background) {
662 // --------- in background mode -----------
663 INFO("entering background mode");
666 // ---- in foreground mode --------------------
667 INFO("entering foreground mode");
669 INFO("running with pid %d", getpid());
671 /* set the daemon environment */
674 afb_debug("main-start");
676 /* enter job processing */
677 jobs_start(3, 0, 50, start);
678 WARNING("hoops returned from jobs_enter! [report bug]");