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-export.h"
56 #include "afb-monitor.h"
58 #include "afb-hook-flags.h"
59 #include "afb-debug.h"
60 #include "process-name.h"
61 #include "wrap-json.h"
62 #if defined(WITH_SUPERVISION)
63 # include "afb-supervision.h"
67 if SELF_PGROUP == 0 the launched command is the group leader
68 if SELF_PGROUP != 0 afb-daemon is the group leader
72 struct afb_apiset *main_apiset;
73 struct json_object *main_config;
75 static pid_t childpid;
77 /*----------------------------------------------------------
78 | helpers for handling list of arguments
79 +--------------------------------------------------------- */
81 static const char *run_for_config_array_opt(const char *name,
82 int (*run) (void *closure, const char *value),
86 struct json_object *array, *value;
88 if (json_object_object_get_ex(main_config, name, &array)) {
89 if (!json_object_is_type(array, json_type_array))
90 return json_object_get_string(array);
91 n = (int)json_object_array_length(array);
92 for (i = 0 ; i < n ; i++) {
93 value = json_object_array_get_idx(array, i);
94 rc = run(closure, json_object_get_string(value));
96 return json_object_get_string(value);
102 static int run_start(void *closure, const char *value)
104 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set) = closure;
105 return starter(value, main_apiset, main_apiset) >= 0;
108 static void apiset_start_list(const char *name,
109 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set),
112 const char *item = run_for_config_array_opt(name, run_start, starter);
114 ERROR("can't start %s %s", message, item);
119 /*----------------------------------------------------------
121 | Handles on exit specific actions
122 +--------------------------------------------------------- */
123 static void exit_handler()
125 struct sigaction siga;
127 memset(&siga, 0, sizeof siga);
128 siga.sa_handler = SIG_IGN;
129 sigaction(SIGTERM, &siga, NULL);
133 else if (childpid > 0)
134 killpg(childpid, SIGTERM);
137 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
139 NOTICE("Received SIGTERM");
143 static void on_sighup(int signum, siginfo_t *info, void *uctx)
145 NOTICE("Received SIGHUP");
149 static void setup_daemon()
151 struct sigaction siga;
153 /* install signal handlers */
154 memset(&siga, 0, sizeof siga);
155 siga.sa_flags = SA_SIGINFO;
157 siga.sa_sigaction = on_sigterm;
158 sigaction(SIGTERM, &siga, NULL);
160 siga.sa_sigaction = on_sighup;
161 sigaction(SIGHUP, &siga, NULL);
164 atexit(exit_handler);
166 /* ignore any SIGPIPE */
167 signal(SIGPIPE, SIG_IGN);
170 /*----------------------------------------------------------
172 | set the process in background
173 +--------------------------------------------------------- */
174 static void daemonize()
182 wrap_json_unpack(main_config, "{s?b s?s}", "daemon", &daemon, "output", &output);
185 fd = open(output, O_WRONLY | O_APPEND | O_CREAT, 0640);
187 ERROR("Can't open output %s", output);
193 INFO("entering background mode");
197 ERROR("Failed to fork daemon process");
204 /* closes the input */
206 NOTICE("Redirecting output to %s", output);
214 /* after that ctrl+C still works */
218 /*---------------------------------------------------------
220 | Handles the HTTP server
221 +--------------------------------------------------------- */
222 static int init_alias(void *closure, const char *spec)
224 struct afb_hsrv *hsrv = closure;
225 char *path = strchr(spec, ':');
228 ERROR("Missing ':' in alias %s. Alias ignored", spec);
232 INFO("Alias for url=%s to path=%s", spec, path);
233 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
237 static int init_http_server(struct afb_hsrv *hsrv)
240 const char *rootapi, *roothttp, *rootbase;
243 rc = wrap_json_unpack(main_config, "{ss ss s?s}",
245 "rootbase", &rootbase,
246 "roothttp", &roothttp);
248 ERROR("Can't get HTTP server config");
252 if (!afb_hsrv_add_handler(hsrv, rootapi,
253 afb_hswitch_websocket_switch, main_apiset, 20))
256 if (!afb_hsrv_add_handler(hsrv, rootapi,
257 afb_hswitch_apis, main_apiset, 10))
260 if (run_for_config_array_opt("alias", init_alias, hsrv))
263 if (roothttp != NULL) {
264 if (!afb_hsrv_add_alias(hsrv, "",
265 afb_common_rootdir_get_fd(), roothttp, -10, 1))
269 if (!afb_hsrv_add_handler(hsrv, rootbase,
270 afb_hswitch_one_page_api_redirect, NULL, -20))
276 static struct afb_hsrv *start_http_server()
279 const char *uploaddir, *rootdir;
280 struct afb_hsrv *hsrv;
281 int cache_timeout, http_port;
283 rc = wrap_json_unpack(main_config, "{ss ss si si}",
284 "uploaddir", &uploaddir,
286 "cache-eol", &cache_timeout,
289 ERROR("Can't get HTTP server start config");
293 if (afb_hreq_init_download_path(uploaddir)) {
294 ERROR("unable to set the upload directory %s", uploaddir);
298 hsrv = afb_hsrv_create();
300 ERROR("memory allocation failure");
304 if (!afb_hsrv_set_cache_timeout(hsrv, cache_timeout)
305 || !init_http_server(hsrv)) {
306 ERROR("initialisation of httpd failed");
311 NOTICE("Waiting port=%d rootdir=%s", http_port, rootdir);
312 NOTICE("Browser URL= http://localhost:%d", http_port);
314 rc = afb_hsrv_start(hsrv, (uint16_t) http_port, 15);
316 ERROR("starting of httpd failed");
324 /*---------------------------------------------------------
326 +--------------------------------------------------------- */
328 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
330 if (info->si_pid == childpid) {
331 switch (info->si_code) {
337 killpg(info->si_pid, SIGKILL);
338 waitpid(info->si_pid, NULL, 0);
350 #define SUBST_CHAR '@'
351 #define SUBST_STR "@"
353 static char *instanciate_string(const char *arg, const char *port, const char *token)
355 char *resu, *it, *wr;
358 /* get the changes */
361 it = strchrnul(arg, SUBST_CHAR);
364 case 'p': chg++; dif += (int)strlen(port) - 2; break;
365 case 't': chg++; dif += (int)strlen(token) - 2; break;
366 case SUBST_CHAR: it++; chg++; dif--; break;
369 it = strchrnul(it, SUBST_CHAR);
372 /* return arg when no change */
376 /* allocates the result */
377 resu = malloc((it - arg) + dif + 1);
379 ERROR("out of memory");
383 /* instanciate the arguments */
386 it = strchrnul(arg, SUBST_CHAR);
387 wr = mempcpy(wr, arg, it - arg);
391 case 'p': wr = stpcpy(wr, port); break;
392 case 't': wr = stpcpy(wr, token); break;
393 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
394 case SUBST_CHAR: *wr++ = *it;
403 static int instanciate_environ(const char *port, const char *token)
405 extern char **environ;
409 /* instantiate the environment */
410 for (i = 0 ; environ[i] ; i++) {
411 repl = instanciate_string(environ[i], port, token);
419 static char **instanciate_command_args(struct json_object *exec, const char *port, const char *token)
425 /* allocates the result */
426 n = (int)json_object_array_length(exec);
427 result = malloc((n + 1) * sizeof * result);
429 ERROR("out of memory");
433 /* instanciate the arguments */
434 for (i = 0 ; i < n ; i++) {
435 repl = instanciate_string(json_object_get_string(json_object_array_get_idx(exec, i)), port, token);
448 static int execute_command()
450 struct json_object *exec, *oport;
451 struct sigaction siga;
457 /* check whether a command is to execute or not */
458 if (!json_object_object_get_ex(main_config, "exec", &exec))
464 /* install signal handler */
465 memset(&siga, 0, sizeof siga);
466 siga.sa_sigaction = on_sigchld;
467 siga.sa_flags = SA_SIGINFO;
468 sigaction(SIGCHLD, &siga, NULL);
475 /* compute the string for port */
476 if (json_object_object_get_ex(main_config, "port", &oport))
477 rc = snprintf(port, sizeof port, "%s", json_object_get_string(oport));
479 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
480 if (rc < 0 || rc >= (int)(sizeof port)) {
481 ERROR("port->txt failed");
484 /* instanciate arguments and environment */
485 token = afb_session_initial_token();
486 args = instanciate_command_args(exec, port, token);
487 if (args && instanciate_environ(port, token) >= 0) {
491 execv(args[0], args);
492 ERROR("can't launch %s: %m", args[0]);
499 /*---------------------------------------------------------
501 +--------------------------------------------------------- */
505 struct afb_xreq xreq;
508 struct json_object *calls;
511 const char *callspec;
512 struct afb_session *session;
515 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
517 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
521 NOTICE("startup call %s returned %s (%s)", sreq->callspec, json_object_get_string(object), info);
522 json_object_put(object);
524 ERROR("startup call %s ERROR! %s (%s)", sreq->callspec, error, info);
529 static void startup_call_current(struct startup_req *sreq);
531 static void startup_call_unref(struct afb_xreq *xreq)
533 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
537 json_object_put(sreq->xreq.json);
538 if (++sreq->index < sreq->count)
539 startup_call_current(sreq);
541 afb_session_close(sreq->session);
542 afb_session_unref(sreq->session);
547 static struct afb_xreq_query_itf startup_xreq_itf =
549 .reply = startup_call_reply,
550 .unref = startup_call_unref
553 static void startup_call_current(struct startup_req *sreq)
555 const char *api, *verb, *json;
556 enum json_tokener_error jerr;
558 sreq->callspec = json_object_get_string(json_object_array_get_idx(sreq->calls, sreq->index)),
559 api = sreq->callspec;
560 verb = strchr(api, '/');
562 json = strchr(verb, ':');
564 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
565 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
566 sreq->xreq.context.validated = 1;
567 sreq->api = strndup(api, verb - api);
568 sreq->verb = strndup(verb + 1, json - verb - 1);
569 sreq->xreq.request.called_api = sreq->api;
570 sreq->xreq.request.called_verb = sreq->verb;
571 sreq->xreq.json = json_tokener_parse_verbose(json + 1, &jerr);
572 if (sreq->api && sreq->verb && jerr == json_tokener_success) {
573 afb_xreq_process(&sreq->xreq, main_apiset);
578 ERROR("Bad call specification %s", sreq->callspec);
582 static void run_startup_calls()
584 struct json_object *calls;
585 struct startup_req *sreq;
588 if (json_object_object_get_ex(main_config, "call", &calls)
589 && json_object_is_type(calls, json_type_array)
590 && (count = (int)json_object_array_length(calls))) {
591 sreq = calloc(1, sizeof *sreq);
592 sreq->session = afb_session_create(3600);
596 startup_call_current(sreq);
600 /*---------------------------------------------------------
601 | job for starting the daemon
602 +--------------------------------------------------------- */
604 static void start(int signum, void *arg)
606 const char *tracereq, *traceapi, *traceevt, *traceses, *tracesvc, *traceditf, *traceglob;
607 const char *workdir, *rootdir, *token, *rootapi;
608 struct json_object *settings;
609 struct afb_hsrv *hsrv;
610 int max_session_count, session_timeout, api_timeout;
611 int no_httpd, http_port;
615 afb_debug("start-entry");
618 ERROR("start aborted: received signal %s", strsignal(signum));
623 token = rootapi = tracesvc = traceditf = tracereq =
624 traceapi = traceevt = traceses = traceglob = NULL;
625 no_httpd = http_port = 0;
626 rc = wrap_json_unpack(main_config, "{"
631 #if !defined(REMOVE_LEGACY_TRACE)
634 "s?s s?s s?s s?s s?s"
641 "apitimeout", &api_timeout,
642 "cntxtimeout", &session_timeout,
643 "session-max", &max_session_count,
645 "no-httpd", &no_httpd,
650 #if !defined(REMOVE_LEGACY_TRACE)
651 "tracesvc", &tracesvc,
652 "traceditf", &traceditf,
654 "tracereq", &tracereq,
655 "traceapi", &traceapi,
656 "traceevt", &traceevt,
657 "traceses", &traceses,
658 "traceglob", &traceglob
661 ERROR("Unable to get start config");
665 /* set the directories */
666 mkdir(workdir, S_IRWXU | S_IRGRP | S_IXGRP);
667 if (chdir(workdir) < 0) {
668 ERROR("Can't enter working dir %s", workdir);
671 if (afb_common_rootdir_set(rootdir) < 0) {
672 ERROR("failed to set common root directory");
676 /* configure the daemon */
677 afb_export_set_config(settings);
678 if (afb_session_init(max_session_count, session_timeout, token)) {
679 ERROR("initialisation of session manager failed");
682 main_apiset = afb_apiset_create("main", api_timeout);
684 ERROR("can't create main api set");
687 if (afb_monitor_init(main_apiset, main_apiset) < 0) {
688 ERROR("failed to setup monitor");
691 #if defined(WITH_SUPERVISION)
692 if (afb_supervision_init(main_apiset, main_config) < 0) {
693 ERROR("failed to setup supervision");
700 afb_hook_create_xreq(NULL, NULL, NULL, afb_hook_flags_xreq_from_text(tracereq), NULL, NULL);
701 #if !defined(REMOVE_LEGACY_TRACE)
702 if (traceapi || tracesvc || traceditf)
703 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi)
704 | afb_hook_flags_legacy_ditf_from_text(traceditf)
705 | afb_hook_flags_legacy_svc_from_text(tracesvc), NULL, NULL);
708 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi), NULL, NULL);
711 afb_hook_create_evt(NULL, afb_hook_flags_evt_from_text(traceevt), NULL, NULL);
713 afb_hook_create_session(NULL, afb_hook_flags_session_from_text(traceses), NULL, NULL);
715 afb_hook_create_global(afb_hook_flags_global_from_text(traceglob), NULL, NULL);
718 afb_debug("start-load");
719 apiset_start_list("binding", afb_api_so_add_binding, "the binding");
720 apiset_start_list("ldpaths", afb_api_so_add_pathset_fails, "the binding path set");
721 apiset_start_list("weak-ldpaths", afb_api_so_add_pathset_nofails, "the weak binding path set");
722 apiset_start_list("auto-api", afb_autoset_add_any, "the automatic api path set");
723 apiset_start_list("ws-server", afb_api_ws_add_server, "the afb-websocket service");
724 #if defined(WITH_DBUS_TRANSPARENCY)
725 apiset_start_list("dbus-server", afb_api_dbus_add_server, "the afb-dbus service");
726 apiset_start_list("dbus-client", afb_api_dbus_add_client, "the afb-dbus client");
728 apiset_start_list("ws-client", afb_api_ws_add_client_weak, "the afb-websocket client");
730 DEBUG("Init config done");
732 /* start the services */
733 afb_debug("start-start");
734 #if !defined(NO_CALL_PERSONALITY)
735 personality((unsigned long)-1L);
737 if (afb_apiset_start_all_services(main_apiset) < 0)
740 /* start the HTTP server */
741 afb_debug("start-http");
743 if (http_port <= 0) {
744 ERROR("no port is defined");
748 if (!afb_hreq_init_cookie(http_port, rootapi, session_timeout)) {
749 ERROR("initialisation of HTTP cookies failed");
753 hsrv = start_http_server();
758 /* run the startup calls */
759 afb_debug("start-call");
762 /* run the command */
763 afb_debug("start-exec");
764 if (execute_command() < 0)
768 sd_notify(1, "READY=1");
774 /*---------------------------------------------------------
776 | Parse option and launch action
777 +--------------------------------------------------------- */
779 int main(int argc, char *argv[])
781 struct json_object *name;
782 afb_debug("main-entry");
784 // ------------- Build session handler & init config -------
785 main_config = afb_config_parse_arguments(argc, argv);
786 if (json_object_object_get_ex(main_config, "name", &name)) {
787 verbose_set_name(json_object_get_string(name), 0);
788 process_name_set_name(json_object_get_string(name));
789 process_name_replace_cmdline(argv, json_object_get_string(name));
791 afb_debug("main-args");
793 // --------- run -----------
795 INFO("running with pid %d", getpid());
797 /* set the daemon environment */
800 afb_debug("main-start");
802 /* enter job processing */
803 jobs_start(3, 0, 50, start, NULL);
804 WARNING("hoops returned from jobs_enter! [report bug]");