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 #if !defined(NO_CALL_PERSONALITY)
33 #include <sys/personality.h>
36 #include <json-c/json.h>
38 #include <systemd/sd-daemon.h>
40 #include "afb-config.h"
41 #include "afb-hswitch.h"
42 #include "afb-apiset.h"
43 #include "afb-api-so.h"
44 #include "afb-api-dbus.h"
45 #include "afb-api-ws.h"
50 #include "afb-session.h"
52 #include "afb-common.h"
53 #include "afb-monitor.h"
56 #include "afb-debug.h"
59 if SELF_PGROUP == 0 the launched command is the group leader
60 if SELF_PGROUP != 0 afb-daemon is the group leader
64 struct afb_apiset *main_apiset;
66 static struct afb_config *config;
67 static pid_t childpid;
69 /*----------------------------------------------------------
70 | helpers for handling list of arguments
71 +--------------------------------------------------------- */
74 * Calls the callback 'run' for each value of the 'list'
75 * until the callback returns 0 or the end of the list is reached.
76 * Returns either NULL if the end of the list is reached or a pointer
77 * to the item whose value made 'run' return 0.
78 * 'closure' is used for passing user data.
80 static struct afb_config_list *run_for_list(struct afb_config_list *list,
81 int (*run) (void *closure, char *value),
84 while (list && run(closure, list->value))
89 static int run_start(void *closure, char *value)
91 int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
92 return starter(value, main_apiset) >= 0;
95 static void apiset_start_list(struct afb_config_list *list,
96 int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
98 list = run_for_list(list, run_start, starter);
100 ERROR("can't start %s %s", message, list->value);
105 /*----------------------------------------------------------
107 | Handles on exit specific actions
108 +--------------------------------------------------------- */
109 static void exit_handler()
111 struct sigaction siga;
113 memset(&siga, 0, sizeof siga);
114 siga.sa_handler = SIG_IGN;
115 sigaction(SIGTERM, &siga, NULL);
119 else if (childpid > 0)
120 killpg(childpid, SIGTERM);
123 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
125 NOTICE("Received SIGTERM");
129 static void on_sighup(int signum, siginfo_t *info, void *uctx)
131 NOTICE("Received SIGHUP");
135 static void setup_daemon()
137 struct sigaction siga;
139 /* install signal handlers */
140 memset(&siga, 0, sizeof siga);
141 siga.sa_flags = SA_SIGINFO;
143 siga.sa_sigaction = on_sigterm;
144 sigaction(SIGTERM, &siga, NULL);
146 siga.sa_sigaction = on_sighup;
147 sigaction(SIGHUP, &siga, NULL);
150 atexit(exit_handler);
152 /* ignore any SIGPIPE */
153 signal(SIGPIPE, SIG_IGN);
156 /*----------------------------------------------------------
158 | set the process in background
159 +--------------------------------------------------------- */
160 static void daemonize()
165 // open /dev/console to redirect output messAFBes
166 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
168 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
171 // fork process when running background mode
174 // if fail nothing much to do
176 ERROR("AFB-daemon Failed to fork son process");
179 // if in father process, just leave
183 // son process get all data in standalone mode
184 NOTICE("background mode [pid:%d console:%s]", getpid(),
187 // redirect default I/O on console
189 dup(consoleFD); // redirect stderr
191 dup(consoleFD); // redirect stdout
192 close(0); // no need for stdin
196 setsid(); // allow father process to fully exit
197 sleep(2); // allow main to leave and release port
201 /*---------------------------------------------------------
203 | Handles the HTTP server
204 +--------------------------------------------------------- */
205 static int init_alias(void *closure, char *spec)
207 struct afb_hsrv *hsrv = closure;
208 char *path = strchr(spec, ':');
211 ERROR("Missing ':' in alias %s. Alias ignored", spec);
215 INFO("Alias for url=%s to path=%s", spec, path);
216 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
220 static int init_http_server(struct afb_hsrv *hsrv)
222 if (!afb_hsrv_add_handler
223 (hsrv, config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
226 if (!afb_hsrv_add_handler
227 (hsrv, config->rootapi, afb_hswitch_apis, main_apiset, 10))
230 if (run_for_list(config->aliases, init_alias, hsrv))
233 if (config->roothttp != NULL) {
234 if (!afb_hsrv_add_alias
235 (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
240 if (!afb_hsrv_add_handler
241 (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
248 static struct afb_hsrv *start_http_server()
251 struct afb_hsrv *hsrv;
253 if (afb_hreq_init_download_path(config->uploaddir)) {
254 ERROR("unable to set the upload directory %s", config->uploaddir);
258 hsrv = afb_hsrv_create();
260 ERROR("memory allocation failure");
264 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
265 || !init_http_server(hsrv)) {
266 ERROR("initialisation of httpd failed");
271 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
272 NOTICE("Browser URL= http://localhost:%d", config->httpdPort);
274 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
276 ERROR("starting of httpd failed");
284 /*---------------------------------------------------------
287 +--------------------------------------------------------- */
289 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
291 if (info->si_pid == childpid) {
292 switch (info->si_code) {
298 killpg(info->si_pid, SIGKILL);
299 waitpid(info->si_pid, NULL, 0);
311 #define SUBST_CHAR '@'
312 #define SUBST_STR "@"
314 static char *instanciate_string(char *arg, const char *port, const char *token)
316 char *resu, *it, *wr;
319 /* get the changes */
322 it = strchrnul(arg, SUBST_CHAR);
325 case 'p': chg++; dif += (int)strlen(port) - 2; break;
326 case 't': chg++; dif += (int)strlen(token) - 2; break;
327 case SUBST_CHAR: it++; chg++; dif--; break;
330 it = strchrnul(it, SUBST_CHAR);
333 /* return arg when no change */
337 /* allocates the result */
338 resu = malloc((it - arg) + dif + 1);
340 ERROR("out of memory");
344 /* instanciate the arguments */
347 it = strchrnul(arg, SUBST_CHAR);
348 wr = mempcpy(wr, arg, it - arg);
352 case 'p': wr = stpcpy(wr, port); break;
353 case 't': wr = stpcpy(wr, token); break;
354 default: *wr++ = SUBST_CHAR;
355 case SUBST_CHAR: *wr++ = *it;
364 static int instanciate_environ(const char *port, const char *token)
366 extern char **environ;
370 /* instanciate the environment */
371 for (i = 0 ; environ[i] ; i++) {
372 repl = instanciate_string(environ[i], port, token);
380 static int instanciate_command_args(const char *port, const char *token)
385 /* instanciate the arguments */
386 for (i = 0 ; config->exec[i] ; i++) {
387 repl = instanciate_string(config->exec[i], port, token);
390 config->exec[i] = repl;
395 static int execute_command()
397 struct sigaction siga;
401 /* check whether a command is to execute or not */
402 if (!config->exec || !config->exec[0])
408 /* install signal handler */
409 memset(&siga, 0, sizeof siga);
410 siga.sa_sigaction = on_sigchld;
411 siga.sa_flags = SA_SIGINFO;
412 sigaction(SIGCHLD, &siga, NULL);
419 /* compute the string for port */
420 if (config->httpdPort)
421 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
423 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
424 if (rc < 0 || rc >= (int)(sizeof port)) {
425 ERROR("port->txt failed");
428 /* instanciate arguments and environment */
429 if (instanciate_command_args(port, config->token) >= 0
430 && instanciate_environ(port, config->token) >= 0) {
434 execv(config->exec[0], config->exec);
435 ERROR("can't launch %s: %m", config->exec[0]);
442 /*---------------------------------------------------------
444 +--------------------------------------------------------- */
448 struct afb_xreq xreq;
451 struct afb_config_list *current;
452 struct afb_session *session;
455 static void startup_call_reply(struct afb_xreq *xreq, int status, struct json_object *obj)
457 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
460 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
462 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
467 static void startup_call_current(struct startup_req *sreq);
469 static void startup_call_unref(struct afb_xreq *xreq)
471 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
475 json_object_put(sreq->xreq.json);
476 sreq->current = sreq->current->next;
478 startup_call_current(sreq);
480 afb_session_close(sreq->session);
481 afb_session_unref(sreq->session);
486 static struct afb_xreq_query_itf startup_xreq_itf =
488 .reply = startup_call_reply,
489 .unref = startup_call_unref
492 static void startup_call_current(struct startup_req *sreq)
494 char *api, *verb, *json;
496 api = sreq->current->value;
497 verb = strchr(api, '/');
499 json = strchr(verb, ':');
501 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
502 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
503 sreq->xreq.context.validated = 1;
504 sreq->api = strndup(api, verb - api);
505 sreq->verb = strndup(verb + 1, json - verb - 1);
506 sreq->xreq.api = sreq->api;
507 sreq->xreq.verb = sreq->verb;
508 sreq->xreq.json = json_tokener_parse(json + 1);
509 if (sreq->api && sreq->verb && sreq->xreq.json) {
510 afb_xreq_process(&sreq->xreq, main_apiset);
515 ERROR("Bad call specification %s", sreq->current->value);
519 static void run_startup_calls()
521 struct afb_config_list *list;
522 struct startup_req *sreq;
524 list = config->calls;
526 sreq = calloc(1, sizeof *sreq);
527 sreq->session = afb_session_create("startup", 3600);
528 sreq->current = list;
529 startup_call_current(sreq);
533 /*---------------------------------------------------------
534 | job for starting the daemon
535 +--------------------------------------------------------- */
537 static void start(int signum)
539 struct afb_hsrv *hsrv;
541 afb_debug("start-entry");
544 ERROR("start aborted: received signal %s", strsignal(signum));
548 // ------------------ sanity check ----------------------------------------
549 if (config->httpdPort <= 0) {
550 ERROR("no port is defined");
554 /* set the directories */
555 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
556 if (chdir(config->workdir) < 0) {
557 ERROR("Can't enter working dir %s", config->workdir);
560 if (afb_common_rootdir_set(config->rootdir) < 0) {
561 ERROR("failed to set common root directory");
565 /* configure the daemon */
566 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
567 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
568 ERROR("initialisation of cookies failed");
571 main_apiset = afb_apiset_create("main", config->apiTimeout);
573 ERROR("can't create main api set");
576 if (afb_monitor_init() < 0) {
577 ERROR("failed to setup monitor");
582 if (config->tracereq)
583 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
584 if (config->traceditf)
585 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
586 if (config->tracesvc)
587 afb_hook_create_svc(NULL, config->tracesvc, NULL, NULL);
588 if (config->traceevt)
589 afb_hook_create_evt(NULL, config->traceevt, NULL, NULL);
592 afb_debug("start-load");
593 apiset_start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
594 apiset_start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
595 apiset_start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
596 apiset_start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
598 apiset_start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
599 apiset_start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
601 DEBUG("Init config done");
603 /* start the services */
604 afb_debug("start-start");
605 #if !defined(NO_CALL_PERSONALITY)
606 personality((unsigned long)-1L);
608 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
611 /* start the HTTP server */
612 afb_debug("start-http");
613 if (!config->noHttpd) {
614 hsrv = start_http_server();
619 /* run the startup calls */
620 afb_debug("start-call");
623 /* run the command */
624 afb_debug("start-exec");
625 if (execute_command() < 0)
629 sd_notify(1, "READY=1");
635 /*---------------------------------------------------------
637 | Parse option and launch action
638 +--------------------------------------------------------- */
640 int main(int argc, char *argv[])
642 afb_debug("main-entry");
644 // let's run this program with a low priority
649 // ------------- Build session handler & init config -------
650 config = afb_config_parse_arguments(argc, argv);
652 afb_debug("main-args");
654 // --------- run -----------
655 if (config->background) {
656 // --------- in background mode -----------
657 INFO("entering background mode");
660 // ---- in foreground mode --------------------
661 INFO("entering foreground mode");
663 INFO("running with pid %d", getpid());
665 /* set the daemon environment */
668 afb_debug("main-start");
670 /* enter job processing */
671 jobs_start(3, 0, 50, start);
672 WARNING("hoops returned from jobs_enter! [report bug]");