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>
32 #include "afb-config.h"
33 #include "afb-hswitch.h"
35 #include "afb-api-so.h"
36 #include "afb-api-dbus.h"
37 #include "afb-api-ws.h"
39 #include "afb-context.h"
41 #include "afb-sig-handler.h"
42 #include "afb-thread.h"
43 #include "afb-session.h"
45 #include "afb-common.h"
48 #include <afb/afb-binding.h>
51 if SELF_PGROUP == 0 the launched command is the group leader
52 if SELF_PGROUP != 0 afb-daemon is the group leader
56 static struct afb_config *config;
57 static pid_t childpid;
59 /*----------------------------------------------------------
60 | helpers for handling list of arguments
61 +--------------------------------------------------------- */
64 * Calls the callback 'run' for each value of the 'list'
65 * until the callback returns 0 or the end of the list is reached.
66 * Returns either NULL if the end of the list is reached or a pointer
67 * to the item whose value made 'run' return 0.
68 * 'closure' is used for passing user data.
70 static struct afb_config_list *run_for_list(struct afb_config_list *list,
71 int (*run) (void *closure, char *value),
74 while (list && run(closure, list->value))
79 static int run_start(void *closure, char *value)
81 int (*starter) (const char *value) = closure;
82 return starter(value) >= 0;
85 static void start_list(struct afb_config_list *list,
86 int (*starter) (const char *value), const char *message)
88 list = run_for_list(list, run_start, starter);
90 ERROR("can't start %s %s", message, list->value);
95 /*----------------------------------------------------------
97 | Handles on exit specific actions
98 +--------------------------------------------------------- */
99 static void exit_handler()
101 /* TODO: check whether using SIGHUP isn't better */
104 else if (childpid > 0)
105 killpg(childpid, SIGKILL);
108 /*----------------------------------------------------------
110 | set the process in background
111 +--------------------------------------------------------- */
112 static void daemonize()
117 // open /dev/console to redirect output messAFBes
118 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
120 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
123 // fork process when running background mode
126 // if fail nothing much to do
128 ERROR("AFB-daemon Failed to fork son process");
131 // if in father process, just leave
135 // son process get all data in standalone mode
136 NOTICE("background mode [pid:%d console:%s]", getpid(),
139 // redirect default I/O on console
141 dup(consoleFD); // redirect stderr
143 dup(consoleFD); // redirect stdout
144 close(0); // no need for stdin
148 setsid(); // allow father process to fully exit
149 sleep(2); // allow main to leave and release port
153 /*---------------------------------------------------------
155 | Handles the HTTP server
156 +--------------------------------------------------------- */
157 static int init_alias(void *closure, char *spec)
159 struct afb_hsrv *hsrv = closure;
160 char *path = strchr(spec, ':');
163 ERROR("Missing ':' in alias %s. Alias ignored", spec);
167 INFO("Alias for url=%s to path=%s", spec, path);
168 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
172 static int init_http_server(struct afb_hsrv *hsrv)
174 if (!afb_hsrv_add_handler
175 (hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
178 if (!afb_hsrv_add_handler
179 (hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
182 if (run_for_list(config->aliases, init_alias, hsrv))
185 if (config->roothttp != NULL) {
186 if (!afb_hsrv_add_alias
187 (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
192 if (!afb_hsrv_add_handler
193 (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
200 static struct afb_hsrv *start_http_server()
203 struct afb_hsrv *hsrv;
205 if (afb_hreq_init_download_path(config->uploaddir)) {
206 ERROR("unable to set the upload directory %s", config->uploaddir);
210 hsrv = afb_hsrv_create();
212 ERROR("memory allocation failure");
216 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
217 || !init_http_server(hsrv)) {
218 ERROR("initialisation of httpd failed");
223 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
224 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
226 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
228 ERROR("starting of httpd failed");
236 /*---------------------------------------------------------
239 +--------------------------------------------------------- */
241 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
243 if (info->si_pid == childpid) {
244 switch (info->si_code) {
250 killpg(info->si_pid, SIGKILL);
251 waitpid(info->si_pid, NULL, 0);
263 #define SUBST_CHAR '@'
264 #define SUBST_STR "@"
266 static int instanciate_command_args()
268 char *orig, *repl, *sub, *val, port[20];
272 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
273 if (rc < 0 || rc >= (int)(sizeof port))
276 for (i = 0 ; (orig = config->exec[i]) ; i++) {
280 sub = strchrnul(orig, SUBST_CHAR);
283 repl = mempcpy(repl, orig, l);
288 if (repl || orig == config->exec[i])
290 repl = malloc(1 + s);
293 orig = config->exec[i];
294 config->exec[i] = repl;
299 case 'p': val = port; break;
300 case 't': val = config->token ? : ""; break;
302 case SUBST_CHAR: val = SUBST_STR; break;
307 repl = mempcpy(repl, val, l);
316 static int execute_command()
318 struct sigaction siga;
320 /* check whether a command is to execute or not */
321 if (!config->exec || !config->exec[0])
327 /* install signal handler */
328 memset(&siga, 0, sizeof siga);
329 siga.sa_sigaction = on_sigchld;
330 siga.sa_flags = SA_SIGINFO;
331 sigaction(SIGCHLD, &siga, NULL);
338 /* makes arguments */
339 if (instanciate_command_args() >= 0) {
342 execv(config->exec[0], config->exec);
343 ERROR("can't launch %s: %m", config->exec[0]);
349 /*---------------------------------------------------------
351 | Parse option and launch action
352 +--------------------------------------------------------- */
354 int main(int argc, char *argv[])
356 struct afb_hsrv *hsrv;
357 struct sd_event *eventloop;
359 LOGAUTH("afb-daemon");
361 // ------------- Build session handler & init config -------
362 config = afb_config_parse_arguments(argc, argv);
363 atexit(exit_handler);
365 // ------------------ sanity check ----------------------------------------
366 if (config->httpdPort <= 0) {
367 ERROR("no port is defined");
371 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
372 if (chdir(config->workdir) < 0) {
373 ERROR("Can't enter working dir %s", config->workdir);
377 afb_api_so_set_timeout(config->apiTimeout);
378 start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
379 start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
380 start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
381 start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
383 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
385 start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
386 start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
388 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
389 ERROR("initialisation of cookies failed");
393 if (afb_sig_handler_init() < 0) {
394 ERROR("failed to initialise signal handlers");
399 if (afb_common_rootdir_set(config->rootdir) < 0) {
400 ERROR("failed to set common root directory");
404 if (afb_thread_init(3, 1, 20) < 0) {
405 ERROR("failed to initialise threading");
408 // let's run this program with a low priority
411 // ------------------ Finaly Process Commands -----------------------------
412 // let's not take the risk to run as ROOT
413 //if (getuid() == 0) goto errorNoRoot;
415 DEBUG("Init config done");
417 // --------- run -----------
418 if (config->background) {
419 // --------- in background mode -----------
420 INFO("entering background mode");
423 // ---- in foreground mode --------------------
424 INFO("entering foreground mode");
427 /* ignore any SIGPIPE */
428 signal(SIGPIPE, SIG_IGN);
430 /* install trace of requests */
431 if (config->tracereq)
432 afb_hook_req_create(NULL, NULL, NULL, config->tracereq, NULL, NULL);
434 /* start the services */
435 if (afb_apis_start_all_services(1) < 0)
438 /* start the HTTP server */
439 if (!config->noHttpd) {
440 hsrv = start_http_server();
445 /* run the command */
446 if (execute_command() < 0)
449 /* signal that ready */
450 if (config->readyfd != 0) {
451 static const char readystr[] = "READY=1";
452 write(config->readyfd, readystr, sizeof(readystr) - 1);
453 close(config->readyfd);
457 eventloop = afb_common_get_event_loop();
459 sd_event_run(eventloop, 30000000);
461 WARNING("hoops returned from infinite loop [report bug]");