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 NO_BINDING_VERBOSE_MACRO
31 #include <json-c/json.h>
33 #include <systemd/sd-daemon.h>
35 #include "afb-config.h"
36 #include "afb-hswitch.h"
37 #include "afb-apiset.h"
38 #include "afb-api-so.h"
39 #include "afb-api-dbus.h"
40 #include "afb-api-ws.h"
45 #include "afb-session.h"
47 #include "afb-common.h"
52 if SELF_PGROUP == 0 the launched command is the group leader
53 if SELF_PGROUP != 0 afb-daemon is the group leader
57 struct afb_apiset *main_apiset;
59 static struct afb_config *config;
60 static pid_t childpid;
62 /*----------------------------------------------------------
63 | helpers for handling list of arguments
64 +--------------------------------------------------------- */
67 * Calls the callback 'run' for each value of the 'list'
68 * until the callback returns 0 or the end of the list is reached.
69 * Returns either NULL if the end of the list is reached or a pointer
70 * to the item whose value made 'run' return 0.
71 * 'closure' is used for passing user data.
73 static struct afb_config_list *run_for_list(struct afb_config_list *list,
74 int (*run) (void *closure, char *value),
77 while (list && run(closure, list->value))
82 static int run_start(void *closure, char *value)
84 int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
85 return starter(value, main_apiset) >= 0;
88 static void apiset_start_list(struct afb_config_list *list,
89 int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
91 list = run_for_list(list, run_start, starter);
93 ERROR("can't start %s %s", message, list->value);
98 /*----------------------------------------------------------
100 | Handles on exit specific actions
101 +--------------------------------------------------------- */
102 static void exit_handler()
104 struct sigaction siga;
106 memset(&siga, 0, sizeof siga);
107 siga.sa_handler = SIG_IGN;
108 sigaction(SIGTERM, &siga, NULL);
112 else if (childpid > 0)
113 killpg(childpid, SIGTERM);
117 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
119 NOTICE("Received SIGTERM");
123 static void on_sighup(int signum, siginfo_t *info, void *uctx)
125 NOTICE("Received SIGHUP");
129 static void setup_daemon()
131 struct sigaction siga;
133 /* install signal handlers */
134 memset(&siga, 0, sizeof siga);
135 siga.sa_flags = SA_SIGINFO;
137 siga.sa_sigaction = on_sigterm;
138 sigaction(SIGTERM, &siga, NULL);
140 siga.sa_sigaction = on_sighup;
141 sigaction(SIGHUP, &siga, NULL);
144 atexit(exit_handler);
146 /* ignore any SIGPIPE */
147 signal(SIGPIPE, SIG_IGN);
150 /*----------------------------------------------------------
152 | set the process in background
153 +--------------------------------------------------------- */
154 static void daemonize()
159 // open /dev/console to redirect output messAFBes
160 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
162 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
165 // fork process when running background mode
168 // if fail nothing much to do
170 ERROR("AFB-daemon Failed to fork son process");
173 // if in father process, just leave
177 // son process get all data in standalone mode
178 NOTICE("background mode [pid:%d console:%s]", getpid(),
181 // redirect default I/O on console
183 dup(consoleFD); // redirect stderr
185 dup(consoleFD); // redirect stdout
186 close(0); // no need for stdin
190 setsid(); // allow father process to fully exit
191 sleep(2); // allow main to leave and release port
195 /*---------------------------------------------------------
197 | Handles the HTTP server
198 +--------------------------------------------------------- */
199 static int init_alias(void *closure, char *spec)
201 struct afb_hsrv *hsrv = closure;
202 char *path = strchr(spec, ':');
205 ERROR("Missing ':' in alias %s. Alias ignored", spec);
209 INFO("Alias for url=%s to path=%s", spec, path);
210 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
214 static int init_http_server(struct afb_hsrv *hsrv)
216 if (!afb_hsrv_add_handler
217 (hsrv, config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
220 if (!afb_hsrv_add_handler
221 (hsrv, config->rootapi, afb_hswitch_apis, main_apiset, 10))
224 if (run_for_list(config->aliases, init_alias, hsrv))
227 if (config->roothttp != NULL) {
228 if (!afb_hsrv_add_alias
229 (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
234 if (!afb_hsrv_add_handler
235 (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
242 static struct afb_hsrv *start_http_server()
245 struct afb_hsrv *hsrv;
247 if (afb_hreq_init_download_path(config->uploaddir)) {
248 ERROR("unable to set the upload directory %s", config->uploaddir);
252 hsrv = afb_hsrv_create();
254 ERROR("memory allocation failure");
258 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
259 || !init_http_server(hsrv)) {
260 ERROR("initialisation of httpd failed");
265 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
266 NOTICE("Browser URL= http://localhost:%d", config->httpdPort);
268 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
270 ERROR("starting of httpd failed");
278 /*---------------------------------------------------------
281 +--------------------------------------------------------- */
283 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
285 if (info->si_pid == childpid) {
286 switch (info->si_code) {
292 killpg(info->si_pid, SIGKILL);
293 waitpid(info->si_pid, NULL, 0);
305 #define SUBST_CHAR '@'
306 #define SUBST_STR "@"
308 static char *instanciate_string(char *arg, const char *port, const char *token)
310 char *resu, *it, *wr;
313 /* get the changes */
316 it = strchrnul(arg, SUBST_CHAR);
319 case 'p': chg++; dif += (int)strlen(port) - 2; break;
320 case 't': chg++; dif += (int)strlen(token) - 2; break;
321 case SUBST_CHAR: it++; chg++; dif--; break;
324 it = strchrnul(it, SUBST_CHAR);
327 /* return arg when no change */
331 /* allocates the result */
332 resu = malloc((it - arg) + dif + 1);
334 ERROR("out of memory");
338 /* instanciate the arguments */
341 it = strchrnul(arg, SUBST_CHAR);
342 wr = mempcpy(wr, arg, it - arg);
346 case 'p': wr = stpcpy(wr, port); break;
347 case 't': wr = stpcpy(wr, token); break;
348 default: *wr++ = SUBST_CHAR;
349 case SUBST_CHAR: *wr++ = *it;
358 static int instanciate_environ(const char *port, const char *token)
360 extern char **environ;
364 /* instanciate the environment */
365 for (i = 0 ; environ[i] ; i++) {
366 repl = instanciate_string(environ[i], port, token);
374 static int instanciate_command_args(const char *port, const char *token)
379 /* instanciate the arguments */
380 for (i = 0 ; config->exec[i] ; i++) {
381 repl = instanciate_string(config->exec[i], port, token);
384 config->exec[i] = repl;
389 static int execute_command()
391 struct sigaction siga;
395 /* check whether a command is to execute or not */
396 if (!config->exec || !config->exec[0])
402 /* install signal handler */
403 memset(&siga, 0, sizeof siga);
404 siga.sa_sigaction = on_sigchld;
405 siga.sa_flags = SA_SIGINFO;
406 sigaction(SIGCHLD, &siga, NULL);
413 /* compute the string for port */
414 if (config->httpdPort)
415 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
417 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
418 if (rc < 0 || rc >= (int)(sizeof port)) {
419 ERROR("port->txt failed");
422 /* instanciate arguments and environment */
423 if (instanciate_command_args(port, config->token) >= 0
424 && instanciate_environ(port, config->token) >= 0) {
428 execv(config->exec[0], config->exec);
429 ERROR("can't launch %s: %m", config->exec[0]);
436 /*---------------------------------------------------------
438 +--------------------------------------------------------- */
442 struct afb_xreq xreq;
445 struct afb_config_list *current;
446 struct afb_session *session;
449 static void startup_call_reply(struct afb_xreq *xreq, int iserror, struct json_object *obj)
451 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
454 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
456 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
461 static void startup_call_current(struct startup_req *sreq);
463 static void startup_call_unref(struct afb_xreq *xreq)
465 struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
469 json_object_put(sreq->xreq.json);
470 sreq->current = sreq->current->next;
472 startup_call_current(sreq);
474 afb_session_close(sreq->session);
475 afb_session_unref(sreq->session);
480 static struct afb_xreq_query_itf startup_xreq_itf =
482 .reply = startup_call_reply,
483 .unref = startup_call_unref
486 static void startup_call_current(struct startup_req *sreq)
488 char *api, *verb, *json;
490 api = sreq->current->value;
491 verb = strchr(api, '/');
493 json = strchr(verb, ':');
495 afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
496 afb_context_init(&sreq->xreq.context, sreq->session, NULL);
497 sreq->xreq.context.validated = 1;
498 sreq->api = strndup(api, verb - api);
499 sreq->verb = strndup(verb + 1, json - verb - 1);
500 sreq->xreq.api = sreq->api;
501 sreq->xreq.verb = sreq->verb;
502 sreq->xreq.json = json_tokener_parse(json + 1);
503 if (sreq->api && sreq->verb && sreq->xreq.json) {
504 afb_xreq_process(&sreq->xreq, main_apiset);
509 ERROR("Bad call specification %s", sreq->current->value);
513 static void run_startup_calls()
515 struct afb_config_list *list;
516 struct startup_req *sreq;
518 list = config->calls;
520 sreq = calloc(1, sizeof *sreq);
521 sreq->session = afb_session_create("startup", 3600);
522 sreq->current = list;
523 startup_call_current(sreq);
527 /*---------------------------------------------------------
528 | job for starting the daemon
529 +--------------------------------------------------------- */
533 struct afb_hsrv *hsrv;
535 // ------------------ sanity check ----------------------------------------
536 if (config->httpdPort <= 0) {
537 ERROR("no port is defined");
541 /* set the directories */
542 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
543 if (chdir(config->workdir) < 0) {
544 ERROR("Can't enter working dir %s", config->workdir);
547 if (afb_common_rootdir_set(config->rootdir) < 0) {
548 ERROR("failed to set common root directory");
552 /* configure the daemon */
553 main_apiset = afb_apiset_create("main", config->apiTimeout, NULL);
555 ERROR("can't create main api set");
558 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
559 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
560 ERROR("initialisation of cookies failed");
565 if (config->tracereq)
566 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
567 if (config->traceditf)
568 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
571 apiset_start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
572 apiset_start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
573 apiset_start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
574 apiset_start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
576 apiset_start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
577 apiset_start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
579 DEBUG("Init config done");
581 /* start the services */
582 if (afb_apiset_start_all_services(main_apiset, 1) < 0)
585 /* start the HTTP server */
586 if (!config->noHttpd) {
587 hsrv = start_http_server();
592 /* run the command */
593 if (execute_command() < 0)
597 sd_notify(1, "READY=1");
599 /* run the startup calls */
606 /*---------------------------------------------------------
608 | Parse option and launch action
609 +--------------------------------------------------------- */
611 int main(int argc, char *argv[])
613 // let's run this program with a low priority
618 // ------------- Build session handler & init config -------
619 config = afb_config_parse_arguments(argc, argv);
620 INFO("running with pid %d", getpid());
622 // --------- run -----------
623 if (config->background) {
624 // --------- in background mode -----------
625 INFO("entering background mode");
628 // ---- in foreground mode --------------------
629 INFO("entering foreground mode");
632 /* set the daemon environment */
635 /* enter job processing */
636 jobs_start(3, 0, 50, start);
637 WARNING("hoops returned from jobs_enter! [report bug]");