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 "afb-sig-handler.h"
45 #include "afb-thread.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 int instanciate_command_args()
270 char *orig, *repl, *sub, *val, port[20];
274 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
275 if (rc < 0 || rc >= (int)(sizeof port))
278 for (i = 0 ; (orig = config->exec[i]) ; i++) {
282 sub = strchrnul(orig, SUBST_CHAR);
285 repl = mempcpy(repl, orig, l);
290 if (repl || orig == config->exec[i])
292 repl = malloc(1 + s);
295 orig = config->exec[i];
296 config->exec[i] = repl;
301 case 'p': val = port; break;
302 case 't': val = config->token ? : ""; break;
304 case SUBST_CHAR: val = SUBST_STR; break;
309 repl = mempcpy(repl, val, l);
318 static int execute_command()
320 struct sigaction siga;
322 /* check whether a command is to execute or not */
323 if (!config->exec || !config->exec[0])
329 /* install signal handler */
330 memset(&siga, 0, sizeof siga);
331 siga.sa_sigaction = on_sigchld;
332 siga.sa_flags = SA_SIGINFO;
333 sigaction(SIGCHLD, &siga, NULL);
340 /* makes arguments */
341 if (instanciate_command_args() >= 0) {
344 execv(config->exec[0], config->exec);
345 ERROR("can't launch %s: %m", config->exec[0]);
351 /*---------------------------------------------------------
353 | Parse option and launch action
354 +--------------------------------------------------------- */
356 int main(int argc, char *argv[])
358 struct afb_hsrv *hsrv;
359 struct sd_event *eventloop;
361 LOGAUTH("afb-daemon");
365 // ------------- Build session handler & init config -------
366 config = afb_config_parse_arguments(argc, argv);
367 atexit(exit_handler);
369 // ------------------ sanity check ----------------------------------------
370 if (config->httpdPort <= 0) {
371 ERROR("no port is defined");
375 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
376 if (chdir(config->workdir) < 0) {
377 ERROR("Can't enter working dir %s", config->workdir);
381 afb_api_so_set_timeout(config->apiTimeout);
382 start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
383 start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
384 start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
385 start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
387 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
389 start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
390 start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
392 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
393 ERROR("initialisation of cookies failed");
397 if (afb_sig_handler_init() < 0) {
398 ERROR("failed to initialise signal handlers");
403 if (afb_common_rootdir_set(config->rootdir) < 0) {
404 ERROR("failed to set common root directory");
408 if (afb_thread_init(3, 1, 20) < 0) {
409 ERROR("failed to initialise threading");
412 // let's run this program with a low priority
415 // ------------------ Finaly Process Commands -----------------------------
416 // let's not take the risk to run as ROOT
417 //if (getuid() == 0) goto errorNoRoot;
419 DEBUG("Init config done");
421 // --------- run -----------
422 if (config->background) {
423 // --------- in background mode -----------
424 INFO("entering background mode");
427 // ---- in foreground mode --------------------
428 INFO("entering foreground mode");
431 /* ignore any SIGPIPE */
432 signal(SIGPIPE, SIG_IGN);
434 /* install trace of requests */
435 if (config->tracereq)
436 afb_hook_req_create(NULL, NULL, NULL, config->tracereq, NULL, NULL);
438 /* start the services */
439 if (afb_apis_start_all_services(1) < 0)
442 /* start the HTTP server */
443 if (!config->noHttpd) {
444 hsrv = start_http_server();
449 /* run the command */
450 if (execute_command() < 0)
453 /* signal that ready */
454 if (config->readyfd != 0) {
455 static const char readystr[] = "READY=1";
456 write(config->readyfd, readystr, sizeof(readystr) - 1);
457 close(config->readyfd);
461 eventloop = afb_common_get_event_loop();
462 sd_notify(1, "READY=1");
464 sd_event_run(eventloop, 30000000);
466 WARNING("hoops returned from infinite loop [report bug]");