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"
55 #include "afb-debug.h"
56 #include "process-name.h"
57 #include "afb-supervision.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;
66 struct afb_config *main_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(main_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(),
186 main_config->console);
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, main_config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
227 if (!afb_hsrv_add_handler
228 (hsrv, main_config->rootapi, afb_hswitch_apis, main_apiset, 10))
231 if (run_for_list(main_config->aliases, init_alias, hsrv))
234 if (main_config->roothttp != NULL) {
235 if (!afb_hsrv_add_alias
236 (hsrv, "", afb_common_rootdir_get_fd(), main_config->roothttp,
241 if (!afb_hsrv_add_handler
242 (hsrv, main_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(main_config->uploaddir)) {
255 ERROR("unable to set the upload directory %s", main_config->uploaddir);
259 hsrv = afb_hsrv_create();
261 ERROR("memory allocation failure");
265 if (!afb_hsrv_set_cache_timeout(hsrv, main_config->cacheTimeout)
266 || !init_http_server(hsrv)) {
267 ERROR("initialisation of httpd failed");
272 NOTICE("Waiting port=%d rootdir=%s", main_config->httpdPort, main_config->rootdir);
273 NOTICE("Browser URL= http://localhost:%d", main_config->httpdPort);
275 rc = afb_hsrv_start(hsrv, (uint16_t) main_config->httpdPort, 15);
277 ERROR("starting of httpd failed");
285 /*---------------------------------------------------------
287 +--------------------------------------------------------- */
289 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
291 if (info->si_pid == childpid) {
292 switch (info->si_code) {
298 killpg(info->si_pid, SIGKILL);
299 waitpid(info->si_pid, NULL, 0);
311 #define SUBST_CHAR '@'
312 #define SUBST_STR "@"
314 static char *instanciate_string(char *arg, const char *port, const char *token)
316 char *resu, *it, *wr;
319 /* get the changes */
322 it = strchrnul(arg, SUBST_CHAR);
325 case 'p': chg++; dif += (int)strlen(port) - 2; break;
326 case 't': chg++; dif += (int)strlen(token) - 2; break;
327 case SUBST_CHAR: it++; chg++; dif--; break;
330 it = strchrnul(it, SUBST_CHAR);
333 /* return arg when no change */
337 /* allocates the result */
338 resu = malloc((it - arg) + dif + 1);
340 ERROR("out of memory");
344 /* instanciate the arguments */
347 it = strchrnul(arg, SUBST_CHAR);
348 wr = mempcpy(wr, arg, it - arg);
352 case 'p': wr = stpcpy(wr, port); break;
353 case 't': wr = stpcpy(wr, token); break;
354 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
355 case SUBST_CHAR: *wr++ = *it;
364 static int instanciate_environ(const char *port, const char *token)
366 extern char **environ;
370 /* instanciate the environment */
371 for (i = 0 ; environ[i] ; i++) {
372 repl = instanciate_string(environ[i], port, token);
380 static int instanciate_command_args(const char *port, const char *token)
385 /* instanciate the arguments */
386 for (i = 0 ; main_config->exec[i] ; i++) {
387 repl = instanciate_string(main_config->exec[i], port, token);
390 main_config->exec[i] = repl;
395 static int execute_command()
397 struct sigaction siga;
402 /* check whether a command is to execute or not */
403 if (!main_config->exec || !main_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 (main_config->httpdPort)
422 rc = snprintf(port, sizeof port, "%d", main_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 token = afb_session_initial_token();
431 if (instanciate_command_args(port, token) >= 0
432 && instanciate_environ(port, token) >= 0) {
436 execv(main_config->exec[0], main_config->exec);
437 ERROR("can't launch %s: %m", main_config->exec[0]);
444 /*---------------------------------------------------------
446 +--------------------------------------------------------- */
450 struct afb_xreq xreq;
453 struct afb_config_list *current;
454 struct afb_session *session;
457 static void startup_call_reply(struct afb_xreq *xreq, int status, struct json_object *obj)
459 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
462 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
464 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
469 static void startup_call_current(struct startup_req *sreq);
471 static void startup_call_unref(struct afb_xreq *xreq)
473 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
477 json_object_put(sreq->xreq.json);
478 sreq->current = sreq->current->next;
480 startup_call_current(sreq);
482 afb_session_close(sreq->session);
483 afb_session_unref(sreq->session);
488 static struct afb_xreq_query_itf startup_xreq_itf =
490 .reply = startup_call_reply,
491 .unref = startup_call_unref
494 static void startup_call_current(struct startup_req *sreq)
496 char *api, *verb, *json;
498 api = sreq->current->value;
499 verb = strchr(api, '/');
501 json = strchr(verb, ':');
503 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
504 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
505 sreq->xreq.context.validated = 1;
506 sreq->api = strndup(api, verb - api);
507 sreq->verb = strndup(verb + 1, json - verb - 1);
508 sreq->xreq.request.api = sreq->api;
509 sreq->xreq.request.verb = sreq->verb;
510 sreq->xreq.json = json_tokener_parse(json + 1);
511 if (sreq->api && sreq->verb && sreq->xreq.json) {
512 afb_xreq_process(&sreq->xreq, main_apiset);
517 ERROR("Bad call specification %s", sreq->current->value);
521 static void run_startup_calls()
523 struct afb_config_list *list;
524 struct startup_req *sreq;
526 list = main_config->calls;
528 sreq = calloc(1, sizeof *sreq);
529 sreq->session = afb_session_create(3600);
530 sreq->current = list;
531 startup_call_current(sreq);
535 /*---------------------------------------------------------
536 | job for starting the daemon
537 +--------------------------------------------------------- */
539 static void start(int signum, void *arg)
541 struct afb_hsrv *hsrv;
543 afb_debug("start-entry");
546 ERROR("start aborted: received signal %s", strsignal(signum));
550 /* set the directories */
551 mkdir(main_config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
552 if (chdir(main_config->workdir) < 0) {
553 ERROR("Can't enter working dir %s", main_config->workdir);
556 if (afb_common_rootdir_set(main_config->rootdir) < 0) {
557 ERROR("failed to set common root directory");
561 /* configure the daemon */
562 if (afb_session_init(main_config->nbSessionMax, main_config->cntxTimeout, main_config->token)) {
563 ERROR("initialisation of session manager failed");
566 main_apiset = afb_apiset_create("main", main_config->apiTimeout);
568 ERROR("can't create main api set");
571 if (afb_monitor_init() < 0) {
572 ERROR("failed to setup monitor");
575 if (afb_supervision_init() < 0) {
576 ERROR("failed to setup supervision");
581 if (main_config->tracereq)
582 afb_hook_create_xreq(NULL, NULL, NULL, main_config->tracereq, NULL, NULL);
583 if (main_config->traceditf)
584 afb_hook_create_ditf(NULL, main_config->traceditf, NULL, NULL);
585 if (main_config->tracesvc)
586 afb_hook_create_svc(NULL, main_config->tracesvc, NULL, NULL);
587 if (main_config->traceevt)
588 afb_hook_create_evt(NULL, main_config->traceevt, NULL, NULL);
591 afb_debug("start-load");
592 apiset_start_list(main_config->so_bindings, afb_api_so_add_binding, "the binding");
593 apiset_start_list(main_config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
594 apiset_start_list(main_config->ws_clients, afb_api_ws_add_client_weak, "the afb-websocket client");
595 apiset_start_list(main_config->ldpaths, afb_api_so_add_pathset_fails, "the binding path set");
596 apiset_start_list(main_config->weak_ldpaths, afb_api_so_add_pathset_nofails, "the weak binding path set");
598 apiset_start_list(main_config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
599 apiset_start_list(main_config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
601 DEBUG("Init config done");
603 /* start the services */
604 afb_debug("start-start");
605 #if !defined(NO_CALL_PERSONALITY)
606 personality((unsigned long)-1L);
608 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
611 /* start the HTTP server */
612 afb_debug("start-http");
613 if (!main_config->noHttpd) {
614 if (main_config->httpdPort <= 0) {
615 ERROR("no port is defined");
619 if (!afb_hreq_init_cookie(main_config->httpdPort, main_config->rootapi, main_config->cntxTimeout)) {
620 ERROR("initialisation of HTTP cookies failed");
624 hsrv = start_http_server();
629 /* run the startup calls */
630 afb_debug("start-call");
633 /* run the command */
634 afb_debug("start-exec");
635 if (execute_command() < 0)
639 sd_notify(1, "READY=1");
645 /*---------------------------------------------------------
647 | Parse option and launch action
648 +--------------------------------------------------------- */
650 int main(int argc, char *argv[])
652 afb_debug("main-entry");
654 // let's run this program with a low priority
659 // ------------- Build session handler & init config -------
660 main_config = afb_config_parse_arguments(argc, argv);
661 if (main_config->name) {
662 verbose_set_name(main_config->name, 0);
663 process_name_set_name(main_config->name);
664 process_name_replace_cmdline(argv, main_config->name);
666 afb_debug("main-args");
668 // --------- run -----------
669 if (main_config->background) {
670 // --------- in background mode -----------
671 INFO("entering background mode");
674 // ---- in foreground mode --------------------
675 INFO("entering foreground mode");
677 INFO("running with pid %d", getpid());
679 /* set the daemon environment */
682 afb_debug("main-start");
684 /* enter job processing */
685 jobs_start(3, 0, 50, start, NULL);
686 WARNING("hoops returned from jobs_enter! [report bug]");