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()
218 int fd = 0, daemon, nostdin;
224 wrap_json_unpack(main_config, "{s?b s?s}", "daemon", &daemon, "output", &output);
228 fd = open(output, O_WRONLY | O_APPEND | O_CREAT, 0640);
230 ERROR("Can't open output %s", output);
236 INFO("entering background mode");
240 ERROR("Failed to fork daemon process");
249 /* closes the input */
251 NOTICE("Redirecting output to %s", output);
260 close(0); /* except if 'daemon', ctrl+C still works after that */
263 /*---------------------------------------------------------
265 | Handles the HTTP server
266 +--------------------------------------------------------- */
267 static int init_alias(void *closure, const char *spec)
269 struct afb_hsrv *hsrv = closure;
270 char *path = strchr(spec, ':');
273 ERROR("Missing ':' in alias %s. Alias ignored", spec);
277 INFO("Alias for url=%s to path=%s", spec, path);
278 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
282 static int init_http_server(struct afb_hsrv *hsrv)
285 const char *rootapi, *roothttp, *rootbase;
288 rc = wrap_json_unpack(main_config, "{ss ss s?s}",
290 "rootbase", &rootbase,
291 "roothttp", &roothttp);
293 ERROR("Can't get HTTP server config");
297 if (!afb_hsrv_add_handler(hsrv, rootapi,
298 afb_hswitch_websocket_switch, main_apiset, 20))
301 if (!afb_hsrv_add_handler(hsrv, rootapi,
302 afb_hswitch_apis, main_apiset, 10))
305 if (run_for_config_array_opt("alias", init_alias, hsrv))
308 if (roothttp != NULL) {
309 if (!afb_hsrv_add_alias(hsrv, "",
310 afb_common_rootdir_get_fd(), roothttp, -10, 1))
314 if (!afb_hsrv_add_handler(hsrv, rootbase,
315 afb_hswitch_one_page_api_redirect, NULL, -20))
321 static struct afb_hsrv *start_http_server()
324 const char *uploaddir, *rootdir;
325 struct afb_hsrv *hsrv;
326 int cache_timeout, http_port;
328 rc = wrap_json_unpack(main_config, "{ss ss si si}",
329 "uploaddir", &uploaddir,
331 "cache-eol", &cache_timeout,
334 ERROR("Can't get HTTP server start config");
338 if (afb_hreq_init_download_path(uploaddir)) {
339 ERROR("unable to set the upload directory %s", uploaddir);
343 hsrv = afb_hsrv_create();
345 ERROR("memory allocation failure");
349 if (!afb_hsrv_set_cache_timeout(hsrv, cache_timeout)
350 || !init_http_server(hsrv)) {
351 ERROR("initialisation of httpd failed");
356 NOTICE("Waiting port=%d rootdir=%s", http_port, rootdir);
357 NOTICE("Browser URL= http://localhost:%d", http_port);
359 rc = afb_hsrv_start(hsrv, (uint16_t) http_port, 15);
361 ERROR("starting of httpd failed");
369 /*---------------------------------------------------------
371 +--------------------------------------------------------- */
373 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
375 if (info->si_pid == childpid) {
376 switch (info->si_code) {
382 killpg(info->si_pid, SIGKILL);
383 waitpid(info->si_pid, NULL, 0);
395 #define SUBST_CHAR '@'
396 #define SUBST_STR "@"
398 static char *instanciate_string(const char *arg, const char *port, const char *token)
400 char *resu, *it, *wr;
403 /* get the changes */
406 it = strchrnul(arg, SUBST_CHAR);
409 case 'p': chg++; dif += (int)strlen(port) - 2; break;
410 case 't': chg++; dif += (int)strlen(token) - 2; break;
411 case SUBST_CHAR: it++; chg++; dif--; break;
414 it = strchrnul(it, SUBST_CHAR);
417 /* return arg when no change */
421 /* allocates the result */
422 resu = malloc((it - arg) + dif + 1);
424 ERROR("out of memory");
428 /* instanciate the arguments */
431 it = strchrnul(arg, SUBST_CHAR);
432 wr = mempcpy(wr, arg, it - arg);
436 case 'p': wr = stpcpy(wr, port); break;
437 case 't': wr = stpcpy(wr, token); break;
438 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
439 case SUBST_CHAR: *wr++ = *it;
448 static int instanciate_environ(const char *port, const char *token)
450 extern char **environ;
454 /* instantiate the environment */
455 for (i = 0 ; environ[i] ; i++) {
456 repl = instanciate_string(environ[i], port, token);
464 static char **instanciate_command_args(struct json_object *exec, const char *port, const char *token)
470 /* allocates the result */
471 n = (int)json_object_array_length(exec);
472 result = malloc((n + 1) * sizeof * result);
474 ERROR("out of memory");
478 /* instanciate the arguments */
479 for (i = 0 ; i < n ; i++) {
480 repl = instanciate_string(json_object_get_string(json_object_array_get_idx(exec, i)), port, token);
493 static int execute_command()
495 struct json_object *exec, *oport;
496 struct sigaction siga;
502 /* check whether a command is to execute or not */
503 if (!json_object_object_get_ex(main_config, "exec", &exec))
509 /* install signal handler */
510 memset(&siga, 0, sizeof siga);
511 siga.sa_sigaction = on_sigchld;
512 siga.sa_flags = SA_SIGINFO;
513 sigaction(SIGCHLD, &siga, NULL);
520 /* compute the string for port */
521 if (json_object_object_get_ex(main_config, "port", &oport))
522 rc = snprintf(port, sizeof port, "%s", json_object_get_string(oport));
524 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
525 if (rc < 0 || rc >= (int)(sizeof port)) {
526 ERROR("port->txt failed");
529 /* instanciate arguments and environment */
530 token = afb_session_initial_token();
531 args = instanciate_command_args(exec, port, token);
532 if (args && instanciate_environ(port, token) >= 0) {
536 execv(args[0], args);
537 ERROR("can't launch %s: %m", args[0]);
544 /*---------------------------------------------------------
546 +--------------------------------------------------------- */
550 struct afb_xreq xreq;
553 struct json_object *calls;
556 const char *callspec;
557 struct afb_session *session;
560 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
562 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
566 NOTICE("startup call %s returned %s (%s)", sreq->callspec, json_object_get_string(object), info);
567 json_object_put(object);
569 ERROR("startup call %s ERROR! %s (%s)", sreq->callspec, error, info);
574 static void startup_call_current(struct startup_req *sreq);
576 static void startup_call_unref(struct afb_xreq *xreq)
578 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
582 json_object_put(sreq->xreq.json);
583 if (++sreq->index < sreq->count)
584 startup_call_current(sreq);
586 afb_session_close(sreq->session);
587 afb_session_unref(sreq->session);
592 static struct afb_xreq_query_itf startup_xreq_itf =
594 .reply = startup_call_reply,
595 .unref = startup_call_unref
598 static void startup_call_current(struct startup_req *sreq)
600 const char *api, *verb, *json;
601 enum json_tokener_error jerr;
603 sreq->callspec = json_object_get_string(json_object_array_get_idx(sreq->calls, sreq->index)),
604 api = sreq->callspec;
605 verb = strchr(api, '/');
607 json = strchr(verb, ':');
609 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
610 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
611 sreq->xreq.context.validated = 1;
612 sreq->api = strndup(api, verb - api);
613 sreq->verb = strndup(verb + 1, json - verb - 1);
614 sreq->xreq.request.called_api = sreq->api;
615 sreq->xreq.request.called_verb = sreq->verb;
616 sreq->xreq.json = json_tokener_parse_verbose(json + 1, &jerr);
617 if (sreq->api && sreq->verb && jerr == json_tokener_success) {
618 afb_xreq_process(&sreq->xreq, main_apiset);
623 ERROR("Bad call specification %s", sreq->callspec);
627 static void run_startup_calls()
629 struct json_object *calls;
630 struct startup_req *sreq;
633 if (json_object_object_get_ex(main_config, "call", &calls)
634 && json_object_is_type(calls, json_type_array)
635 && (count = (int)json_object_array_length(calls))) {
636 sreq = calloc(1, sizeof *sreq);
637 sreq->session = afb_session_create(3600);
641 startup_call_current(sreq);
645 /*---------------------------------------------------------
646 | job for starting the daemon
647 +--------------------------------------------------------- */
649 static void start(int signum, void *arg)
651 const char *tracereq, *traceapi, *traceevt, *traceses, *tracesvc, *traceditf, *traceglob;
652 const char *workdir, *rootdir, *token, *rootapi;
653 struct json_object *settings;
654 struct afb_hsrv *hsrv;
655 int max_session_count, session_timeout, api_timeout;
656 int no_httpd, http_port;
660 afb_debug("start-entry");
663 ERROR("start aborted: received signal %s", strsignal(signum));
668 token = rootapi = tracesvc = traceditf = tracereq =
669 traceapi = traceevt = traceses = traceglob = NULL;
670 no_httpd = http_port = 0;
671 rc = wrap_json_unpack(main_config, "{"
676 #if !defined(REMOVE_LEGACY_TRACE)
679 "s?s s?s s?s s?s s?s"
686 "apitimeout", &api_timeout,
687 "cntxtimeout", &session_timeout,
688 "session-max", &max_session_count,
690 "no-httpd", &no_httpd,
695 #if !defined(REMOVE_LEGACY_TRACE)
696 "tracesvc", &tracesvc,
697 "traceditf", &traceditf,
699 "tracereq", &tracereq,
700 "traceapi", &traceapi,
701 "traceevt", &traceevt,
702 "traceses", &traceses,
703 "traceglob", &traceglob
706 ERROR("Unable to get start config");
710 /* set the directories */
711 mkdir(workdir, S_IRWXU | S_IRGRP | S_IXGRP);
712 if (chdir(workdir) < 0) {
713 ERROR("Can't enter working dir %s", workdir);
716 if (afb_common_rootdir_set(rootdir) < 0) {
717 ERROR("failed to set common root directory %s", rootdir);
720 if (addenv_realpath("AFB_WORKDIR", "." /* resolved by realpath */)
721 || addenv_realpath("AFB_ROOTDIR", rootdir /* relative to current directory */)) {
722 ERROR("can't set environment");
726 /* configure the daemon */
727 afb_export_set_config(settings);
728 if (afb_session_init(max_session_count, session_timeout, token)) {
729 ERROR("initialisation of session manager failed");
732 main_apiset = afb_apiset_create("main", api_timeout);
734 ERROR("can't create main api set");
737 if (afb_monitor_init(main_apiset, main_apiset) < 0) {
738 ERROR("failed to setup monitor");
741 #if defined(WITH_SUPERVISION)
742 if (afb_supervision_init(main_apiset, main_config) < 0) {
743 ERROR("failed to setup supervision");
750 afb_hook_create_xreq(NULL, NULL, NULL, afb_hook_flags_xreq_from_text(tracereq), NULL, NULL);
751 #if !defined(REMOVE_LEGACY_TRACE)
752 if (traceapi || tracesvc || traceditf)
753 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi)
754 | afb_hook_flags_legacy_ditf_from_text(traceditf)
755 | afb_hook_flags_legacy_svc_from_text(tracesvc), NULL, NULL);
758 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi), NULL, NULL);
761 afb_hook_create_evt(NULL, afb_hook_flags_evt_from_text(traceevt), NULL, NULL);
763 afb_hook_create_session(NULL, afb_hook_flags_session_from_text(traceses), NULL, NULL);
765 afb_hook_create_global(afb_hook_flags_global_from_text(traceglob), NULL, NULL);
767 /* load bindings and apis */
768 afb_debug("start-load");
769 apiset_start_list("binding", afb_api_so_add_binding, "the binding");
770 apiset_start_list("ldpaths", afb_api_so_add_pathset_fails, "the binding path set");
771 apiset_start_list("weak-ldpaths", afb_api_so_add_pathset_nofails, "the weak binding path set");
772 apiset_start_list("auto-api", afb_autoset_add_any, "the automatic api path set");
773 #if defined(WITH_DBUS_TRANSPARENCY)
774 apiset_start_list("dbus-client", afb_api_dbus_add_client, "the afb-dbus client");
776 apiset_start_list("ws-client", afb_api_ws_add_client_weak, "the afb-websocket client");
778 DEBUG("Init config done");
780 /* start the services */
781 afb_debug("start-start");
782 #if !defined(NO_CALL_PERSONALITY)
783 personality((unsigned long)-1L);
785 if (afb_apiset_start_all_services(main_apiset) < 0)
788 /* export started apis */
789 apiset_start_list("ws-server", afb_api_ws_add_server, "the afb-websocket service");
790 #if defined(WITH_DBUS_TRANSPARENCY)
791 apiset_start_list("dbus-server", afb_api_dbus_add_server, "the afb-dbus service");
794 /* start the HTTP server */
795 afb_debug("start-http");
797 if (http_port <= 0) {
798 ERROR("no port is defined");
802 if (!afb_hreq_init_cookie(http_port, rootapi, session_timeout)) {
803 ERROR("initialisation of HTTP cookies failed");
807 hsrv = start_http_server();
812 /* run the startup calls */
813 afb_debug("start-call");
816 /* run the command */
817 afb_debug("start-exec");
818 if (execute_command() < 0)
822 sd_notify(1, "READY=1");
828 /*---------------------------------------------------------
830 | Parse option and launch action
831 +--------------------------------------------------------- */
833 int main(int argc, char *argv[])
835 struct json_object *obj;
836 afb_debug("main-entry");
838 // ------------- Build session handler & init config -------
839 main_config = afb_config_parse_arguments(argc, argv);
840 if (sig_monitor_init(
841 !json_object_object_get_ex(main_config, "trap-faults", &obj)
842 || json_object_get_boolean(obj)) < 0) {
843 ERROR("failed to initialise signal handlers");
848 if (json_object_object_get_ex(main_config, "name", &obj)) {
849 verbose_set_name(json_object_get_string(obj), 0);
850 process_name_set_name(json_object_get_string(obj));
851 process_name_replace_cmdline(argv, json_object_get_string(obj));
853 afb_debug("main-args");
855 // --------- run -----------
857 INFO("running with pid %d", getpid());
859 /* set the daemon environment */
862 afb_debug("main-start");
864 /* enter job processing */
865 jobs_start(3, 0, 50, start, NULL);
866 WARNING("hoops returned from jobs_enter! [report bug]");