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.
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 SELF_PGROUP == 0 the launched command is the group leader
72 if SELF_PGROUP != 0 afb-daemon is the group leader
76 struct afb_apiset *main_apiset;
77 struct json_object *main_config;
79 static pid_t childpid;
82 * Tiny helper around putenv: add the variable name=value
84 * @param name name of the variable to set
85 * @param value value to set to the variable
87 * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
89 static int addenv(const char *name, const char *value)
93 head = malloc(2 + strlen(name) + strlen(value));
98 middle = stpcpy(head, name);
100 strcpy(&middle[1], value);
105 * Tiny helper around addenv that export the real path
107 * @param name name of the variable to set
108 * @param path the path value to export to the variable
110 * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
112 static int addenv_realpath(const char *name, const char *path)
114 char buffer[PATH_MAX];
115 char *p = realpath(path, buffer);
116 return p ? addenv(name, p) : -1;
119 /*----------------------------------------------------------
120 | helpers for handling list of arguments
121 +--------------------------------------------------------- */
123 static const char *run_for_config_array_opt(const char *name,
124 int (*run) (void *closure, const char *value),
128 struct json_object *array, *value;
130 if (json_object_object_get_ex(main_config, name, &array)) {
131 if (!json_object_is_type(array, json_type_array))
132 return json_object_get_string(array);
133 n = (int)json_object_array_length(array);
134 for (i = 0 ; i < n ; i++) {
135 value = json_object_array_get_idx(array, i);
136 rc = run(closure, json_object_get_string(value));
138 return json_object_get_string(value);
144 static int run_start(void *closure, const char *value)
146 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set) = closure;
147 return starter(value, main_apiset, main_apiset) >= 0;
150 static void apiset_start_list(const char *name,
151 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set),
154 const char *item = run_for_config_array_opt(name, run_start, starter);
156 ERROR("can't start %s %s", message, item);
161 /*----------------------------------------------------------
163 | Handles on exit specific actions
164 +--------------------------------------------------------- */
165 static void exit_handler()
167 struct sigaction siga;
169 memset(&siga, 0, sizeof siga);
170 siga.sa_handler = SIG_IGN;
171 sigaction(SIGTERM, &siga, NULL);
175 else if (childpid > 0)
176 killpg(childpid, SIGTERM);
179 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
181 NOTICE("Received SIGTERM");
185 static void on_sighup(int signum, siginfo_t *info, void *uctx)
187 NOTICE("Received SIGHUP");
191 static void setup_daemon()
193 struct sigaction siga;
195 /* install signal handlers */
196 memset(&siga, 0, sizeof siga);
197 siga.sa_flags = SA_SIGINFO;
199 siga.sa_sigaction = on_sigterm;
200 sigaction(SIGTERM, &siga, NULL);
202 siga.sa_sigaction = on_sighup;
203 sigaction(SIGHUP, &siga, NULL);
206 atexit(exit_handler);
208 /* ignore any SIGPIPE */
209 signal(SIGPIPE, SIG_IGN);
212 /*----------------------------------------------------------
214 | set the process in background
215 +--------------------------------------------------------- */
216 static void daemonize()
224 wrap_json_unpack(main_config, "{s?b s?s}", "daemon", &daemon, "output", &output);
227 fd = open(output, O_WRONLY | O_APPEND | O_CREAT, 0640);
229 ERROR("Can't open output %s", output);
235 INFO("entering background mode");
239 ERROR("Failed to fork daemon process");
246 /* closes the input */
248 NOTICE("Redirecting output to %s", output);
256 /* after that ctrl+C still works */
260 /*---------------------------------------------------------
262 | Handles the HTTP server
263 +--------------------------------------------------------- */
264 static int init_alias(void *closure, const char *spec)
266 struct afb_hsrv *hsrv = closure;
267 char *path = strchr(spec, ':');
270 ERROR("Missing ':' in alias %s. Alias ignored", spec);
274 INFO("Alias for url=%s to path=%s", spec, path);
275 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
279 static int init_http_server(struct afb_hsrv *hsrv)
282 const char *rootapi, *roothttp, *rootbase;
285 rc = wrap_json_unpack(main_config, "{ss ss s?s}",
287 "rootbase", &rootbase,
288 "roothttp", &roothttp);
290 ERROR("Can't get HTTP server config");
294 if (!afb_hsrv_add_handler(hsrv, rootapi,
295 afb_hswitch_websocket_switch, main_apiset, 20))
298 if (!afb_hsrv_add_handler(hsrv, rootapi,
299 afb_hswitch_apis, main_apiset, 10))
302 if (run_for_config_array_opt("alias", init_alias, hsrv))
305 if (roothttp != NULL) {
306 if (!afb_hsrv_add_alias(hsrv, "",
307 afb_common_rootdir_get_fd(), roothttp, -10, 1))
311 if (!afb_hsrv_add_handler(hsrv, rootbase,
312 afb_hswitch_one_page_api_redirect, NULL, -20))
318 static struct afb_hsrv *start_http_server()
321 const char *uploaddir, *rootdir;
322 struct afb_hsrv *hsrv;
323 int cache_timeout, http_port;
325 rc = wrap_json_unpack(main_config, "{ss ss si si}",
326 "uploaddir", &uploaddir,
328 "cache-eol", &cache_timeout,
331 ERROR("Can't get HTTP server start config");
335 if (afb_hreq_init_download_path(uploaddir)) {
336 ERROR("unable to set the upload directory %s", uploaddir);
340 hsrv = afb_hsrv_create();
342 ERROR("memory allocation failure");
346 if (!afb_hsrv_set_cache_timeout(hsrv, cache_timeout)
347 || !init_http_server(hsrv)) {
348 ERROR("initialisation of httpd failed");
353 NOTICE("Waiting port=%d rootdir=%s", http_port, rootdir);
354 NOTICE("Browser URL= http://localhost:%d", http_port);
356 rc = afb_hsrv_start(hsrv, (uint16_t) http_port, 15);
358 ERROR("starting of httpd failed");
366 /*---------------------------------------------------------
368 +--------------------------------------------------------- */
370 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
372 if (info->si_pid == childpid) {
373 switch (info->si_code) {
379 killpg(info->si_pid, SIGKILL);
380 waitpid(info->si_pid, NULL, 0);
392 #define SUBST_CHAR '@'
393 #define SUBST_STR "@"
395 static char *instanciate_string(const char *arg, const char *port, const char *token)
397 char *resu, *it, *wr;
400 /* get the changes */
403 it = strchrnul(arg, SUBST_CHAR);
406 case 'p': chg++; dif += (int)strlen(port) - 2; break;
407 case 't': chg++; dif += (int)strlen(token) - 2; break;
408 case SUBST_CHAR: it++; chg++; dif--; break;
411 it = strchrnul(it, SUBST_CHAR);
414 /* return arg when no change */
418 /* allocates the result */
419 resu = malloc((it - arg) + dif + 1);
421 ERROR("out of memory");
425 /* instanciate the arguments */
428 it = strchrnul(arg, SUBST_CHAR);
429 wr = mempcpy(wr, arg, it - arg);
433 case 'p': wr = stpcpy(wr, port); break;
434 case 't': wr = stpcpy(wr, token); break;
435 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
436 case SUBST_CHAR: *wr++ = *it;
445 static int instanciate_environ(const char *port, const char *token)
447 extern char **environ;
451 /* instantiate the environment */
452 for (i = 0 ; environ[i] ; i++) {
453 repl = instanciate_string(environ[i], port, token);
461 static char **instanciate_command_args(struct json_object *exec, const char *port, const char *token)
467 /* allocates the result */
468 n = (int)json_object_array_length(exec);
469 result = malloc((n + 1) * sizeof * result);
471 ERROR("out of memory");
475 /* instanciate the arguments */
476 for (i = 0 ; i < n ; i++) {
477 repl = instanciate_string(json_object_get_string(json_object_array_get_idx(exec, i)), port, token);
490 static int execute_command()
492 struct json_object *exec, *oport;
493 struct sigaction siga;
499 /* check whether a command is to execute or not */
500 if (!json_object_object_get_ex(main_config, "exec", &exec))
506 /* install signal handler */
507 memset(&siga, 0, sizeof siga);
508 siga.sa_sigaction = on_sigchld;
509 siga.sa_flags = SA_SIGINFO;
510 sigaction(SIGCHLD, &siga, NULL);
517 /* compute the string for port */
518 if (json_object_object_get_ex(main_config, "port", &oport))
519 rc = snprintf(port, sizeof port, "%s", json_object_get_string(oport));
521 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
522 if (rc < 0 || rc >= (int)(sizeof port)) {
523 ERROR("port->txt failed");
526 /* instanciate arguments and environment */
527 token = afb_session_initial_token();
528 args = instanciate_command_args(exec, port, token);
529 if (args && instanciate_environ(port, token) >= 0) {
533 execv(args[0], args);
534 ERROR("can't launch %s: %m", args[0]);
541 /*---------------------------------------------------------
543 +--------------------------------------------------------- */
547 struct afb_xreq xreq;
550 struct json_object *calls;
553 const char *callspec;
554 struct afb_session *session;
557 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
559 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
563 NOTICE("startup call %s returned %s (%s)", sreq->callspec, json_object_get_string(object), info);
564 json_object_put(object);
566 ERROR("startup call %s ERROR! %s (%s)", sreq->callspec, error, info);
571 static void startup_call_current(struct startup_req *sreq);
573 static void startup_call_unref(struct afb_xreq *xreq)
575 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
579 json_object_put(sreq->xreq.json);
580 if (++sreq->index < sreq->count)
581 startup_call_current(sreq);
583 afb_session_close(sreq->session);
584 afb_session_unref(sreq->session);
589 static struct afb_xreq_query_itf startup_xreq_itf =
591 .reply = startup_call_reply,
592 .unref = startup_call_unref
595 static void startup_call_current(struct startup_req *sreq)
597 const char *api, *verb, *json;
598 enum json_tokener_error jerr;
600 sreq->callspec = json_object_get_string(json_object_array_get_idx(sreq->calls, sreq->index)),
601 api = sreq->callspec;
602 verb = strchr(api, '/');
604 json = strchr(verb, ':');
606 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
607 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
608 sreq->xreq.context.validated = 1;
609 sreq->api = strndup(api, verb - api);
610 sreq->verb = strndup(verb + 1, json - verb - 1);
611 sreq->xreq.request.called_api = sreq->api;
612 sreq->xreq.request.called_verb = sreq->verb;
613 sreq->xreq.json = json_tokener_parse_verbose(json + 1, &jerr);
614 if (sreq->api && sreq->verb && jerr == json_tokener_success) {
615 afb_xreq_process(&sreq->xreq, main_apiset);
620 ERROR("Bad call specification %s", sreq->callspec);
624 static void run_startup_calls()
626 struct json_object *calls;
627 struct startup_req *sreq;
630 if (json_object_object_get_ex(main_config, "call", &calls)
631 && json_object_is_type(calls, json_type_array)
632 && (count = (int)json_object_array_length(calls))) {
633 sreq = calloc(1, sizeof *sreq);
634 sreq->session = afb_session_create(3600);
638 startup_call_current(sreq);
642 /*---------------------------------------------------------
643 | job for starting the daemon
644 +--------------------------------------------------------- */
646 static void start(int signum, void *arg)
648 const char *tracereq, *traceapi, *traceevt, *traceses, *tracesvc, *traceditf, *traceglob;
649 const char *workdir, *rootdir, *token, *rootapi;
650 struct json_object *settings;
651 struct afb_hsrv *hsrv;
652 int max_session_count, session_timeout, api_timeout;
653 int no_httpd, http_port;
657 afb_debug("start-entry");
660 ERROR("start aborted: received signal %s", strsignal(signum));
665 token = rootapi = tracesvc = traceditf = tracereq =
666 traceapi = traceevt = traceses = traceglob = NULL;
667 no_httpd = http_port = 0;
668 rc = wrap_json_unpack(main_config, "{"
673 #if !defined(REMOVE_LEGACY_TRACE)
676 "s?s s?s s?s s?s s?s"
683 "apitimeout", &api_timeout,
684 "cntxtimeout", &session_timeout,
685 "session-max", &max_session_count,
687 "no-httpd", &no_httpd,
692 #if !defined(REMOVE_LEGACY_TRACE)
693 "tracesvc", &tracesvc,
694 "traceditf", &traceditf,
696 "tracereq", &tracereq,
697 "traceapi", &traceapi,
698 "traceevt", &traceevt,
699 "traceses", &traceses,
700 "traceglob", &traceglob
703 ERROR("Unable to get start config");
707 /* set the directories */
708 mkdir(workdir, S_IRWXU | S_IRGRP | S_IXGRP);
709 if (chdir(workdir) < 0) {
710 ERROR("Can't enter working dir %s", workdir);
713 if (afb_common_rootdir_set(rootdir) < 0) {
714 ERROR("failed to set common root directory %s", rootdir);
717 if (addenv_realpath("AFB_WORKDIR", "." /* resolved by realpath */)
718 || addenv_realpath("AFB_ROOTDIR", rootdir /* relative to current directory */)) {
719 ERROR("can't set environment");
723 /* configure the daemon */
724 afb_export_set_config(settings);
725 if (afb_session_init(max_session_count, session_timeout, token)) {
726 ERROR("initialisation of session manager failed");
729 main_apiset = afb_apiset_create("main", api_timeout);
731 ERROR("can't create main api set");
734 if (afb_monitor_init(main_apiset, main_apiset) < 0) {
735 ERROR("failed to setup monitor");
738 #if defined(WITH_SUPERVISION)
739 if (afb_supervision_init(main_apiset, main_config) < 0) {
740 ERROR("failed to setup supervision");
747 afb_hook_create_xreq(NULL, NULL, NULL, afb_hook_flags_xreq_from_text(tracereq), NULL, NULL);
748 #if !defined(REMOVE_LEGACY_TRACE)
749 if (traceapi || tracesvc || traceditf)
750 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi)
751 | afb_hook_flags_legacy_ditf_from_text(traceditf)
752 | afb_hook_flags_legacy_svc_from_text(tracesvc), NULL, NULL);
755 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi), NULL, NULL);
758 afb_hook_create_evt(NULL, afb_hook_flags_evt_from_text(traceevt), NULL, NULL);
760 afb_hook_create_session(NULL, afb_hook_flags_session_from_text(traceses), NULL, NULL);
762 afb_hook_create_global(afb_hook_flags_global_from_text(traceglob), NULL, NULL);
764 /* load bindings and apis */
765 afb_debug("start-load");
766 apiset_start_list("binding", afb_api_so_add_binding, "the binding");
767 apiset_start_list("ldpaths", afb_api_so_add_pathset_fails, "the binding path set");
768 apiset_start_list("weak-ldpaths", afb_api_so_add_pathset_nofails, "the weak binding path set");
769 apiset_start_list("auto-api", afb_autoset_add_any, "the automatic api path set");
770 #if defined(WITH_DBUS_TRANSPARENCY)
771 apiset_start_list("dbus-client", afb_api_dbus_add_client, "the afb-dbus client");
773 apiset_start_list("ws-client", afb_api_ws_add_client_weak, "the afb-websocket client");
775 DEBUG("Init config done");
777 /* start the services */
778 afb_debug("start-start");
779 #if !defined(NO_CALL_PERSONALITY)
780 personality((unsigned long)-1L);
782 if (afb_apiset_start_all_services(main_apiset) < 0)
785 /* export started apis */
786 apiset_start_list("ws-server", afb_api_ws_add_server, "the afb-websocket service");
787 #if defined(WITH_DBUS_TRANSPARENCY)
788 apiset_start_list("dbus-server", afb_api_dbus_add_server, "the afb-dbus service");
791 /* start the HTTP server */
792 afb_debug("start-http");
794 if (http_port <= 0) {
795 ERROR("no port is defined");
799 if (!afb_hreq_init_cookie(http_port, rootapi, session_timeout)) {
800 ERROR("initialisation of HTTP cookies failed");
804 hsrv = start_http_server();
809 /* run the startup calls */
810 afb_debug("start-call");
813 /* run the command */
814 afb_debug("start-exec");
815 if (execute_command() < 0)
819 sd_notify(1, "READY=1");
825 /*---------------------------------------------------------
827 | Parse option and launch action
828 +--------------------------------------------------------- */
830 int main(int argc, char *argv[])
832 struct json_object *obj;
833 afb_debug("main-entry");
835 // ------------- Build session handler & init config -------
836 main_config = afb_config_parse_arguments(argc, argv);
837 if (sig_monitor_init(
838 !json_object_object_get_ex(main_config, "trap-faults", &obj)
839 || json_object_get_boolean(obj)) < 0) {
840 ERROR("failed to initialise signal handlers");
845 if (json_object_object_get_ex(main_config, "name", &obj)) {
846 verbose_set_name(json_object_get_string(obj), 0);
847 process_name_set_name(json_object_get_string(obj));
848 process_name_replace_cmdline(argv, json_object_get_string(obj));
850 afb_debug("main-args");
852 // --------- run -----------
854 INFO("running with pid %d", getpid());
856 /* set the daemon environment */
859 afb_debug("main-start");
861 /* enter job processing */
862 jobs_start(3, 0, 50, start, NULL);
863 WARNING("hoops returned from jobs_enter! [report bug]");