2 * Copyright (C) 2015-2019 "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.
33 #if !defined(NO_CALL_PERSONALITY)
34 #include <sys/personality.h>
37 #include <json-c/json.h>
39 #include <systemd/sd-daemon.h>
41 #include "afb-config.h"
42 #include "afb-hswitch.h"
43 #include "afb-apiset.h"
44 #include "afb-autoset.h"
45 #include "afb-api-so.h"
46 #if defined(WITH_DBUS_TRANSPARENCY)
47 # include "afb-api-dbus.h"
49 #include "afb-api-ws.h"
53 #include "afb-session.h"
55 #include "afb-common.h"
56 #include "afb-export.h"
57 #include "afb-monitor.h"
59 #include "afb-hook-flags.h"
60 #include "afb-debug.h"
61 #if defined(WITH_SUPERVISION)
62 # include "afb-supervision.h"
65 #include "process-name.h"
66 #include "wrap-json.h"
68 #include "sig-monitor.h"
71 #if !defined(DEFAULT_BINDER_INTERFACE)
72 # define DEFAULT_BINDER_INTERFACE NULL
76 if SELF_PGROUP == 0 the launched command is the group leader
77 if SELF_PGROUP != 0 afb-daemon is the group leader
81 struct afb_apiset *main_apiset;
82 struct json_object *main_config;
84 static pid_t childpid;
87 * Tiny helper around putenv: add the variable name=value
89 * @param name name of the variable to set
90 * @param value value to set to the variable
92 * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
94 static int addenv(const char *name, const char *value)
98 head = malloc(2 + strlen(name) + strlen(value));
103 middle = stpcpy(head, name);
105 strcpy(&middle[1], value);
110 * Tiny helper around addenv that export the real path
112 * @param name name of the variable to set
113 * @param path the path value to export to the variable
115 * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
117 static int addenv_realpath(const char *name, const char *path)
119 char buffer[PATH_MAX];
120 char *p = realpath(path, buffer);
121 return p ? addenv(name, p) : -1;
125 * Tiny helper around addenv that export an integer
127 * @param name name of the variable to set
128 * @param value the integer value to export
130 * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
132 static int addenv_int(const char *name, int value)
135 snprintf(buffer, sizeof buffer, "%d", value);
136 return addenv(name, buffer);
139 /*----------------------------------------------------------
140 | helpers for handling list of arguments
141 +--------------------------------------------------------- */
143 static const char *run_for_config_array_opt(const char *name,
144 int (*run) (void *closure, const char *value),
148 struct json_object *array, *value;
150 if (json_object_object_get_ex(main_config, name, &array)) {
151 if (!json_object_is_type(array, json_type_array))
152 return json_object_get_string(array);
153 n = (int)json_object_array_length(array);
154 for (i = 0 ; i < n ; i++) {
155 value = json_object_array_get_idx(array, i);
156 rc = run(closure, json_object_get_string(value));
158 return json_object_get_string(value);
164 static int run_start(void *closure, const char *value)
166 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set) = closure;
167 return starter(value, main_apiset, main_apiset) >= 0;
170 static void apiset_start_list(const char *name,
171 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set),
174 const char *item = run_for_config_array_opt(name, run_start, starter);
176 ERROR("can't start %s %s", message, item);
181 /*----------------------------------------------------------
183 | Handles on exit specific actions
184 +--------------------------------------------------------- */
185 static void exit_handler()
187 struct sigaction siga;
189 memset(&siga, 0, sizeof siga);
190 siga.sa_handler = SIG_IGN;
191 sigaction(SIGTERM, &siga, NULL);
195 else if (childpid > 0)
196 killpg(childpid, SIGTERM);
199 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
201 NOTICE("Received SIGTERM");
205 static void on_sighup(int signum, siginfo_t *info, void *uctx)
207 NOTICE("Received SIGHUP");
211 static void setup_daemon()
213 struct sigaction siga;
215 /* install signal handlers */
216 memset(&siga, 0, sizeof siga);
217 siga.sa_flags = SA_SIGINFO;
219 siga.sa_sigaction = on_sigterm;
220 sigaction(SIGTERM, &siga, NULL);
222 siga.sa_sigaction = on_sighup;
223 sigaction(SIGHUP, &siga, NULL);
226 atexit(exit_handler);
228 /* ignore any SIGPIPE */
229 signal(SIGPIPE, SIG_IGN);
232 /*----------------------------------------------------------
234 | set the process in background
235 +--------------------------------------------------------- */
236 static void daemonize()
238 int fd = 0, daemon, nostdin;
244 wrap_json_unpack(main_config, "{s?b s?s}", "daemon", &daemon, "output", &output);
248 fd = open(output, O_WRONLY | O_APPEND | O_CREAT, 0640);
250 ERROR("Can't open output %s", output);
256 INFO("entering background mode");
260 ERROR("Failed to fork daemon process");
269 /* closes the input */
271 NOTICE("Redirecting output to %s", output);
280 close(0); /* except if 'daemon', ctrl+C still works after that */
283 /*---------------------------------------------------------
285 | Handles the HTTP server
286 +--------------------------------------------------------- */
287 static int init_alias(void *closure, const char *spec)
289 struct afb_hsrv *hsrv = closure;
290 char *path = strchr(spec, ':');
293 ERROR("Missing ':' in alias %s. Alias ignored", spec);
297 INFO("Alias for url=%s to path=%s", spec, path);
298 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
302 static int init_http_server(struct afb_hsrv *hsrv)
305 const char *rootapi, *roothttp, *rootbase;
308 rc = wrap_json_unpack(main_config, "{ss ss s?s}",
310 "rootbase", &rootbase,
311 "roothttp", &roothttp);
313 ERROR("Can't get HTTP server config");
317 if (!afb_hsrv_add_handler(hsrv, rootapi,
318 afb_hswitch_websocket_switch, main_apiset, 20))
321 if (!afb_hsrv_add_handler(hsrv, rootapi,
322 afb_hswitch_apis, main_apiset, 10))
325 if (run_for_config_array_opt("alias", init_alias, hsrv))
328 if (roothttp != NULL) {
329 if (!afb_hsrv_add_alias(hsrv, "",
330 afb_common_rootdir_get_fd(), roothttp, -10, 1))
334 if (!afb_hsrv_add_handler(hsrv, rootbase,
335 afb_hswitch_one_page_api_redirect, NULL, -20))
341 static struct afb_hsrv *start_http_server()
344 const char *uploaddir, *rootdir;
345 struct afb_hsrv *hsrv;
346 int cache_timeout, http_port;
348 rc = wrap_json_unpack(main_config, "{ss ss si si}",
349 "uploaddir", &uploaddir,
351 "cache-eol", &cache_timeout,
354 ERROR("Can't get HTTP server start config");
358 if (afb_hreq_init_download_path(uploaddir)) {
359 ERROR("unable to set the upload directory %s", uploaddir);
363 hsrv = afb_hsrv_create();
365 ERROR("memory allocation failure");
369 if (!afb_hsrv_set_cache_timeout(hsrv, cache_timeout)
370 || !init_http_server(hsrv)) {
371 ERROR("initialisation of httpd failed");
376 NOTICE("Waiting port=%d rootdir=%s", http_port, rootdir);
377 NOTICE("Browser URL= http://localhost:%d", http_port);
379 rc = afb_hsrv_start(hsrv, 15);
381 ERROR("starting of httpd failed");
386 rc = afb_hsrv_add_interface_tcp(hsrv, DEFAULT_BINDER_INTERFACE, (uint16_t) http_port);
388 ERROR("setting interface failed");
396 /*---------------------------------------------------------
398 +--------------------------------------------------------- */
400 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
402 if (info->si_pid == childpid) {
403 switch (info->si_code) {
409 killpg(info->si_pid, SIGKILL);
410 waitpid(info->si_pid, NULL, 0);
422 #define SUBST_CHAR '@'
423 #define SUBST_STR "@"
425 static char *instanciate_string(const char *arg, const char *port, const char *token)
427 char *resu, *it, *wr;
430 /* get the changes */
433 it = strchrnul(arg, SUBST_CHAR);
436 case 'p': chg++; dif += (int)strlen(port) - 2; break;
437 case 't': chg++; dif += (int)strlen(token) - 2; break;
438 case SUBST_CHAR: it++; chg++; dif--; break;
441 it = strchrnul(it, SUBST_CHAR);
444 /* return arg when no change */
448 /* allocates the result */
449 resu = malloc((it - arg) + dif + 1);
451 ERROR("out of memory");
455 /* instanciate the arguments */
458 it = strchrnul(arg, SUBST_CHAR);
459 wr = mempcpy(wr, arg, it - arg);
463 case 'p': wr = stpcpy(wr, port); break;
464 case 't': wr = stpcpy(wr, token); break;
465 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
466 case SUBST_CHAR: *wr++ = *it;
475 static int instanciate_environ(const char *port, const char *token)
477 extern char **environ;
481 /* instantiate the environment */
482 for (i = 0 ; environ[i] ; i++) {
483 repl = instanciate_string(environ[i], port, token);
491 static char **instanciate_command_args(struct json_object *exec, const char *port, const char *token)
497 /* allocates the result */
498 n = (int)json_object_array_length(exec);
499 result = malloc((n + 1) * sizeof * result);
501 ERROR("out of memory");
505 /* instanciate the arguments */
506 for (i = 0 ; i < n ; i++) {
507 repl = instanciate_string(json_object_get_string(json_object_array_get_idx(exec, i)), port, token);
520 static int execute_command()
522 struct json_object *exec, *oport;
523 struct sigaction siga;
529 /* check whether a command is to execute or not */
530 if (!json_object_object_get_ex(main_config, "exec", &exec))
536 /* install signal handler */
537 memset(&siga, 0, sizeof siga);
538 siga.sa_sigaction = on_sigchld;
539 siga.sa_flags = SA_SIGINFO;
540 sigaction(SIGCHLD, &siga, NULL);
547 /* compute the string for port */
548 if (json_object_object_get_ex(main_config, "port", &oport))
549 rc = snprintf(port, sizeof port, "%s", json_object_get_string(oport));
551 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
552 if (rc < 0 || rc >= (int)(sizeof port)) {
553 ERROR("port->txt failed");
556 /* instantiate arguments and environment */
557 token = afb_session_initial_token();
558 args = instanciate_command_args(exec, port, token);
559 if (args && instanciate_environ(port, token) >= 0) {
563 execv(args[0], args);
564 ERROR("can't launch %s: %m", args[0]);
571 /*---------------------------------------------------------
573 +--------------------------------------------------------- */
577 struct afb_xreq xreq;
580 struct json_object *calls;
583 const char *callspec;
584 struct afb_session *session;
587 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
589 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
593 NOTICE("startup call %s returned %s (%s)", sreq->callspec, json_object_get_string(object), info);
594 json_object_put(object);
596 ERROR("startup call %s ERROR! %s (%s)", sreq->callspec, error, info);
601 static void startup_call_current(struct startup_req *sreq);
603 static void startup_call_unref(struct afb_xreq *xreq)
605 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
609 json_object_put(sreq->xreq.json);
610 if (++sreq->index < sreq->count)
611 startup_call_current(sreq);
613 afb_session_close(sreq->session);
614 afb_session_unref(sreq->session);
619 static struct afb_xreq_query_itf startup_xreq_itf =
621 .reply = startup_call_reply,
622 .unref = startup_call_unref
625 static void startup_call_current(struct startup_req *sreq)
627 const char *api, *verb, *json;
628 enum json_tokener_error jerr;
630 sreq->callspec = json_object_get_string(json_object_array_get_idx(sreq->calls, sreq->index)),
631 api = sreq->callspec;
632 verb = strchr(api, '/');
634 json = strchr(verb, ':');
636 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
637 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
638 sreq->xreq.context.validated = 1;
639 sreq->api = strndup(api, verb - api);
640 sreq->verb = strndup(verb + 1, json - verb - 1);
641 sreq->xreq.request.called_api = sreq->api;
642 sreq->xreq.request.called_verb = sreq->verb;
643 sreq->xreq.json = json_tokener_parse_verbose(json + 1, &jerr);
644 if (sreq->api && sreq->verb && jerr == json_tokener_success) {
645 afb_xreq_process(&sreq->xreq, main_apiset);
650 ERROR("Bad call specification %s", sreq->callspec);
654 static void run_startup_calls()
656 struct json_object *calls;
657 struct startup_req *sreq;
660 if (json_object_object_get_ex(main_config, "call", &calls)
661 && json_object_is_type(calls, json_type_array)
662 && (count = (int)json_object_array_length(calls))) {
663 sreq = calloc(1, sizeof *sreq);
664 sreq->session = afb_session_create(3600);
668 startup_call_current(sreq);
672 /*---------------------------------------------------------
673 | job for starting the daemon
674 +--------------------------------------------------------- */
676 static void start(int signum, void *arg)
678 const char *tracereq, *traceapi, *traceevt, *traceses, *tracesvc, *traceditf, *traceglob;
679 const char *workdir, *rootdir, *token, *rootapi;
680 struct json_object *settings;
681 struct afb_hsrv *hsrv;
682 int max_session_count, session_timeout, api_timeout;
683 int no_httpd, http_port;
687 afb_debug("start-entry");
690 ERROR("start aborted: received signal %s", strsignal(signum));
695 token = rootapi = tracesvc = traceditf = tracereq =
696 traceapi = traceevt = traceses = traceglob = NULL;
699 rc = wrap_json_unpack(main_config, "{"
704 #if !defined(REMOVE_LEGACY_TRACE)
707 "s?s s?s s?s s?s s?s"
714 "apitimeout", &api_timeout,
715 "cntxtimeout", &session_timeout,
716 "session-max", &max_session_count,
718 "no-httpd", &no_httpd,
723 #if !defined(REMOVE_LEGACY_TRACE)
724 "tracesvc", &tracesvc,
725 "traceditf", &traceditf,
727 "tracereq", &tracereq,
728 "traceapi", &traceapi,
729 "traceevt", &traceevt,
730 "traceses", &traceses,
731 "traceglob", &traceglob
734 ERROR("Unable to get start config");
738 /* initialize session handling */
739 if (afb_session_init(max_session_count, session_timeout, token)) {
740 ERROR("initialisation of session manager failed");
744 /* set the directories */
745 mkdir(workdir, S_IRWXU | S_IRGRP | S_IXGRP);
746 if (chdir(workdir) < 0) {
747 ERROR("Can't enter working dir %s", workdir);
750 if (afb_common_rootdir_set(rootdir) < 0) {
751 ERROR("failed to set common root directory %s", rootdir);
754 if (addenv_realpath("AFB_WORKDIR", "." /* resolved by realpath */)
755 || addenv_realpath("AFB_ROOTDIR", rootdir /* relative to current directory */)) {
756 ERROR("can't set DIR environment");
763 ERROR("no port is defined");
766 if (http_port == 0) {
767 ERROR("random port is not implemented");
770 if (addenv_int("AFB_PORT", http_port)
771 || addenv("AFB_TOKEN", afb_session_initial_token())) {
772 ERROR("can't set HTTP environment");
777 /* configure the daemon */
778 afb_export_set_config(settings);
779 main_apiset = afb_apiset_create("main", api_timeout);
781 ERROR("can't create main api set");
784 if (afb_monitor_init(main_apiset, main_apiset) < 0) {
785 ERROR("failed to setup monitor");
788 #if defined(WITH_SUPERVISION)
789 if (afb_supervision_init(main_apiset, main_config) < 0) {
790 ERROR("failed to setup supervision");
797 afb_hook_create_xreq(NULL, NULL, NULL, afb_hook_flags_xreq_from_text(tracereq), NULL, NULL);
798 #if !defined(REMOVE_LEGACY_TRACE)
799 if (traceapi || tracesvc || traceditf)
800 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi)
801 | afb_hook_flags_legacy_ditf_from_text(traceditf)
802 | afb_hook_flags_legacy_svc_from_text(tracesvc), NULL, NULL);
805 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi), NULL, NULL);
808 afb_hook_create_evt(NULL, afb_hook_flags_evt_from_text(traceevt), NULL, NULL);
810 afb_hook_create_session(NULL, afb_hook_flags_session_from_text(traceses), NULL, NULL);
812 afb_hook_create_global(afb_hook_flags_global_from_text(traceglob), NULL, NULL);
814 /* load bindings and apis */
815 afb_debug("start-load");
816 apiset_start_list("binding", afb_api_so_add_binding, "the binding");
817 apiset_start_list("ldpaths", afb_api_so_add_pathset_fails, "the binding path set");
818 apiset_start_list("weak-ldpaths", afb_api_so_add_pathset_nofails, "the weak binding path set");
819 apiset_start_list("auto-api", afb_autoset_add_any, "the automatic api path set");
820 #if defined(WITH_DBUS_TRANSPARENCY)
821 apiset_start_list("dbus-client", afb_api_dbus_add_client, "the afb-dbus client");
823 apiset_start_list("ws-client", afb_api_ws_add_client_weak, "the afb-websocket client");
825 DEBUG("Init config done");
827 /* start the services */
828 afb_debug("start-start");
829 #if !defined(NO_CALL_PERSONALITY)
830 personality((unsigned long)-1L);
832 if (afb_apiset_start_all_services(main_apiset) < 0)
835 /* export started apis */
836 apiset_start_list("ws-server", afb_api_ws_add_server, "the afb-websocket service");
837 #if defined(WITH_DBUS_TRANSPARENCY)
838 apiset_start_list("dbus-server", afb_api_dbus_add_server, "the afb-dbus service");
841 /* start the HTTP server */
842 afb_debug("start-http");
844 if (!afb_hreq_init_cookie(http_port, rootapi, session_timeout)) {
845 ERROR("initialisation of HTTP cookies failed");
849 hsrv = start_http_server();
854 /* run the startup calls */
855 afb_debug("start-call");
858 /* run the command */
859 afb_debug("start-exec");
860 if (execute_command() < 0)
864 sd_notify(1, "READY=1");
866 /* activate the watchdog */
868 if (watchdog_activate() < 0)
869 ERROR("can't start the watchdog");
877 /*---------------------------------------------------------
879 | Parse option and launch action
880 +--------------------------------------------------------- */
882 int main(int argc, char *argv[])
884 struct json_object *obj;
885 afb_debug("main-entry");
887 // ------------- Build session handler & init config -------
888 main_config = afb_config_parse_arguments(argc, argv);
889 if (sig_monitor_init(
890 !json_object_object_get_ex(main_config, "trap-faults", &obj)
891 || json_object_get_boolean(obj)) < 0) {
892 ERROR("failed to initialise signal handlers");
897 if (json_object_object_get_ex(main_config, "name", &obj)) {
898 verbose_set_name(json_object_get_string(obj), 0);
899 process_name_set_name(json_object_get_string(obj));
900 process_name_replace_cmdline(argv, json_object_get_string(obj));
902 afb_debug("main-args");
904 // --------- run -----------
906 INFO("running with pid %d", getpid());
908 /* set the daemon environment */
911 afb_debug("main-start");
913 /* enter job processing */
914 jobs_start(3, 0, 50, start, NULL);
915 WARNING("hoops returned from jobs_enter! [report bug]");