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-monitor.h"
57 #include "afb-hook-flags.h"
58 #include "afb-debug.h"
59 #include "process-name.h"
60 #include "wrap-json.h"
61 #if defined(WITH_SUPERVISION)
62 # include "afb-supervision.h"
66 if SELF_PGROUP == 0 the launched command is the group leader
67 if SELF_PGROUP != 0 afb-daemon is the group leader
71 struct afb_apiset *main_apiset;
72 struct json_object *main_config;
74 static pid_t childpid;
76 /*----------------------------------------------------------
77 | helpers for handling list of arguments
78 +--------------------------------------------------------- */
80 static const char *run_for_config_array_opt(const char *name,
81 int (*run) (void *closure, const char *value),
85 struct json_object *array, *value;
87 if (json_object_object_get_ex(main_config, name, &array)) {
88 if (!json_object_is_type(array, json_type_array))
89 return json_object_get_string(array);
90 n = (int)json_object_array_length(array);
91 for (i = 0 ; i < n ; i++) {
92 value = json_object_array_get_idx(array, i);
93 rc = run(closure, json_object_get_string(value));
95 return json_object_get_string(value);
101 static int run_start(void *closure, const char *value)
103 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set) = closure;
104 return starter(value, main_apiset, main_apiset) >= 0;
107 static void apiset_start_list(const char *name,
108 int (*starter) (const char *value, struct afb_apiset *declare_set, struct afb_apiset *call_set),
111 const char *item = run_for_config_array_opt(name, run_start, starter);
113 ERROR("can't start %s %s", message, item);
118 /*----------------------------------------------------------
120 | Handles on exit specific actions
121 +--------------------------------------------------------- */
122 static void exit_handler()
124 struct sigaction siga;
126 memset(&siga, 0, sizeof siga);
127 siga.sa_handler = SIG_IGN;
128 sigaction(SIGTERM, &siga, NULL);
132 else if (childpid > 0)
133 killpg(childpid, SIGTERM);
136 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
138 NOTICE("Received SIGTERM");
142 static void on_sighup(int signum, siginfo_t *info, void *uctx)
144 NOTICE("Received SIGHUP");
148 static void setup_daemon()
150 struct sigaction siga;
152 /* install signal handlers */
153 memset(&siga, 0, sizeof siga);
154 siga.sa_flags = SA_SIGINFO;
156 siga.sa_sigaction = on_sigterm;
157 sigaction(SIGTERM, &siga, NULL);
159 siga.sa_sigaction = on_sighup;
160 sigaction(SIGHUP, &siga, NULL);
163 atexit(exit_handler);
165 /* ignore any SIGPIPE */
166 signal(SIGPIPE, SIG_IGN);
169 /*----------------------------------------------------------
171 | set the process in background
172 +--------------------------------------------------------- */
173 static void daemonize()
181 wrap_json_unpack(main_config, "{s?b s?s}", "daemon", &daemon, "output", &output);
184 fd = open(output, O_WRONLY | O_APPEND | O_CREAT, 0640);
186 ERROR("Can't open output %s", output);
192 INFO("entering background mode");
196 ERROR("Failed to fork daemon process");
203 /* closes the input */
205 NOTICE("Redirecting output to %s", output);
213 /* after that ctrl+C still works */
217 /*---------------------------------------------------------
219 | Handles the HTTP server
220 +--------------------------------------------------------- */
221 static int init_alias(void *closure, const char *spec)
223 struct afb_hsrv *hsrv = closure;
224 char *path = strchr(spec, ':');
227 ERROR("Missing ':' in alias %s. Alias ignored", spec);
231 INFO("Alias for url=%s to path=%s", spec, path);
232 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
236 static int init_http_server(struct afb_hsrv *hsrv)
239 const char *rootapi, *roothttp, *rootbase;
242 rc = wrap_json_unpack(main_config, "{ss ss s?s}",
244 "rootbase", &rootbase,
245 "roothttp", &roothttp);
247 ERROR("Can't get HTTP server config");
251 if (!afb_hsrv_add_handler(hsrv, rootapi,
252 afb_hswitch_websocket_switch, main_apiset, 20))
255 if (!afb_hsrv_add_handler(hsrv, rootapi,
256 afb_hswitch_apis, main_apiset, 10))
259 if (run_for_config_array_opt("alias", init_alias, hsrv))
262 if (roothttp != NULL) {
263 if (!afb_hsrv_add_alias(hsrv, "",
264 afb_common_rootdir_get_fd(), roothttp, -10, 1))
268 if (!afb_hsrv_add_handler(hsrv, rootbase,
269 afb_hswitch_one_page_api_redirect, NULL, -20))
275 static struct afb_hsrv *start_http_server()
278 const char *uploaddir, *rootdir;
279 struct afb_hsrv *hsrv;
280 int cache_timeout, http_port;
282 rc = wrap_json_unpack(main_config, "{ss ss si si}",
283 "uploaddir", &uploaddir,
285 "cache-eol", &cache_timeout,
288 ERROR("Can't get HTTP server start config");
292 if (afb_hreq_init_download_path(uploaddir)) {
293 ERROR("unable to set the upload directory %s", uploaddir);
297 hsrv = afb_hsrv_create();
299 ERROR("memory allocation failure");
303 if (!afb_hsrv_set_cache_timeout(hsrv, cache_timeout)
304 || !init_http_server(hsrv)) {
305 ERROR("initialisation of httpd failed");
310 NOTICE("Waiting port=%d rootdir=%s", http_port, rootdir);
311 NOTICE("Browser URL= http://localhost:%d", http_port);
313 rc = afb_hsrv_start(hsrv, (uint16_t) http_port, 15);
315 ERROR("starting of httpd failed");
323 /*---------------------------------------------------------
325 +--------------------------------------------------------- */
327 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
329 if (info->si_pid == childpid) {
330 switch (info->si_code) {
336 killpg(info->si_pid, SIGKILL);
337 waitpid(info->si_pid, NULL, 0);
349 #define SUBST_CHAR '@'
350 #define SUBST_STR "@"
352 static char *instanciate_string(const char *arg, const char *port, const char *token)
354 char *resu, *it, *wr;
357 /* get the changes */
360 it = strchrnul(arg, SUBST_CHAR);
363 case 'p': chg++; dif += (int)strlen(port) - 2; break;
364 case 't': chg++; dif += (int)strlen(token) - 2; break;
365 case SUBST_CHAR: it++; chg++; dif--; break;
368 it = strchrnul(it, SUBST_CHAR);
371 /* return arg when no change */
375 /* allocates the result */
376 resu = malloc((it - arg) + dif + 1);
378 ERROR("out of memory");
382 /* instanciate the arguments */
385 it = strchrnul(arg, SUBST_CHAR);
386 wr = mempcpy(wr, arg, it - arg);
390 case 'p': wr = stpcpy(wr, port); break;
391 case 't': wr = stpcpy(wr, token); break;
392 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
393 case SUBST_CHAR: *wr++ = *it;
402 static int instanciate_environ(const char *port, const char *token)
404 extern char **environ;
408 /* instantiate the environment */
409 for (i = 0 ; environ[i] ; i++) {
410 repl = instanciate_string(environ[i], port, token);
418 static char **instanciate_command_args(struct json_object *exec, const char *port, const char *token)
424 /* allocates the result */
425 n = (int)json_object_array_length(exec);
426 result = malloc((n + 1) * sizeof * result);
428 ERROR("out of memory");
432 /* instanciate the arguments */
433 for (i = 0 ; i < n ; i++) {
434 repl = instanciate_string(json_object_get_string(json_object_array_get_idx(exec, i)), port, token);
447 static int execute_command()
449 struct json_object *exec, *oport;
450 struct sigaction siga;
456 /* check whether a command is to execute or not */
457 if (!json_object_object_get_ex(main_config, "exec", &exec))
463 /* install signal handler */
464 memset(&siga, 0, sizeof siga);
465 siga.sa_sigaction = on_sigchld;
466 siga.sa_flags = SA_SIGINFO;
467 sigaction(SIGCHLD, &siga, NULL);
474 /* compute the string for port */
475 if (json_object_object_get_ex(main_config, "port", &oport))
476 rc = snprintf(port, sizeof port, "%s", json_object_get_string(oport));
478 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
479 if (rc < 0 || rc >= (int)(sizeof port)) {
480 ERROR("port->txt failed");
483 /* instanciate arguments and environment */
484 token = afb_session_initial_token();
485 args = instanciate_command_args(exec, port, token);
486 if (args && instanciate_environ(port, token) >= 0) {
490 execv(args[0], args);
491 ERROR("can't launch %s: %m", args[0]);
498 /*---------------------------------------------------------
500 +--------------------------------------------------------- */
504 struct afb_xreq xreq;
507 struct json_object *calls;
510 const char *callspec;
511 struct afb_session *session;
514 static void startup_call_reply(struct afb_xreq *xreq, struct json_object *object, const char *error, const char *info)
516 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
520 NOTICE("startup call %s returned %s (%s)", sreq->callspec, json_object_get_string(object), info);
521 json_object_put(object);
523 ERROR("startup call %s ERROR! %s (%s)", sreq->callspec, error, info);
528 static void startup_call_current(struct startup_req *sreq);
530 static void startup_call_unref(struct afb_xreq *xreq)
532 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
536 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;
557 sreq->callspec = json_object_get_string(json_object_array_get_idx(sreq->calls, sreq->index)),
558 api = sreq->callspec;
559 verb = strchr(api, '/');
561 json = strchr(verb, ':');
563 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
564 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
565 sreq->xreq.context.validated = 1;
566 sreq->api = strndup(api, verb - api);
567 sreq->verb = strndup(verb + 1, json - verb - 1);
568 sreq->xreq.request.called_api = sreq->api;
569 sreq->xreq.request.called_verb = sreq->verb;
570 sreq->xreq.json = json_tokener_parse(json + 1);
571 if (sreq->api && sreq->verb && sreq->xreq.json) {
572 afb_xreq_process(&sreq->xreq, main_apiset);
577 ERROR("Bad call specification %s", sreq->callspec);
581 static void run_startup_calls()
583 struct json_object *calls;
584 struct startup_req *sreq;
587 if (json_object_object_get_ex(main_config, "call", &calls)
588 && json_object_is_type(calls, json_type_array)
589 && (count = (int)json_object_array_length(calls))) {
590 sreq = calloc(1, sizeof *sreq);
591 sreq->session = afb_session_create(3600);
595 startup_call_current(sreq);
599 /*---------------------------------------------------------
600 | job for starting the daemon
601 +--------------------------------------------------------- */
603 static void start(int signum, void *arg)
605 const char *tracereq, *traceapi, *traceevt, *traceses, *tracesvc, *traceditf, *traceglob;
606 const char *workdir, *rootdir, *token, *rootapi;
607 struct afb_hsrv *hsrv;
608 int max_session_count, session_timeout, api_timeout;
609 int no_httpd, http_port;
613 afb_debug("start-entry");
616 ERROR("start aborted: received signal %s", strsignal(signum));
620 token = rootapi = tracesvc = traceditf = tracereq =
621 traceapi = traceevt = traceses = traceglob = NULL;
622 no_httpd = http_port = 0;
623 rc = wrap_json_unpack(main_config, "{"
627 #if !defined(REMOVE_LEGACY_TRACE)
630 "s?s s?s s?s s?s s?s"
637 "apitimeout", &api_timeout,
638 "cntxtimeout", &session_timeout,
639 "session-max", &max_session_count,
641 "no-httpd", &no_httpd,
645 #if !defined(REMOVE_LEGACY_TRACE)
646 "tracesvc", &tracesvc,
647 "traceditf", &traceditf,
649 "tracereq", &tracereq,
650 "traceapi", &traceapi,
651 "traceevt", &traceevt,
652 "traceses", &traceses,
653 "traceglob", &traceglob
656 ERROR("Unable to get start config");
660 /* set the directories */
661 mkdir(workdir, S_IRWXU | S_IRGRP | S_IXGRP);
662 if (chdir(workdir) < 0) {
663 ERROR("Can't enter working dir %s", workdir);
666 if (afb_common_rootdir_set(rootdir) < 0) {
667 ERROR("failed to set common root directory");
671 /* configure the daemon */
672 if (afb_session_init(max_session_count, session_timeout, token)) {
673 ERROR("initialisation of session manager failed");
676 main_apiset = afb_apiset_create("main", api_timeout);
678 ERROR("can't create main api set");
681 if (afb_monitor_init(main_apiset, main_apiset) < 0) {
682 ERROR("failed to setup monitor");
685 #if defined(WITH_SUPERVISION)
686 if (afb_supervision_init(main_apiset, main_config) < 0) {
687 ERROR("failed to setup supervision");
694 afb_hook_create_xreq(NULL, NULL, NULL, afb_hook_flags_xreq_from_text(tracereq), NULL, NULL);
695 #if !defined(REMOVE_LEGACY_TRACE)
696 if (traceapi || tracesvc || traceditf)
697 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi)
698 | afb_hook_flags_legacy_ditf_from_text(traceditf)
699 | afb_hook_flags_legacy_svc_from_text(tracesvc), NULL, NULL);
702 afb_hook_create_api(NULL, afb_hook_flags_api_from_text(traceapi), NULL, NULL);
705 afb_hook_create_evt(NULL, afb_hook_flags_evt_from_text(traceevt), NULL, NULL);
707 afb_hook_create_session(NULL, afb_hook_flags_session_from_text(traceses), NULL, NULL);
709 afb_hook_create_global(afb_hook_flags_global_from_text(traceglob), NULL, NULL);
712 afb_debug("start-load");
713 apiset_start_list("binding", afb_api_so_add_binding, "the binding");
714 apiset_start_list("ldpaths", afb_api_so_add_pathset_fails, "the binding path set");
715 apiset_start_list("weak-ldpaths", afb_api_so_add_pathset_nofails, "the weak binding path set");
716 apiset_start_list("auto-api", afb_autoset_add_any, "the automatic api path set");
717 apiset_start_list("ws-server", afb_api_ws_add_server, "the afb-websocket service");
718 #if defined(WITH_DBUS_TRANSPARENCY)
719 apiset_start_list("dbus-server", afb_api_dbus_add_server, "the afb-dbus service");
720 apiset_start_list("dbus-client", afb_api_dbus_add_client, "the afb-dbus client");
722 apiset_start_list("ws-client", afb_api_ws_add_client_weak, "the afb-websocket client");
724 DEBUG("Init config done");
726 /* start the services */
727 afb_debug("start-start");
728 #if !defined(NO_CALL_PERSONALITY)
729 personality((unsigned long)-1L);
731 if (afb_apiset_start_all_services(main_apiset) < 0)
734 /* start the HTTP server */
735 afb_debug("start-http");
737 if (http_port <= 0) {
738 ERROR("no port is defined");
742 if (!afb_hreq_init_cookie(http_port, rootapi, session_timeout)) {
743 ERROR("initialisation of HTTP cookies failed");
747 hsrv = start_http_server();
752 /* run the startup calls */
753 afb_debug("start-call");
756 /* run the command */
757 afb_debug("start-exec");
758 if (execute_command() < 0)
762 sd_notify(1, "READY=1");
768 /*---------------------------------------------------------
770 | Parse option and launch action
771 +--------------------------------------------------------- */
773 int main(int argc, char *argv[])
775 struct json_object *name;
776 afb_debug("main-entry");
778 // ------------- Build session handler & init config -------
779 main_config = afb_config_parse_arguments(argc, argv);
780 if (json_object_object_get_ex(main_config, "name", &name)) {
781 verbose_set_name(json_object_get_string(name), 0);
782 process_name_set_name(json_object_get_string(name));
783 process_name_replace_cmdline(argv, json_object_get_string(name));
785 afb_debug("main-args");
787 // --------- run -----------
789 INFO("running with pid %d", getpid());
791 /* set the daemon environment */
794 afb_debug("main-start");
796 /* enter job processing */
797 jobs_start(3, 0, 50, start, NULL);
798 WARNING("hoops returned from jobs_enter! [report bug]");