2 * Copyright (C) 2015, 2016, 2017 "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.
20 #define AFB_BINDING_PRAGMA_NO_VERBOSE_MACRO
32 #include <json-c/json.h>
34 #include <systemd/sd-daemon.h>
36 #include "afb-config.h"
37 #include "afb-hswitch.h"
38 #include "afb-apiset.h"
39 #include "afb-api-so.h"
40 #include "afb-api-dbus.h"
41 #include "afb-api-ws.h"
46 #include "afb-session.h"
48 #include "afb-common.h"
49 #include "afb-monitor.h"
54 if SELF_PGROUP == 0 the launched command is the group leader
55 if SELF_PGROUP != 0 afb-daemon is the group leader
59 struct afb_apiset *main_apiset;
61 static struct afb_config *config;
62 static pid_t childpid;
64 /*----------------------------------------------------------
65 | helpers for handling list of arguments
66 +--------------------------------------------------------- */
69 * Calls the callback 'run' for each value of the 'list'
70 * until the callback returns 0 or the end of the list is reached.
71 * Returns either NULL if the end of the list is reached or a pointer
72 * to the item whose value made 'run' return 0.
73 * 'closure' is used for passing user data.
75 static struct afb_config_list *run_for_list(struct afb_config_list *list,
76 int (*run) (void *closure, char *value),
79 while (list && run(closure, list->value))
84 static int run_start(void *closure, char *value)
86 int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
87 return starter(value, main_apiset) >= 0;
90 static void apiset_start_list(struct afb_config_list *list,
91 int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
93 list = run_for_list(list, run_start, starter);
95 ERROR("can't start %s %s", message, list->value);
100 /*----------------------------------------------------------
102 | Handles on exit specific actions
103 +--------------------------------------------------------- */
104 static void exit_handler()
106 struct sigaction siga;
108 memset(&siga, 0, sizeof siga);
109 siga.sa_handler = SIG_IGN;
110 sigaction(SIGTERM, &siga, NULL);
114 else if (childpid > 0)
115 killpg(childpid, SIGTERM);
118 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
120 NOTICE("Received SIGTERM");
124 static void on_sighup(int signum, siginfo_t *info, void *uctx)
126 NOTICE("Received SIGHUP");
130 static void setup_daemon()
132 struct sigaction siga;
134 /* install signal handlers */
135 memset(&siga, 0, sizeof siga);
136 siga.sa_flags = SA_SIGINFO;
138 siga.sa_sigaction = on_sigterm;
139 sigaction(SIGTERM, &siga, NULL);
141 siga.sa_sigaction = on_sighup;
142 sigaction(SIGHUP, &siga, NULL);
145 atexit(exit_handler);
147 /* ignore any SIGPIPE */
148 signal(SIGPIPE, SIG_IGN);
151 /*----------------------------------------------------------
153 | set the process in background
154 +--------------------------------------------------------- */
155 static void daemonize()
160 // open /dev/console to redirect output messAFBes
161 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
163 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
166 // fork process when running background mode
169 // if fail nothing much to do
171 ERROR("AFB-daemon Failed to fork son process");
174 // if in father process, just leave
178 // son process get all data in standalone mode
179 NOTICE("background mode [pid:%d console:%s]", getpid(),
182 // redirect default I/O on console
184 dup(consoleFD); // redirect stderr
186 dup(consoleFD); // redirect stdout
187 close(0); // no need for stdin
191 setsid(); // allow father process to fully exit
192 sleep(2); // allow main to leave and release port
196 /*---------------------------------------------------------
198 | Handles the HTTP server
199 +--------------------------------------------------------- */
200 static int init_alias(void *closure, char *spec)
202 struct afb_hsrv *hsrv = closure;
203 char *path = strchr(spec, ':');
206 ERROR("Missing ':' in alias %s. Alias ignored", spec);
210 INFO("Alias for url=%s to path=%s", spec, path);
211 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
215 static int init_http_server(struct afb_hsrv *hsrv)
217 if (!afb_hsrv_add_handler
218 (hsrv, config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
221 if (!afb_hsrv_add_handler
222 (hsrv, config->rootapi, afb_hswitch_apis, main_apiset, 10))
225 if (run_for_list(config->aliases, init_alias, hsrv))
228 if (config->roothttp != NULL) {
229 if (!afb_hsrv_add_alias
230 (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
235 if (!afb_hsrv_add_handler
236 (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
243 static struct afb_hsrv *start_http_server()
246 struct afb_hsrv *hsrv;
248 if (afb_hreq_init_download_path(config->uploaddir)) {
249 ERROR("unable to set the upload directory %s", config->uploaddir);
253 hsrv = afb_hsrv_create();
255 ERROR("memory allocation failure");
259 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
260 || !init_http_server(hsrv)) {
261 ERROR("initialisation of httpd failed");
266 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
267 NOTICE("Browser URL= http://localhost:%d", config->httpdPort);
269 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
271 ERROR("starting of httpd failed");
279 /*---------------------------------------------------------
282 +--------------------------------------------------------- */
284 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
286 if (info->si_pid == childpid) {
287 switch (info->si_code) {
293 killpg(info->si_pid, SIGKILL);
294 waitpid(info->si_pid, NULL, 0);
306 #define SUBST_CHAR '@'
307 #define SUBST_STR "@"
309 static char *instanciate_string(char *arg, const char *port, const char *token)
311 char *resu, *it, *wr;
314 /* get the changes */
317 it = strchrnul(arg, SUBST_CHAR);
320 case 'p': chg++; dif += (int)strlen(port) - 2; break;
321 case 't': chg++; dif += (int)strlen(token) - 2; break;
322 case SUBST_CHAR: it++; chg++; dif--; break;
325 it = strchrnul(it, SUBST_CHAR);
328 /* return arg when no change */
332 /* allocates the result */
333 resu = malloc((it - arg) + dif + 1);
335 ERROR("out of memory");
339 /* instanciate the arguments */
342 it = strchrnul(arg, SUBST_CHAR);
343 wr = mempcpy(wr, arg, it - arg);
347 case 'p': wr = stpcpy(wr, port); break;
348 case 't': wr = stpcpy(wr, token); break;
349 default: *wr++ = SUBST_CHAR;
350 case SUBST_CHAR: *wr++ = *it;
359 static int instanciate_environ(const char *port, const char *token)
361 extern char **environ;
365 /* instanciate the environment */
366 for (i = 0 ; environ[i] ; i++) {
367 repl = instanciate_string(environ[i], port, token);
375 static int instanciate_command_args(const char *port, const char *token)
380 /* instanciate the arguments */
381 for (i = 0 ; config->exec[i] ; i++) {
382 repl = instanciate_string(config->exec[i], port, token);
385 config->exec[i] = repl;
390 static int execute_command()
392 struct sigaction siga;
396 /* check whether a command is to execute or not */
397 if (!config->exec || !config->exec[0])
403 /* install signal handler */
404 memset(&siga, 0, sizeof siga);
405 siga.sa_sigaction = on_sigchld;
406 siga.sa_flags = SA_SIGINFO;
407 sigaction(SIGCHLD, &siga, NULL);
414 /* compute the string for port */
415 if (config->httpdPort)
416 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
418 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
419 if (rc < 0 || rc >= (int)(sizeof port)) {
420 ERROR("port->txt failed");
423 /* instanciate arguments and environment */
424 if (instanciate_command_args(port, config->token) >= 0
425 && instanciate_environ(port, config->token) >= 0) {
429 execv(config->exec[0], config->exec);
430 ERROR("can't launch %s: %m", config->exec[0]);
437 /*---------------------------------------------------------
439 +--------------------------------------------------------- */
443 struct afb_xreq xreq;
446 struct afb_config_list *current;
447 struct afb_session *session;
450 static void startup_call_reply(struct afb_xreq *xreq, int iserror, struct json_object *obj)
452 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
455 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
457 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
462 static void startup_call_current(struct startup_req *sreq);
464 static void startup_call_unref(struct afb_xreq *xreq)
466 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
470 json_object_put(sreq->xreq.json);
471 sreq->current = sreq->current->next;
473 startup_call_current(sreq);
475 afb_session_close(sreq->session);
476 afb_session_unref(sreq->session);
481 static struct afb_xreq_query_itf startup_xreq_itf =
483 .reply = startup_call_reply,
484 .unref = startup_call_unref
487 static void startup_call_current(struct startup_req *sreq)
489 char *api, *verb, *json;
491 api = sreq->current->value;
492 verb = strchr(api, '/');
494 json = strchr(verb, ':');
496 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
497 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
498 sreq->xreq.context.validated = 1;
499 sreq->api = strndup(api, verb - api);
500 sreq->verb = strndup(verb + 1, json - verb - 1);
501 sreq->xreq.api = sreq->api;
502 sreq->xreq.verb = sreq->verb;
503 sreq->xreq.json = json_tokener_parse(json + 1);
504 if (sreq->api && sreq->verb && sreq->xreq.json) {
505 afb_xreq_process(&sreq->xreq, main_apiset);
510 ERROR("Bad call specification %s", sreq->current->value);
514 static void run_startup_calls()
516 struct afb_config_list *list;
517 struct startup_req *sreq;
519 list = config->calls;
521 sreq = calloc(1, sizeof *sreq);
522 sreq->session = afb_session_create("startup", 3600);
523 sreq->current = list;
524 startup_call_current(sreq);
528 /*---------------------------------------------------------
529 | job for starting the daemon
530 +--------------------------------------------------------- */
532 static void start(int signum)
534 struct afb_hsrv *hsrv;
537 ERROR("start aborted: received signal %s", strsignal(signum));
541 // ------------------ sanity check ----------------------------------------
542 if (config->httpdPort <= 0) {
543 ERROR("no port is defined");
547 /* set the directories */
548 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
549 if (chdir(config->workdir) < 0) {
550 ERROR("Can't enter working dir %s", config->workdir);
553 if (afb_common_rootdir_set(config->rootdir) < 0) {
554 ERROR("failed to set common root directory");
558 /* configure the daemon */
559 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
560 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
561 ERROR("initialisation of cookies failed");
564 main_apiset = afb_apiset_create("main", config->apiTimeout);
566 ERROR("can't create main api set");
569 if (afb_monitor_init() < 0) {
570 ERROR("failed to setup monitor");
575 if (config->tracereq)
576 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
577 if (config->traceditf)
578 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
579 if (config->tracesvc)
580 afb_hook_create_svc(NULL, config->tracesvc, NULL, NULL);
581 if (config->traceevt)
582 afb_hook_create_evt(NULL, config->traceevt, NULL, NULL);
585 apiset_start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
586 apiset_start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
587 apiset_start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
588 apiset_start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
590 apiset_start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
591 apiset_start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
593 DEBUG("Init config done");
595 /* start the services */
596 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
599 /* start the HTTP server */
600 if (!config->noHttpd) {
601 hsrv = start_http_server();
606 /* run the command */
607 if (execute_command() < 0)
611 sd_notify(1, "READY=1");
613 /* run the startup calls */
620 /*---------------------------------------------------------
622 | Parse option and launch action
623 +--------------------------------------------------------- */
625 int main(int argc, char *argv[])
627 // let's run this program with a low priority
632 // ------------- Build session handler & init config -------
633 config = afb_config_parse_arguments(argc, argv);
634 INFO("running with pid %d", getpid());
636 // --------- run -----------
637 if (config->background) {
638 // --------- in background mode -----------
639 INFO("entering background mode");
642 // ---- in foreground mode --------------------
643 INFO("entering foreground mode");
646 /* set the daemon environment */
649 /* enter job processing */
650 jobs_start(3, 0, 50, start);
651 WARNING("hoops returned from jobs_enter! [report bug]");