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
30 #include <systemd/sd-event.h>
31 #include <systemd/sd-daemon.h>
33 #include <afb/afb-binding.h>
35 #include "afb-config.h"
36 #include "afb-hswitch.h"
38 #include "afb-api-so.h"
39 #include "afb-api-dbus.h"
40 #include "afb-api-ws.h"
42 #include "afb-context.h"
44 #include "sig-monitor.h"
46 #include "afb-session.h"
48 #include "afb-common.h"
53 if SELF_PGROUP == 0 the launched command is the group leader
54 if SELF_PGROUP != 0 afb-daemon is the group leader
58 static struct afb_config *config;
59 static pid_t childpid;
61 /*----------------------------------------------------------
62 | helpers for handling list of arguments
63 +--------------------------------------------------------- */
66 * Calls the callback 'run' for each value of the 'list'
67 * until the callback returns 0 or the end of the list is reached.
68 * Returns either NULL if the end of the list is reached or a pointer
69 * to the item whose value made 'run' return 0.
70 * 'closure' is used for passing user data.
72 static struct afb_config_list *run_for_list(struct afb_config_list *list,
73 int (*run) (void *closure, char *value),
76 while (list && run(closure, list->value))
81 static int run_start(void *closure, char *value)
83 int (*starter) (const char *value) = closure;
84 return starter(value) >= 0;
87 static void start_list(struct afb_config_list *list,
88 int (*starter) (const char *value), const char *message)
90 list = run_for_list(list, run_start, starter);
92 ERROR("can't start %s %s", message, list->value);
97 /*----------------------------------------------------------
99 | Handles on exit specific actions
100 +--------------------------------------------------------- */
101 static void exit_handler()
103 /* TODO: check whether using SIGHUP isn't better */
106 else if (childpid > 0)
107 killpg(childpid, SIGKILL);
110 /*----------------------------------------------------------
112 | set the process in background
113 +--------------------------------------------------------- */
114 static void daemonize()
119 // open /dev/console to redirect output messAFBes
120 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
122 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
125 // fork process when running background mode
128 // if fail nothing much to do
130 ERROR("AFB-daemon Failed to fork son process");
133 // if in father process, just leave
137 // son process get all data in standalone mode
138 NOTICE("background mode [pid:%d console:%s]", getpid(),
141 // redirect default I/O on console
143 dup(consoleFD); // redirect stderr
145 dup(consoleFD); // redirect stdout
146 close(0); // no need for stdin
150 setsid(); // allow father process to fully exit
151 sleep(2); // allow main to leave and release port
155 /*---------------------------------------------------------
157 | Handles the HTTP server
158 +--------------------------------------------------------- */
159 static int init_alias(void *closure, char *spec)
161 struct afb_hsrv *hsrv = closure;
162 char *path = strchr(spec, ':');
165 ERROR("Missing ':' in alias %s. Alias ignored", spec);
169 INFO("Alias for url=%s to path=%s", spec, path);
170 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
174 static int init_http_server(struct afb_hsrv *hsrv)
176 if (!afb_hsrv_add_handler
177 (hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
180 if (!afb_hsrv_add_handler
181 (hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
184 if (run_for_list(config->aliases, init_alias, hsrv))
187 if (config->roothttp != NULL) {
188 if (!afb_hsrv_add_alias
189 (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
194 if (!afb_hsrv_add_handler
195 (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
202 static struct afb_hsrv *start_http_server()
205 struct afb_hsrv *hsrv;
207 if (afb_hreq_init_download_path(config->uploaddir)) {
208 ERROR("unable to set the upload directory %s", config->uploaddir);
212 hsrv = afb_hsrv_create();
214 ERROR("memory allocation failure");
218 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
219 || !init_http_server(hsrv)) {
220 ERROR("initialisation of httpd failed");
225 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
226 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
228 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
230 ERROR("starting of httpd failed");
238 /*---------------------------------------------------------
241 +--------------------------------------------------------- */
243 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
245 if (info->si_pid == childpid) {
246 switch (info->si_code) {
252 killpg(info->si_pid, SIGKILL);
253 waitpid(info->si_pid, NULL, 0);
265 #define SUBST_CHAR '@'
266 #define SUBST_STR "@"
268 static char *instanciate_string(char *arg, const char *port, const char *token)
270 char *resu, *it, *wr;
273 /* get the changes */
276 it = strchrnul(arg, SUBST_CHAR);
279 case 'p': chg++; dif += (int)strlen(port) - 2; break;
280 case 't': chg++; dif += (int)strlen(token) - 2; break;
281 case SUBST_CHAR: it++; chg++; dif--; break;
284 it = strchrnul(it, SUBST_CHAR);
287 /* return arg when no change */
291 /* allocates the result */
292 resu = malloc((it - arg) + dif + 1);
294 ERROR("out of memory");
298 /* instanciate the arguments */
301 it = strchrnul(arg, SUBST_CHAR);
302 wr = mempcpy(wr, arg, it - arg);
306 case 'p': wr = stpcpy(wr, port); break;
307 case 't': wr = stpcpy(wr, token); break;
308 default: *wr++ = SUBST_CHAR;
309 case SUBST_CHAR: *wr++ = *it;
318 static int instanciate_environ(const char *port, const char *token)
320 extern char **environ;
324 /* instanciate the environment */
325 for (i = 0 ; environ[i] ; i++) {
326 repl = instanciate_string(environ[i], port, token);
334 static int instanciate_command_args(const char *port, const char *token)
339 /* instanciate the arguments */
340 for (i = 0 ; config->exec[i] ; i++) {
341 repl = instanciate_string(config->exec[i], port, token);
344 config->exec[i] = repl;
349 static int execute_command()
351 struct sigaction siga;
355 /* check whether a command is to execute or not */
356 if (!config->exec || !config->exec[0])
362 /* install signal handler */
363 memset(&siga, 0, sizeof siga);
364 siga.sa_sigaction = on_sigchld;
365 siga.sa_flags = SA_SIGINFO;
366 sigaction(SIGCHLD, &siga, NULL);
373 /* compute the string for port */
374 if (config->httpdPort)
375 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
377 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
378 if (rc < 0 || rc >= (int)(sizeof port)) {
379 ERROR("port->txt failed");
382 /* instanciate arguments and environment */
383 if (instanciate_command_args(port, config->token) >= 0
384 && instanciate_environ(port, config->token) >= 0) {
388 execv(config->exec[0], config->exec);
389 ERROR("can't launch %s: %m", config->exec[0]);
396 /*---------------------------------------------------------
398 | Parse option and launch action
399 +--------------------------------------------------------- */
401 int main(int argc, char *argv[])
403 struct afb_hsrv *hsrv;
404 struct sd_event *eventloop;
406 LOGAUTH("afb-daemon");
410 // ------------- Build session handler & init config -------
411 config = afb_config_parse_arguments(argc, argv);
412 atexit(exit_handler);
414 // ------------------ sanity check ----------------------------------------
415 if (config->httpdPort <= 0) {
416 ERROR("no port is defined");
420 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
421 if (chdir(config->workdir) < 0) {
422 ERROR("Can't enter working dir %s", config->workdir);
426 afb_api_so_set_timeout(config->apiTimeout);
427 start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
428 start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
429 start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
430 start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
432 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
434 start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
435 start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
437 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
438 ERROR("initialisation of cookies failed");
442 if (sig_monitor_init() < 0) {
443 ERROR("failed to initialise signal handlers");
448 if (afb_common_rootdir_set(config->rootdir) < 0) {
449 ERROR("failed to set common root directory");
453 if (jobs_init(3, 1, 20) < 0) {
454 ERROR("failed to initialise threading");
457 // let's run this program with a low priority
460 // ------------------ Finaly Process Commands -----------------------------
461 // let's not take the risk to run as ROOT
462 //if (getuid() == 0) goto errorNoRoot;
464 DEBUG("Init config done");
466 // --------- run -----------
467 if (config->background) {
468 // --------- in background mode -----------
469 INFO("entering background mode");
472 // ---- in foreground mode --------------------
473 INFO("entering foreground mode");
476 /* ignore any SIGPIPE */
477 signal(SIGPIPE, SIG_IGN);
479 /* install trace of requests */
480 if (config->tracereq)
481 afb_hook_req_create(NULL, NULL, NULL, config->tracereq, NULL, NULL);
483 /* start the services */
484 if (afb_apis_start_all_services(1) < 0)
487 /* start the HTTP server */
488 if (!config->noHttpd) {
489 hsrv = start_http_server();
494 /* run the command */
495 if (execute_command() < 0)
498 /* signal that ready */
499 if (config->readyfd != 0) {
500 static const char readystr[] = "READY=1";
501 write(config->readyfd, readystr, sizeof(readystr) - 1);
502 close(config->readyfd);
506 eventloop = afb_common_get_event_loop();
507 sd_notify(1, "READY=1");
509 sd_event_run(eventloop, 30000000);
511 WARNING("hoops returned from infinite loop [report bug]");