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-config.h"
34 #include "afb-hswitch.h"
36 #include "afb-api-so.h"
37 #include "afb-api-dbus.h"
38 #include "afb-api-ws.h"
40 #include "afb-context.h"
42 #include "afb-sig-handler.h"
43 #include "afb-thread.h"
44 #include "afb-session.h"
46 #include "afb-common.h"
49 #include <afb/afb-binding.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 static struct afb_config *config;
58 static pid_t childpid;
60 /*----------------------------------------------------------
61 | helpers for handling list of arguments
62 +--------------------------------------------------------- */
65 * Calls the callback 'run' for each value of the 'list'
66 * until the callback returns 0 or the end of the list is reached.
67 * Returns either NULL if the end of the list is reached or a pointer
68 * to the item whose value made 'run' return 0.
69 * 'closure' is used for passing user data.
71 static struct afb_config_list *run_for_list(struct afb_config_list *list,
72 int (*run) (void *closure, char *value),
75 while (list && run(closure, list->value))
80 static int run_start(void *closure, char *value)
82 int (*starter) (const char *value) = closure;
83 return starter(value) >= 0;
86 static void start_list(struct afb_config_list *list,
87 int (*starter) (const char *value), const char *message)
89 list = run_for_list(list, run_start, starter);
91 ERROR("can't start %s %s", message, list->value);
96 /*----------------------------------------------------------
98 | Handles on exit specific actions
99 +--------------------------------------------------------- */
100 static void exit_handler()
102 /* TODO: check whether using SIGHUP isn't better */
105 else if (childpid > 0)
106 killpg(childpid, SIGKILL);
109 /*----------------------------------------------------------
111 | set the process in background
112 +--------------------------------------------------------- */
113 static void daemonize()
118 // open /dev/console to redirect output messAFBes
119 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
121 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
124 // fork process when running background mode
127 // if fail nothing much to do
129 ERROR("AFB-daemon Failed to fork son process");
132 // if in father process, just leave
136 // son process get all data in standalone mode
137 NOTICE("background mode [pid:%d console:%s]", getpid(),
140 // redirect default I/O on console
142 dup(consoleFD); // redirect stderr
144 dup(consoleFD); // redirect stdout
145 close(0); // no need for stdin
149 setsid(); // allow father process to fully exit
150 sleep(2); // allow main to leave and release port
154 /*---------------------------------------------------------
156 | Handles the HTTP server
157 +--------------------------------------------------------- */
158 static int init_alias(void *closure, char *spec)
160 struct afb_hsrv *hsrv = closure;
161 char *path = strchr(spec, ':');
164 ERROR("Missing ':' in alias %s. Alias ignored", spec);
168 INFO("Alias for url=%s to path=%s", spec, path);
169 return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
173 static int init_http_server(struct afb_hsrv *hsrv)
175 if (!afb_hsrv_add_handler
176 (hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
179 if (!afb_hsrv_add_handler
180 (hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
183 if (run_for_list(config->aliases, init_alias, hsrv))
186 if (config->roothttp != NULL) {
187 if (!afb_hsrv_add_alias
188 (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
193 if (!afb_hsrv_add_handler
194 (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
201 static struct afb_hsrv *start_http_server()
204 struct afb_hsrv *hsrv;
206 if (afb_hreq_init_download_path(config->uploaddir)) {
207 ERROR("unable to set the upload directory %s", config->uploaddir);
211 hsrv = afb_hsrv_create();
213 ERROR("memory allocation failure");
217 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
218 || !init_http_server(hsrv)) {
219 ERROR("initialisation of httpd failed");
224 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
225 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
227 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
229 ERROR("starting of httpd failed");
237 /*---------------------------------------------------------
240 +--------------------------------------------------------- */
242 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
244 if (info->si_pid == childpid) {
245 switch (info->si_code) {
251 killpg(info->si_pid, SIGKILL);
252 waitpid(info->si_pid, NULL, 0);
264 #define SUBST_CHAR '@'
265 #define SUBST_STR "@"
267 static int instanciate_command_args()
269 char *orig, *repl, *sub, *val, port[20];
273 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
274 if (rc < 0 || rc >= (int)(sizeof port))
277 for (i = 0 ; (orig = config->exec[i]) ; i++) {
281 sub = strchrnul(orig, SUBST_CHAR);
284 repl = mempcpy(repl, orig, l);
289 if (repl || orig == config->exec[i])
291 repl = malloc(1 + s);
294 orig = config->exec[i];
295 config->exec[i] = repl;
300 case 'p': val = port; break;
301 case 't': val = config->token ? : ""; break;
303 case SUBST_CHAR: val = SUBST_STR; break;
308 repl = mempcpy(repl, val, l);
317 static int execute_command()
319 struct sigaction siga;
321 /* check whether a command is to execute or not */
322 if (!config->exec || !config->exec[0])
328 /* install signal handler */
329 memset(&siga, 0, sizeof siga);
330 siga.sa_sigaction = on_sigchld;
331 siga.sa_flags = SA_SIGINFO;
332 sigaction(SIGCHLD, &siga, NULL);
339 /* makes arguments */
340 if (instanciate_command_args() >= 0) {
343 execv(config->exec[0], config->exec);
344 ERROR("can't launch %s: %m", config->exec[0]);
350 /*---------------------------------------------------------
352 | Parse option and launch action
353 +--------------------------------------------------------- */
355 int main(int argc, char *argv[])
357 struct afb_hsrv *hsrv;
358 struct sd_event *eventloop;
360 LOGAUTH("afb-daemon");
362 // ------------- Build session handler & init config -------
363 config = afb_config_parse_arguments(argc, argv);
364 atexit(exit_handler);
366 // ------------------ sanity check ----------------------------------------
367 if (config->httpdPort <= 0) {
368 ERROR("no port is defined");
372 mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
373 if (chdir(config->workdir) < 0) {
374 ERROR("Can't enter working dir %s", config->workdir);
378 afb_api_so_set_timeout(config->apiTimeout);
379 start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
380 start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
381 start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
382 start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
384 afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
386 start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
387 start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
389 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
390 ERROR("initialisation of cookies failed");
394 if (afb_sig_handler_init() < 0) {
395 ERROR("failed to initialise signal handlers");
400 if (afb_common_rootdir_set(config->rootdir) < 0) {
401 ERROR("failed to set common root directory");
405 if (afb_thread_init(3, 1, 20) < 0) {
406 ERROR("failed to initialise threading");
409 // let's run this program with a low priority
412 // ------------------ Finaly Process Commands -----------------------------
413 // let's not take the risk to run as ROOT
414 //if (getuid() == 0) goto errorNoRoot;
416 DEBUG("Init config done");
418 // --------- run -----------
419 if (config->background) {
420 // --------- in background mode -----------
421 INFO("entering background mode");
424 // ---- in foreground mode --------------------
425 INFO("entering foreground mode");
428 /* ignore any SIGPIPE */
429 signal(SIGPIPE, SIG_IGN);
431 /* install trace of requests */
432 if (config->tracereq)
433 afb_hook_req_create(NULL, NULL, NULL, config->tracereq, NULL, NULL);
435 /* start the services */
436 if (afb_apis_start_all_services(1) < 0)
439 /* start the HTTP server */
440 if (!config->noHttpd) {
441 hsrv = start_http_server();
446 /* run the command */
447 if (execute_command() < 0)
450 /* signal that ready */
451 if (config->readyfd != 0) {
452 static const char readystr[] = "READY=1";
453 write(config->readyfd, readystr, sizeof(readystr) - 1);
454 close(config->readyfd);
458 eventloop = afb_common_get_event_loop();
459 sd_notify(1, "READY=1");
461 sd_event_run(eventloop, 30000000);
463 WARNING("hoops returned from infinite loop [report bug]");