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>
42 #include "afb-hswitch.h"
43 #include "afb-apiset.h"
44 #include "afb-autoset.h"
45 #include "afb-api-so.h"
46 #if 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"
60 #include "afb-hook-flags.h"
62 #include "afb-debug.h"
64 # include "afb-supervision.h"
67 #include "process-name.h"
68 #include "wrap-json.h"
70 #include "sig-monitor.h"
73 #if !defined(DEFAULT_BINDER_INTERFACE)
74 # define DEFAULT_BINDER_INTERFACE NULL
78 if SELF_PGROUP == 0 the launched command is the group leader
79 if SELF_PGROUP != 0 afb-daemon is the group leader
83 struct afb_apiset *main_apiset;
84 struct json_object *main_config;
86 static pid_t childpid;
89 * Tiny helper around putenv: add the variable name=value
91 * @param name name of the variable to set
92 * @param value value to set to the variable
94 * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
96 static int addenv(const char *name, const char *value)
100 head = malloc(2 + strlen(name) + strlen(value));
105 middle = stpcpy(head, name);
107 strcpy(&middle[1], value);
112 * Tiny helper around addenv that export the real path
114 * @param name name of the variable to set
115 * @param path the path value to export to the variable
117 * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
119 static int addenv_realpath(const char *name, const char *path)
121 char buffer[PATH_MAX];
122 char *p = realpath(path, buffer);
123 return p ? addenv(name, p) : -1;
127 * Tiny helper around addenv that export an integer
129 * @param name name of the variable to set
130 * @param value the integer value to export
132 * @return 0 in case of success or -1 in case of error (with errno set to ENOMEM)
134 static int addenv_int(const char *name, int value)
137 snprintf(buffer, sizeof buffer, "%d", value);
138 return addenv(name, buffer);
141 /*----------------------------------------------------------
142 | helpers for handling list of arguments
143 +--------------------------------------------------------- */
145 static const char *run_for_config_array_opt(const char *name,
146 int (*run) (void *closure, const char *value),
150 struct json_object *array, *value;
152 if (json_object_object_get_ex(main_config, name, &array)) {
153 if (!json_object_is_type(array, json_type_array))
154 return json_object_get_string(array);
155 n = (int)json_object_array_length(array);
156 for (i = 0 ; i < n ; i++) {
157 value = json_object_array_get_idx(array, i);
158 rc = run(closure, json_object_get_string(value));
160 return json_object_get_string(value);
166 static int run_start(void *closure, const char *value)
168 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set) = closure;
169 return starter(value, main_apiset, main_apiset) >= 0;
172 static void apiset_start_list(const char *name,
173 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set),
176 const char *item = run_for_config_array_opt(name, run_start, starter);
178 ERROR("can't start %s %s", message, item);
183 /*----------------------------------------------------------
185 | Handles on exit specific actions
186 +--------------------------------------------------------- */
187 static void exit_handler()
189 struct sigaction siga;
191 memset(&siga, 0, sizeof siga);
192 siga.sa_handler = SIG_IGN;
193 sigaction(SIGTERM, &siga, NULL);
197 else if (childpid > 0)
198 killpg(childpid, SIGTERM);
201 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
203 NOTICE("Received SIGTERM");
207 static void on_sighup(int signum, siginfo_t *info, void *uctx)
209 NOTICE("Received SIGHUP");
213 static void setup_daemon()
215 struct sigaction siga;
217 /* install signal handlers */
218 memset(&siga, 0, sizeof siga);
219 siga.sa_flags = SA_SIGINFO;
221 siga.sa_sigaction = on_sigterm;
222 sigaction(SIGTERM, &siga, NULL);
224 siga.sa_sigaction = on_sighup;
225 sigaction(SIGHUP, &siga, NULL);
228 atexit(exit_handler);
230 /* ignore any SIGPIPE */
231 signal(SIGPIPE, SIG_IGN);
234 /*----------------------------------------------------------
236 | set the process in background
237 +--------------------------------------------------------- */
238 static void daemonize()
240 int fd = 0, daemon, nostdin;
246 wrap_json_unpack(main_config, "{s?b s?s}", "daemon", &daemon, "output", &output);
250 fd = open(output, O_WRONLY | O_APPEND | O_CREAT, 0640);
252 ERROR("Can't open output %s", output);
258 INFO("entering background mode");
262 ERROR("Failed to fork daemon process");
271 /* closes the input */
273 NOTICE("Redirecting output to %s", output);
282 close(0); /* except if 'daemon', ctrl+C still works after that */
285 /*---------------------------------------------------------
287 | Handles the HTTP server
288 +--------------------------------------------------------- */
289 static int init_alias(void *closure, const char *spec)
291 struct afb_hsrv *hsrv = closure;
292 char *path = strchr(spec, ':');
295 ERROR("Missing ':' in alias %s. Alias ignored", spec);
299 INFO("Alias for url=%s to path=%s", spec, path);
300 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
304 static int init_http_server(struct afb_hsrv *hsrv)
307 const char *rootapi, *roothttp, *rootbase;
310 rc = wrap_json_unpack(main_config, "{ss ss s?s}",
312 "rootbase", &rootbase,
313 "roothttp", &roothttp);
315 ERROR("Can't get HTTP server config");
319 if (!afb_hsrv_add_handler(hsrv, rootapi,
320 afb_hswitch_websocket_switch, main_apiset, 20))
323 if (!afb_hsrv_add_handler(hsrv, rootapi,
324 afb_hswitch_apis, main_apiset, 10))
327 if (run_for_config_array_opt("alias", init_alias, hsrv))
330 if (roothttp != NULL) {
331 if (!afb_hsrv_add_alias(hsrv, "",
332 afb_common_rootdir_get_fd(), roothttp, -10, 1))
336 if (!afb_hsrv_add_handler(hsrv, rootbase,
337 afb_hswitch_one_page_api_redirect, NULL, -20))
343 static int add_interface(void *closure, const char *value)
345 struct afb_hsrv *hsrv = closure;
348 rc = afb_hsrv_add_interface(hsrv, value);
352 static struct afb_hsrv *start_http_server()
355 const char *uploaddir, *rootdir, *errs;
356 struct afb_hsrv *hsrv;
357 int cache_timeout, http_port;
358 struct json_object *junk;
361 rc = wrap_json_unpack(main_config, "{ss ss si s?i}",
362 "uploaddir", &uploaddir,
364 "cache-eol", &cache_timeout,
367 ERROR("Can't get HTTP server start config");
371 if (afb_hreq_init_download_path(uploaddir)) {
372 static const char fallback_uploaddir[] = "/tmp";
373 WARNING("unable to set the upload directory %s", uploaddir);
374 if (afb_hreq_init_download_path(fallback_uploaddir)) {
375 ERROR("unable to fallback to upload directory %s", fallback_uploaddir);
378 uploaddir = fallback_uploaddir;
381 hsrv = afb_hsrv_create();
383 ERROR("memory allocation failure");
387 if (!afb_hsrv_set_cache_timeout(hsrv, cache_timeout)
388 || !init_http_server(hsrv)) {
389 ERROR("initialisation of httpd failed");
394 rc = afb_hsrv_start(hsrv, 15);
396 ERROR("starting of httpd failed");
401 NOTICE("Serving rootdir=%s uploaddir=%s", rootdir, uploaddir);
403 /* check if port is set */
405 /* not set, check existing interfaces */
406 if (!json_object_object_get_ex(main_config, "interface", &junk)) {
407 ERROR("No port and no interface ");
410 rc = afb_hsrv_add_interface_tcp(hsrv, DEFAULT_BINDER_INTERFACE, (uint16_t) http_port);
412 ERROR("setting interface failed");
416 NOTICE("Browser URL= http://localhost:%d", http_port);
419 errs = run_for_config_array_opt("interface", add_interface, hsrv);
421 ERROR("setting interface %s failed", errs);
429 /*---------------------------------------------------------
431 +--------------------------------------------------------- */
433 static void exit_at_end()
438 static void wait_child(int signum, void* arg)
440 pid_t pid = (pid_t)(intptr_t)arg;
441 pid_t pidchld = childpid;
443 if (pidchld == pid) {
446 killpg(pidchld, SIGKILL);
447 waitpid(pidchld, NULL, 0);
448 jobs_exit(exit_at_end);
450 waitpid(pid, NULL, 0);
454 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
456 if (info->si_pid == childpid) {
457 switch (info->si_code) {
461 jobs_queue_lazy(0, 0, wait_child, (void*)(intptr_t)info->si_pid);
474 #define SUBST_CHAR '@'
475 #define SUBST_STR "@"
477 static char *instanciate_string(const char *arg, const char *port, const char *token)
479 char *resu, *it, *wr;
482 /* get the changes */
485 it = strchrnul(arg, SUBST_CHAR);
488 case 'p': chg++; dif += (int)strlen(port) - 2; break;
489 case 't': chg++; dif += (int)strlen(token) - 2; break;
490 case SUBST_CHAR: it++; chg++; dif--; break;
493 it = strchrnul(it, SUBST_CHAR);
496 /* return arg when no change */
500 /* allocates the result */
501 resu = malloc((it - arg) + dif + 1);
503 ERROR("out of memory");
507 /* instanciate the arguments */
510 it = strchrnul(arg, SUBST_CHAR);
511 wr = mempcpy(wr, arg, it - arg);
515 case 'p': wr = stpcpy(wr, port); break;
516 case 't': wr = stpcpy(wr, token); break;
517 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
518 case SUBST_CHAR: *wr++ = *it;
527 static int instanciate_environ(const char *port, const char *token)
529 extern char **environ;
533 /* instantiate the environment */
534 for (i = 0 ; environ[i] ; i++) {
535 repl = instanciate_string(environ[i], port, token);
543 static char **instanciate_command_args(struct json_object *exec, const char *port, const char *token)
549 /* allocates the result */
550 n = (int)json_object_array_length(exec);
551 result = malloc((n + 1) * sizeof * result);
553 ERROR("out of memory");
557 /* instanciate the arguments */
558 for (i = 0 ; i < n ; i++) {
559 repl = instanciate_string(json_object_get_string(json_object_array_get_idx(exec, i)), port, token);
572 static int execute_command()
574 struct json_object *exec, *oport, *otok;
575 struct sigaction siga;
581 /* check whether a command is to execute or not */
582 if (!json_object_object_get_ex(main_config, "exec", &exec))
588 /* install signal handler */
589 memset(&siga, 0, sizeof siga);
590 siga.sa_sigaction = on_sigchld;
591 siga.sa_flags = SA_SIGINFO;
592 sigaction(SIGCHLD, &siga, NULL);
599 /* compute the string for port */
600 if (json_object_object_get_ex(main_config, "port", &oport))
601 rc = snprintf(port, sizeof port, "%s", json_object_get_string(oport));
603 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
604 if (rc < 0 || rc >= (int)(sizeof port)) {
605 ERROR("port->txt failed");
608 /* instantiate arguments and environment */
609 if (json_object_object_get_ex(main_config, "token", &otok))
610 token = json_object_get_string(otok);
612 token = SUBST_STR"p";
613 args = instanciate_command_args(exec, port, token);
614 if (args && instanciate_environ(port, token) >= 0) {
618 execv(args[0], args);
619 ERROR("can't launch %s: %m", args[0]);
626 /*---------------------------------------------------------
628 +--------------------------------------------------------- */
632 struct afb_xreq xreq;
635 struct json_object *calls;
638 const char *callspec;
639 struct afb_session *session;
642 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
644 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
648 NOTICE("startup call %s returned %s (%s)", sreq->callspec, json_object_get_string(object), info);
649 json_object_put(object);
651 ERROR("startup call %s ERROR! %s (%s)", sreq->callspec, error, info);
656 static void startup_call_current(struct startup_req *sreq);
658 static void startup_call_unref(struct afb_xreq *xreq)
660 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
664 json_object_put(sreq->xreq.json);
665 if (++sreq->index < sreq->count)
666 startup_call_current(sreq);
668 afb_session_close(sreq->session);
669 afb_session_unref(sreq->session);
674 static struct afb_xreq_query_itf startup_xreq_itf =
676 .reply = startup_call_reply,
677 .unref = startup_call_unref
680 static void startup_call_current(struct startup_req *sreq)
682 const char *api, *verb, *json;
683 enum json_tokener_error jerr;
685 sreq->callspec = json_object_get_string(json_object_array_get_idx(sreq->calls, sreq->index)),
686 api = sreq->callspec;
687 verb = strchr(api, '/');
689 json = strchr(verb, ':');
691 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
692 afb_context_init_validated(&sreq->xreq.context, sreq->session, NULL, NULL);
693 sreq->api = strndup(api, verb - api);
694 sreq->verb = strndup(verb + 1, json - verb - 1);
695 sreq->xreq.request.called_api = sreq->api;
696 sreq->xreq.request.called_verb = sreq->verb;
697 sreq->xreq.json = json_tokener_parse_verbose(json + 1, &jerr);
698 if (sreq->api && sreq->verb && jerr == json_tokener_success) {
699 afb_xreq_process(&sreq->xreq, main_apiset);
704 ERROR("Bad call specification %s", sreq->callspec);
708 static void run_startup_calls()
710 struct json_object *calls;
711 struct startup_req *sreq;
714 if (json_object_object_get_ex(main_config, "call", &calls)
715 && json_object_is_type(calls, json_type_array)
716 && (count = (int)json_object_array_length(calls))) {
717 sreq = calloc(1, sizeof *sreq);
718 sreq->session = afb_session_create(3600);
722 startup_call_current(sreq);
726 /*---------------------------------------------------------
727 | job for starting the daemon
728 +--------------------------------------------------------- */
730 static void start(int signum, void *arg)
733 const char *tracereq = NULL, *traceapi = NULL, *traceevt = NULL,
734 #if !defined(REMOVE_LEGACY_TRACE)
735 *tracesvc = NULL, *traceditf = NULL,
737 *traceses = NULL, *traceglob = NULL;
739 const char *workdir, *rootdir, *token, *rootapi;
740 struct json_object *settings;
741 struct afb_hsrv *hsrv;
742 int max_session_count, session_timeout, api_timeout;
743 int no_httpd, http_port;
747 afb_debug("start-entry");
750 ERROR("start aborted: received signal %s", strsignal(signum));
757 rootapi = token = NULL;
758 rc = wrap_json_unpack(main_config, "{"
763 #if !defined(REMOVE_LEGACY_TRACE)
766 "s?s s?s s?s s?s s?s"
775 "apitimeout", &api_timeout,
776 "cntxtimeout", &session_timeout,
777 "session-max", &max_session_count,
779 "no-httpd", &no_httpd,
784 #if !defined(REMOVE_LEGACY_TRACE)
785 "tracesvc", &tracesvc,
786 "traceditf", &traceditf,
788 "tracereq", &tracereq,
789 "traceapi", &traceapi,
790 "traceevt", &traceevt,
791 "traceses", &traceses,
792 "traceglob", &traceglob,
797 ERROR("Unable to get start config");
801 /* initialize session handling */
802 if (afb_session_init(max_session_count, session_timeout)) {
803 ERROR("initialisation of session manager failed");
807 /* set the directories */
808 mkdir(workdir, S_IRWXU | S_IRGRP | S_IXGRP);
809 if (chdir(workdir) < 0) {
810 ERROR("Can't enter working dir %s", workdir);
813 if (afb_common_rootdir_set(rootdir) < 0) {
814 ERROR("failed to set common root directory %s", rootdir);
817 if (addenv_realpath("AFB_WORKDIR", "." /* resolved by realpath */)
818 || addenv_realpath("AFB_ROOTDIR", rootdir /* relative to current directory */)) {
819 ERROR("can't set DIR environment");
826 ERROR("no port is defined");
829 if (http_port == 0) {
830 ERROR("random port is not implemented");
833 if (addenv_int("AFB_PORT", http_port)
834 || addenv("AFB_TOKEN", token?:"")) {
835 ERROR("can't set HTTP environment");
840 /* configure the daemon */
841 afb_export_set_config(settings);
842 main_apiset = afb_apiset_create("main", api_timeout);
844 ERROR("can't create main api set");
847 if (afb_monitor_init(main_apiset, main_apiset) < 0) {
848 ERROR("failed to setup monitor");
852 if (afb_supervision_init(main_apiset, main_config) < 0) {
853 ERROR("failed to setup supervision");
861 afb_hook_create_xreq(NULL, NULL, NULL, afb_hook_flags_xreq_from_text(tracereq), NULL, NULL);
862 #if !defined(REMOVE_LEGACY_TRACE)
863 if (traceapi || tracesvc || traceditf)
864 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi)
865 | afb_hook_flags_legacy_ditf_from_text(traceditf)
866 | afb_hook_flags_legacy_svc_from_text(tracesvc), NULL, NULL);
869 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi), NULL, NULL);
872 afb_hook_create_evt(NULL, afb_hook_flags_evt_from_text(traceevt), NULL, NULL);
874 afb_hook_create_session(NULL, afb_hook_flags_session_from_text(traceses), NULL, NULL);
876 afb_hook_create_global(afb_hook_flags_global_from_text(traceglob), NULL, NULL);
879 /* load bindings and apis */
880 afb_debug("start-load");
881 #if WITH_DYNAMIC_BINDING
882 apiset_start_list("binding", afb_api_so_add_binding, "the binding");
883 apiset_start_list("ldpaths", afb_api_so_add_pathset_fails, "the binding path set");
884 apiset_start_list("weak-ldpaths", afb_api_so_add_pathset_nofails, "the weak binding path set");
886 apiset_start_list("auto-api", afb_autoset_add_any, "the automatic api path set");
887 #if WITH_DBUS_TRANSPARENCY
888 apiset_start_list("dbus-client", afb_api_dbus_add_client, "the afb-dbus client");
890 apiset_start_list("ws-client", afb_api_ws_add_client_weak, "the afb-websocket client");
892 DEBUG("Init config done");
894 /* start the services */
895 afb_debug("start-start");
896 #if !defined(NO_CALL_PERSONALITY)
897 personality((unsigned long)-1L);
899 if (afb_apiset_start_all_services(main_apiset) < 0)
902 /* export started apis */
903 apiset_start_list("ws-server", afb_api_ws_add_server, "the afb-websocket service");
904 #if WITH_DBUS_TRANSPARENCY
905 apiset_start_list("dbus-server", afb_api_dbus_add_server, "the afb-dbus service");
908 /* start the HTTP server */
909 afb_debug("start-http");
911 if (!afb_hreq_init_cookie(http_port, rootapi, session_timeout)) {
912 ERROR("initialisation of HTTP cookies failed");
916 hsrv = start_http_server();
921 /* run the startup calls */
922 afb_debug("start-call");
925 /* run the command */
926 afb_debug("start-exec");
927 if (execute_command(http_port, token) < 0)
931 sd_notify(1, "READY=1");
933 /* activate the watchdog */
935 if (watchdog_activate() < 0)
936 ERROR("can't start the watchdog");
944 /*---------------------------------------------------------
946 | Parse option and launch action
947 +--------------------------------------------------------- */
949 int main(int argc, char *argv[])
951 struct json_object *obj;
952 afb_debug("main-entry");
954 // ------------- Build session handler & init config -------
955 main_config = afb_args_parse(argc, argv);
956 if (sig_monitor_init(
957 !json_object_object_get_ex(main_config, "trap-faults", &obj)
958 || json_object_get_boolean(obj)) < 0) {
959 ERROR("failed to initialise signal handlers");
964 if (json_object_object_get_ex(main_config, "name", &obj)) {
965 verbose_set_name(json_object_get_string(obj), 0);
966 process_name_set_name(json_object_get_string(obj));
967 process_name_replace_cmdline(argv, json_object_get_string(obj));
969 afb_debug("main-args");
971 // --------- run -----------
973 INFO("running with pid %d", getpid());
975 /* set the daemon environment */
978 afb_debug("main-start");
980 /* enter job processing */
981 jobs_start(3, 0, 100, start, NULL);
982 WARNING("hoops returned from jobs_enter! [report bug]");