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.
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 #include "afb-api-dbus.h"
44 #include "afb-api-ws.h"
49 #include "afb-session.h"
51 #include "afb-common.h"
52 #include "afb-monitor.h"
54 #include "afb-debug.h"
55 #include "process-name.h"
56 #include "afb-supervision.h"
59 if SELF_PGROUP == 0 the launched command is the group leader
60 if SELF_PGROUP != 0 afb-daemon is the group leader
64 struct afb_apiset *main_apiset;
65 struct afb_config *main_config;
67 static pid_t childpid;
69 /*----------------------------------------------------------
70 | helpers for handling list of arguments
71 +--------------------------------------------------------- */
74 * Calls the callback 'run' for each value of the 'list'
75 * until the callback returns 0 or the end of the list is reached.
76 * Returns either NULL if the end of the list is reached or a pointer
77 * to the item whose value made 'run' return 0.
78 * 'closure' is used for passing user data.
80 static struct afb_config_list *run_for_list(struct afb_config_list *list,
81 int (*run) (void *closure, char *value),
84 while (list && run(closure, list->value))
89 static int run_start(void *closure, char *value)
91 int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
92 return starter(value, main_apiset) >= 0;
95 static void apiset_start_list(struct afb_config_list *list,
96 int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
98 list = run_for_list(list, run_start, starter);
100 ERROR("can't start %s %s", message, list->value);
105 /*----------------------------------------------------------
107 | Handles on exit specific actions
108 +--------------------------------------------------------- */
109 static void exit_handler()
111 struct sigaction siga;
113 memset(&siga, 0, sizeof siga);
114 siga.sa_handler = SIG_IGN;
115 sigaction(SIGTERM, &siga, NULL);
119 else if (childpid > 0)
120 killpg(childpid, SIGTERM);
123 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
125 NOTICE("Received SIGTERM");
129 static void on_sighup(int signum, siginfo_t *info, void *uctx)
131 NOTICE("Received SIGHUP");
135 static void setup_daemon()
137 struct sigaction siga;
139 /* install signal handlers */
140 memset(&siga, 0, sizeof siga);
141 siga.sa_flags = SA_SIGINFO;
143 siga.sa_sigaction = on_sigterm;
144 sigaction(SIGTERM, &siga, NULL);
146 siga.sa_sigaction = on_sighup;
147 sigaction(SIGHUP, &siga, NULL);
150 atexit(exit_handler);
152 /* ignore any SIGPIPE */
153 signal(SIGPIPE, SIG_IGN);
156 /*----------------------------------------------------------
158 | set the process in background
159 +--------------------------------------------------------- */
160 static void daemonize()
165 // open /dev/console to redirect output messAFBes
166 consoleFD = open(main_config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
168 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
171 // fork process when running background mode
174 // if fail nothing much to do
176 ERROR("AFB-daemon Failed to fork son process");
179 // if in father process, just leave
183 // son process get all data in standalone mode
184 NOTICE("background mode [pid:%d console:%s]", getpid(),
185 main_config->console);
187 // redirect default I/O on console
189 dup(consoleFD); // redirect stderr
191 dup(consoleFD); // redirect stdout
192 close(0); // no need for stdin
196 setsid(); // allow father process to fully exit
197 sleep(2); // allow main to leave and release port
201 /*---------------------------------------------------------
203 | Handles the HTTP server
204 +--------------------------------------------------------- */
205 static int init_alias(void *closure, char *spec)
207 struct afb_hsrv *hsrv = closure;
208 char *path = strchr(spec, ':');
211 ERROR("Missing ':' in alias %s. Alias ignored", spec);
215 INFO("Alias for url=%s to path=%s", spec, path);
216 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
220 static int init_http_server(struct afb_hsrv *hsrv)
222 if (!afb_hsrv_add_handler
223 (hsrv, main_config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
226 if (!afb_hsrv_add_handler
227 (hsrv, main_config->rootapi, afb_hswitch_apis, main_apiset, 10))
230 if (run_for_list(main_config->aliases, init_alias, hsrv))
233 if (main_config->roothttp != NULL) {
234 if (!afb_hsrv_add_alias
235 (hsrv, "", afb_common_rootdir_get_fd(), main_config->roothttp,
240 if (!afb_hsrv_add_handler
241 (hsrv, main_config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
248 static struct afb_hsrv *start_http_server()
251 struct afb_hsrv *hsrv;
253 if (afb_hreq_init_download_path(main_config->uploaddir)) {
254 ERROR("unable to set the upload directory %s", main_config->uploaddir);
258 hsrv = afb_hsrv_create();
260 ERROR("memory allocation failure");
264 if (!afb_hsrv_set_cache_timeout(hsrv, main_config->cacheTimeout)
265 || !init_http_server(hsrv)) {
266 ERROR("initialisation of httpd failed");
271 NOTICE("Waiting port=%d rootdir=%s", main_config->httpdPort, main_config->rootdir);
272 NOTICE("Browser URL= http://localhost:%d", main_config->httpdPort);
274 rc = afb_hsrv_start(hsrv, (uint16_t) main_config->httpdPort, 15);
276 ERROR("starting of httpd failed");
284 /*---------------------------------------------------------
286 +--------------------------------------------------------- */
288 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
290 if (info->si_pid == childpid) {
291 switch (info->si_code) {
297 killpg(info->si_pid, SIGKILL);
298 waitpid(info->si_pid, NULL, 0);
310 #define SUBST_CHAR '@'
311 #define SUBST_STR "@"
313 static char *instanciate_string(char *arg, const char *port, const char *token)
315 char *resu, *it, *wr;
318 /* get the changes */
321 it = strchrnul(arg, SUBST_CHAR);
324 case 'p': chg++; dif += (int)strlen(port) - 2; break;
325 case 't': chg++; dif += (int)strlen(token) - 2; break;
326 case SUBST_CHAR: it++; chg++; dif--; break;
329 it = strchrnul(it, SUBST_CHAR);
332 /* return arg when no change */
336 /* allocates the result */
337 resu = malloc((it - arg) + dif + 1);
339 ERROR("out of memory");
343 /* instanciate the arguments */
346 it = strchrnul(arg, SUBST_CHAR);
347 wr = mempcpy(wr, arg, it - arg);
351 case 'p': wr = stpcpy(wr, port); break;
352 case 't': wr = stpcpy(wr, token); break;
353 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
354 case SUBST_CHAR: *wr++ = *it;
363 static int instanciate_environ(const char *port, const char *token)
365 extern char **environ;
369 /* instanciate the environment */
370 for (i = 0 ; environ[i] ; i++) {
371 repl = instanciate_string(environ[i], port, token);
379 static int instanciate_command_args(const char *port, const char *token)
384 /* instanciate the arguments */
385 for (i = 0 ; main_config->exec[i] ; i++) {
386 repl = instanciate_string(main_config->exec[i], port, token);
389 main_config->exec[i] = repl;
394 static int execute_command()
396 struct sigaction siga;
401 /* check whether a command is to execute or not */
402 if (!main_config->exec || !main_config->exec[0])
408 /* install signal handler */
409 memset(&siga, 0, sizeof siga);
410 siga.sa_sigaction = on_sigchld;
411 siga.sa_flags = SA_SIGINFO;
412 sigaction(SIGCHLD, &siga, NULL);
419 /* compute the string for port */
420 if (main_config->httpdPort)
421 rc = snprintf(port, sizeof port, "%d", main_config->httpdPort);
423 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
424 if (rc < 0 || rc >= (int)(sizeof port)) {
425 ERROR("port->txt failed");
428 /* instanciate arguments and environment */
429 token = afb_session_initial_token();
430 if (instanciate_command_args(port, token) >= 0
431 && instanciate_environ(port, token) >= 0) {
435 execv(main_config->exec[0], main_config->exec);
436 ERROR("can't launch %s: %m", main_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.request.api = sreq->api;
508 sreq->xreq.request.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 = main_config->calls;
527 sreq = calloc(1, sizeof *sreq);
528 sreq->session = afb_session_create(3600);
529 sreq->current = list;
530 startup_call_current(sreq);
534 /*---------------------------------------------------------
535 | job for starting the daemon
536 +--------------------------------------------------------- */
538 static void start(int signum, void *arg)
540 struct afb_hsrv *hsrv;
542 afb_debug("start-entry");
545 ERROR("start aborted: received signal %s", strsignal(signum));
549 /* set the directories */
550 mkdir(main_config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
551 if (chdir(main_config->workdir) < 0) {
552 ERROR("Can't enter working dir %s", main_config->workdir);
555 if (afb_common_rootdir_set(main_config->rootdir) < 0) {
556 ERROR("failed to set common root directory");
560 /* configure the daemon */
561 if (afb_session_init(main_config->nbSessionMax, main_config->cntxTimeout, main_config->token)) {
562 ERROR("initialisation of session manager failed");
565 main_apiset = afb_apiset_create("main", main_config->apiTimeout);
567 ERROR("can't create main api set");
570 if (afb_monitor_init() < 0) {
571 ERROR("failed to setup monitor");
574 if (afb_supervision_init() < 0) {
575 ERROR("failed to setup supervision");
580 if (main_config->tracereq)
581 afb_hook_create_xreq(NULL, NULL, NULL, main_config->tracereq, NULL, NULL);
582 if (main_config->traceditf)
583 afb_hook_create_ditf(NULL, main_config->traceditf, NULL, NULL);
584 if (main_config->tracesvc)
585 afb_hook_create_svc(NULL, main_config->tracesvc, NULL, NULL);
586 if (main_config->traceevt)
587 afb_hook_create_evt(NULL, main_config->traceevt, NULL, NULL);
588 if (main_config->traceses)
589 afb_hook_create_session(NULL, main_config->traceses, NULL, NULL);
592 afb_debug("start-load");
593 apiset_start_list(main_config->so_bindings, afb_api_so_add_binding, "the binding");
594 apiset_start_list(main_config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
595 apiset_start_list(main_config->ws_clients, afb_api_ws_add_client_weak, "the afb-websocket client");
596 apiset_start_list(main_config->ldpaths, afb_api_so_add_pathset_fails, "the binding path set");
597 apiset_start_list(main_config->weak_ldpaths, afb_api_so_add_pathset_nofails, "the weak binding path set");
599 apiset_start_list(main_config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
600 apiset_start_list(main_config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
602 DEBUG("Init config done");
604 /* start the services */
605 afb_debug("start-start");
606 #if !defined(NO_CALL_PERSONALITY)
607 personality((unsigned long)-1L);
609 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
612 /* start the HTTP server */
613 afb_debug("start-http");
614 if (!main_config->noHttpd) {
615 if (main_config->httpdPort <= 0) {
616 ERROR("no port is defined");
620 if (!afb_hreq_init_cookie(main_config->httpdPort, main_config->rootapi, main_config->cntxTimeout)) {
621 ERROR("initialisation of HTTP cookies failed");
625 hsrv = start_http_server();
630 /* run the startup calls */
631 afb_debug("start-call");
634 /* run the command */
635 afb_debug("start-exec");
636 if (execute_command() < 0)
640 sd_notify(1, "READY=1");
646 /*---------------------------------------------------------
648 | Parse option and launch action
649 +--------------------------------------------------------- */
651 int main(int argc, char *argv[])
653 afb_debug("main-entry");
655 // let's run this program with a low priority
658 // ------------- Build session handler & init config -------
659 main_config = afb_config_parse_arguments(argc, argv);
660 if (main_config->name) {
661 verbose_set_name(main_config->name, 0);
662 process_name_set_name(main_config->name);
663 process_name_replace_cmdline(argv, main_config->name);
665 afb_debug("main-args");
667 // --------- run -----------
668 if (main_config->background) {
669 // --------- in background mode -----------
670 INFO("entering background mode");
673 // ---- in foreground mode --------------------
674 INFO("entering foreground mode");
676 INFO("running with pid %d", getpid());
678 /* set the daemon environment */
681 afb_debug("main-start");
683 /* enter job processing */
684 jobs_start(3, 0, 50, start, NULL);
685 WARNING("hoops returned from jobs_enter! [report bug]");