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-autoset.h"
43 #include "afb-api-so.h"
44 #if defined(WITH_DBUS_TRANSPARENCY)
45 # include "afb-api-dbus.h"
47 #include "afb-api-ws.h"
52 #include "afb-session.h"
54 #include "afb-common.h"
55 #include "afb-monitor.h"
57 #include "afb-debug.h"
58 #include "process-name.h"
59 #include "afb-supervision.h"
62 if SELF_PGROUP == 0 the launched command is the group leader
63 if SELF_PGROUP != 0 afb-daemon is the group leader
67 struct afb_apiset *main_apiset;
68 struct afb_config *main_config;
70 static pid_t childpid;
72 /*----------------------------------------------------------
73 | helpers for handling list of arguments
74 +--------------------------------------------------------- */
77 * Calls the callback 'run' for each value of the 'list'
78 * until the callback returns 0 or the end of the list is reached.
79 * Returns either NULL if the end of the list is reached or a pointer
80 * to the item whose value made 'run' return 0.
81 * 'closure' is used for passing user data.
83 static struct afb_config_list *run_for_list(struct afb_config_list *list,
84 int (*run) (void *closure, char *value),
87 while (list && run(closure, list->value))
92 static int run_start(void *closure, char *value)
94 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set) = closure;
95 return starter(value, main_apiset, main_apiset) >= 0;
98 static void apiset_start_list(struct afb_config_list *list,
99 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set),
102 list = run_for_list(list, run_start, starter);
104 ERROR("can't start %s %s", message, list->value);
109 /*----------------------------------------------------------
111 | Handles on exit specific actions
112 +--------------------------------------------------------- */
113 static void exit_handler()
115 struct sigaction siga;
117 memset(&siga, 0, sizeof siga);
118 siga.sa_handler = SIG_IGN;
119 sigaction(SIGTERM, &siga, NULL);
123 else if (childpid > 0)
124 killpg(childpid, SIGTERM);
127 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
129 NOTICE("Received SIGTERM");
133 static void on_sighup(int signum, siginfo_t *info, void *uctx)
135 NOTICE("Received SIGHUP");
139 static void setup_daemon()
141 struct sigaction siga;
143 /* install signal handlers */
144 memset(&siga, 0, sizeof siga);
145 siga.sa_flags = SA_SIGINFO;
147 siga.sa_sigaction = on_sigterm;
148 sigaction(SIGTERM, &siga, NULL);
150 siga.sa_sigaction = on_sighup;
151 sigaction(SIGHUP, &siga, NULL);
154 atexit(exit_handler);
156 /* ignore any SIGPIPE */
157 signal(SIGPIPE, SIG_IGN);
160 /*----------------------------------------------------------
162 | set the process in background
163 +--------------------------------------------------------- */
164 static void daemonize()
169 // open /dev/console to redirect output messAFBes
170 consoleFD = open(main_config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
172 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
175 // fork process when running background mode
178 // if fail nothing much to do
180 ERROR("AFB-daemon Failed to fork son process");
183 // if in father process, just leave
187 // son process get all data in standalone mode
188 NOTICE("background mode [pid:%d console:%s]", getpid(),
189 main_config->console);
191 // redirect default I/O on console
193 dup(consoleFD); // redirect stderr
195 dup(consoleFD); // redirect stdout
196 close(0); // no need for stdin
200 setsid(); // allow father process to fully exit
201 sleep(2); // allow main to leave and release port
205 /*---------------------------------------------------------
207 | Handles the HTTP server
208 +--------------------------------------------------------- */
209 static int init_alias(void *closure, char *spec)
211 struct afb_hsrv *hsrv = closure;
212 char *path = strchr(spec, ':');
215 ERROR("Missing ':' in alias %s. Alias ignored", spec);
219 INFO("Alias for url=%s to path=%s", spec, path);
220 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
224 static int init_http_server(struct afb_hsrv *hsrv)
226 if (!afb_hsrv_add_handler
227 (hsrv, main_config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
230 if (!afb_hsrv_add_handler
231 (hsrv, main_config->rootapi, afb_hswitch_apis, main_apiset, 10))
234 if (run_for_list(main_config->aliases, init_alias, hsrv))
237 if (main_config->roothttp != NULL) {
238 if (!afb_hsrv_add_alias
239 (hsrv, "", afb_common_rootdir_get_fd(), main_config->roothttp,
244 if (!afb_hsrv_add_handler
245 (hsrv, main_config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
252 static struct afb_hsrv *start_http_server()
255 struct afb_hsrv *hsrv;
257 if (afb_hreq_init_download_path(main_config->uploaddir)) {
258 ERROR("unable to set the upload directory %s", main_config->uploaddir);
262 hsrv = afb_hsrv_create();
264 ERROR("memory allocation failure");
268 if (!afb_hsrv_set_cache_timeout(hsrv, main_config->cache_timeout)
269 || !init_http_server(hsrv)) {
270 ERROR("initialisation of httpd failed");
275 NOTICE("Waiting port=%d rootdir=%s", main_config->http_port, main_config->rootdir);
276 NOTICE("Browser URL= http://localhost:%d", main_config->http_port);
278 rc = afb_hsrv_start(hsrv, (uint16_t) main_config->http_port, 15);
280 ERROR("starting of httpd failed");
288 /*---------------------------------------------------------
290 +--------------------------------------------------------- */
292 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
294 if (info->si_pid == childpid) {
295 switch (info->si_code) {
301 killpg(info->si_pid, SIGKILL);
302 waitpid(info->si_pid, NULL, 0);
314 #define SUBST_CHAR '@'
315 #define SUBST_STR "@"
317 static char *instanciate_string(char *arg, const char *port, const char *token)
319 char *resu, *it, *wr;
322 /* get the changes */
325 it = strchrnul(arg, SUBST_CHAR);
328 case 'p': chg++; dif += (int)strlen(port) - 2; break;
329 case 't': chg++; dif += (int)strlen(token) - 2; break;
330 case SUBST_CHAR: it++; chg++; dif--; break;
333 it = strchrnul(it, SUBST_CHAR);
336 /* return arg when no change */
340 /* allocates the result */
341 resu = malloc((it - arg) + dif + 1);
343 ERROR("out of memory");
347 /* instanciate the arguments */
350 it = strchrnul(arg, SUBST_CHAR);
351 wr = mempcpy(wr, arg, it - arg);
355 case 'p': wr = stpcpy(wr, port); break;
356 case 't': wr = stpcpy(wr, token); break;
357 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
358 case SUBST_CHAR: *wr++ = *it;
367 static int instanciate_environ(const char *port, const char *token)
369 extern char **environ;
373 /* instanciate the environment */
374 for (i = 0 ; environ[i] ; i++) {
375 repl = instanciate_string(environ[i], port, token);
383 static int instanciate_command_args(const char *port, const char *token)
388 /* instanciate the arguments */
389 for (i = 0 ; main_config->exec[i] ; i++) {
390 repl = instanciate_string(main_config->exec[i], port, token);
393 main_config->exec[i] = repl;
398 static int execute_command()
400 struct sigaction siga;
405 /* check whether a command is to execute or not */
406 if (!main_config->exec || !main_config->exec[0])
412 /* install signal handler */
413 memset(&siga, 0, sizeof siga);
414 siga.sa_sigaction = on_sigchld;
415 siga.sa_flags = SA_SIGINFO;
416 sigaction(SIGCHLD, &siga, NULL);
423 /* compute the string for port */
424 if (main_config->http_port)
425 rc = snprintf(port, sizeof port, "%d", main_config->http_port);
427 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
428 if (rc < 0 || rc >= (int)(sizeof port)) {
429 ERROR("port->txt failed");
432 /* instanciate arguments and environment */
433 token = afb_session_initial_token();
434 if (instanciate_command_args(port, token) >= 0
435 && instanciate_environ(port, token) >= 0) {
439 execv(main_config->exec[0], main_config->exec);
440 ERROR("can't launch %s: %m", main_config->exec[0]);
447 /*---------------------------------------------------------
449 +--------------------------------------------------------- */
453 struct afb_xreq xreq;
456 struct afb_config_list *current;
457 struct afb_session *session;
460 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
462 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
466 NOTICE("startup call %s returned %s (%s)", sreq->current->value, json_object_get_string(object), info);
467 json_object_put(object);
469 ERROR("startup call %s ERROR! %s (%s)", sreq->current->value, error, info);
474 static void startup_call_current(struct startup_req *sreq);
476 static void startup_call_unref(struct afb_xreq *xreq)
478 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
482 json_object_put(sreq->xreq.json);
483 sreq->current = sreq->current->next;
485 startup_call_current(sreq);
487 afb_session_close(sreq->session);
488 afb_session_unref(sreq->session);
493 static struct afb_xreq_query_itf startup_xreq_itf =
495 .reply = startup_call_reply,
496 .unref = startup_call_unref
499 static void startup_call_current(struct startup_req *sreq)
501 char *api, *verb, *json;
503 api = sreq->current->value;
504 verb = strchr(api, '/');
506 json = strchr(verb, ':');
508 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
509 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
510 sreq->xreq.context.validated = 1;
511 sreq->api = strndup(api, verb - api);
512 sreq->verb = strndup(verb + 1, json - verb - 1);
513 sreq->xreq.request.called_api = sreq->api;
514 sreq->xreq.request.called_verb = sreq->verb;
515 sreq->xreq.json = json_tokener_parse(json + 1);
516 if (sreq->api && sreq->verb && sreq->xreq.json) {
517 afb_xreq_process(&sreq->xreq, main_apiset);
522 ERROR("Bad call specification %s", sreq->current->value);
526 static void run_startup_calls()
528 struct afb_config_list *list;
529 struct startup_req *sreq;
531 list = main_config->calls;
533 sreq = calloc(1, sizeof *sreq);
534 sreq->session = afb_session_create(3600);
535 sreq->current = list;
536 startup_call_current(sreq);
540 /*---------------------------------------------------------
541 | job for starting the daemon
542 +--------------------------------------------------------- */
544 static void start(int signum, void *arg)
546 struct afb_hsrv *hsrv;
548 afb_debug("start-entry");
551 ERROR("start aborted: received signal %s", strsignal(signum));
555 /* set the directories */
556 mkdir(main_config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
557 if (chdir(main_config->workdir) < 0) {
558 ERROR("Can't enter working dir %s", main_config->workdir);
561 if (afb_common_rootdir_set(main_config->rootdir) < 0) {
562 ERROR("failed to set common root directory");
566 /* configure the daemon */
567 if (afb_session_init(main_config->max_session_count, main_config->session_timeout, main_config->token)) {
568 ERROR("initialisation of session manager failed");
571 main_apiset = afb_apiset_create("main", main_config->api_timeout);
573 ERROR("can't create main api set");
576 if (afb_monitor_init(main_apiset, main_apiset) < 0) {
577 ERROR("failed to setup monitor");
580 if (afb_supervision_init() < 0) {
581 ERROR("failed to setup supervision");
586 if (main_config->tracereq)
587 afb_hook_create_xreq(NULL, NULL, NULL, main_config->tracereq, NULL, NULL);
588 if (main_config->traceapi)
589 afb_hook_create_api(NULL, main_config->traceapi, NULL, NULL);
590 if (main_config->traceevt)
591 afb_hook_create_evt(NULL, main_config->traceevt, NULL, NULL);
592 if (main_config->traceses)
593 afb_hook_create_session(NULL, main_config->traceses, NULL, NULL);
596 afb_debug("start-load");
597 apiset_start_list(main_config->so_bindings, afb_api_so_add_binding, "the binding");
598 #if defined(WITH_DBUS_TRANSPARENCY)
599 apiset_start_list(main_config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
601 apiset_start_list(main_config->ws_clients, afb_api_ws_add_client_weak, "the afb-websocket client");
602 apiset_start_list(main_config->ldpaths, afb_api_so_add_pathset_fails, "the binding path set");
603 apiset_start_list(main_config->weak_ldpaths, afb_api_so_add_pathset_nofails, "the weak binding path set");
604 apiset_start_list(main_config->auto_ws, afb_autoset_add_ws, "the automatic afb-websocket path set");
605 apiset_start_list(main_config->auto_link, afb_autoset_add_so, "the automatic link binding path set");
607 #if defined(WITH_DBUS_TRANSPARENCY)
608 apiset_start_list(main_config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
610 apiset_start_list(main_config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
612 DEBUG("Init config done");
614 /* start the services */
615 afb_debug("start-start");
616 #if !defined(NO_CALL_PERSONALITY)
617 personality((unsigned long)-1L);
619 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
622 /* start the HTTP server */
623 afb_debug("start-http");
624 if (!main_config->no_httpd) {
625 if (main_config->http_port <= 0) {
626 ERROR("no port is defined");
630 if (!afb_hreq_init_cookie(main_config->http_port, main_config->rootapi, main_config->session_timeout)) {
631 ERROR("initialisation of HTTP cookies failed");
635 hsrv = start_http_server();
640 /* run the startup calls */
641 afb_debug("start-call");
644 /* run the command */
645 afb_debug("start-exec");
646 if (execute_command() < 0)
650 sd_notify(1, "READY=1");
656 /*---------------------------------------------------------
658 | Parse option and launch action
659 +--------------------------------------------------------- */
661 int main(int argc, char *argv[])
663 afb_debug("main-entry");
665 // let's run this program with a low priority
668 // ------------- Build session handler & init config -------
669 main_config = afb_config_parse_arguments(argc, argv);
670 if (main_config->name) {
671 verbose_set_name(main_config->name, 0);
672 process_name_set_name(main_config->name);
673 process_name_replace_cmdline(argv, main_config->name);
675 afb_debug("main-args");
677 // --------- run -----------
678 if (main_config->background) {
679 // --------- in background mode -----------
680 INFO("entering background mode");
683 // ---- in foreground mode --------------------
684 INFO("entering foreground mode");
686 INFO("running with pid %d", getpid());
688 /* set the daemon environment */
691 afb_debug("main-start");
693 /* enter job processing */
694 jobs_start(3, 0, 50, start, NULL);
695 WARNING("hoops returned from jobs_enter! [report bug]");