2 * Copyright (C) 2015 "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.
28 #include <sys/types.h>
35 #include <systemd/sd-event.h>
37 #include "afb-config.h"
38 #include "afb-hswitch.h"
40 #include "afb-api-so.h"
42 #include "afb-context.h"
46 #include "afb-common.h"
48 #include "afb-plugin.h"
50 #if !defined(PLUGIN_INSTALL_DIR)
51 #error "you should define PLUGIN_INSTALL_DIR"
54 #define AFB_VERSION "0.4"
56 // Define command line option
58 #define SET_BACKGROUND 2
59 #define SET_FORGROUND 3
61 #define SET_TCP_PORT 5
62 #define SET_ROOT_DIR 6
63 #define SET_ROOT_BASE 7
64 #define SET_ROOT_API 8
67 #define SET_CACHE_TIMEOUT 10
68 #define SET_SESSION_DIR 11
70 #define SET_AUTH_TOKEN 12
72 #define SET_APITIMEOUT 14
73 #define SET_CNTXTIMEOUT 15
75 #define DISPLAY_VERSION 16
76 #define DISPLAY_HELP 17
79 #define SET_READYFD 19
81 // Command line structure hold cli --command + help text
83 int val; // command number within application
84 int has_arg; // command number within application
85 char *name; // command as used in --xxxx cli
86 char *help; // help text
91 static AFB_options cliOptions [] = {
92 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
94 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
95 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
97 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
98 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
99 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
100 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
101 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
103 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
104 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
105 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
107 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
109 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
110 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
112 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
113 {DISPLAY_HELP ,0,"help" , "Display this help"},
115 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
116 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
122 /*----------------------------------------------------------
124 | print version and copyright
125 +--------------------------------------------------------- */
126 static void printVersion (FILE *file)
128 fprintf(file, "\n----------------------------------------- \n");
129 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
130 fprintf(file, " \n");
131 fprintf(file, " Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
132 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
133 fprintf(file, " Licence Apache 2\n\n");
137 /*----------------------------------------------------------
139 | print information from long option array
140 +--------------------------------------------------------- */
142 static void printHelp(FILE *file, const char *name)
147 fprintf (file, "%s:\nallowed options\n", name);
148 for (ind=0; cliOptions [ind].name != NULL;ind++)
151 if (cliOptions [ind].has_arg == 0 )
153 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
155 sprintf(command, "%s=xxxx", cliOptions [ind].name);
156 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
159 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
162 // load config from disk and merge with CLI option
163 static void config_set_default (struct afb_config * config)
166 if (config->httpdPort == 0)
167 config->httpdPort = 1234;
169 // default Plugin API timeout
170 if (config->apiTimeout == 0)
171 config->apiTimeout = DEFLT_API_TIMEOUT;
173 // default AUTH_TOKEN
174 if (config->token == NULL)
175 config->token = DEFLT_AUTH_TOKEN;
177 // cache timeout default one hour
178 if (config->cacheTimeout == 0)
179 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
181 // cache timeout default one hour
182 if (config->cntxTimeout == 0)
183 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
185 if (config->rootdir == NULL) {
186 config->rootdir = getenv("AFBDIR");
187 if (config->rootdir == NULL) {
188 config->rootdir = malloc (512);
189 strncpy (config->rootdir, getenv("HOME"),512);
190 strncat (config->rootdir, "/.AFB",512);
192 // if directory does not exist createit
193 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
196 // if no Angular/HTML5 rootbase let's try '/' as default
197 if (config->rootbase == NULL)
198 config->rootbase = "/opa";
200 if (config->rootapi == NULL)
201 config->rootapi = "/api";
203 if (config->ldpaths == NULL)
204 config->ldpaths = PLUGIN_INSTALL_DIR;
206 // if no session dir create a default path from rootdir
207 if (config->sessiondir == NULL) {
208 config->sessiondir = malloc (512);
209 strncpy (config->sessiondir, config->rootdir, 512);
210 strncat (config->sessiondir, "/sessions",512);
213 // if no config dir create a default path from sessiondir
214 if (config->console == NULL) {
215 config->console = malloc (512);
216 strncpy (config->console, config->sessiondir, 512);
217 strncat (config->console, "/AFB-console.out",512);
222 /*---------------------------------------------------------
224 | Parse option and launch action
225 +--------------------------------------------------------- */
227 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
229 char* programName = argv [0];
233 struct option *gnuOptions;
235 // ------------------ Process Command Line -----------------------
237 // if no argument print help and return
239 printHelp(stderr, programName);
243 // build GNU getopt info from cliOptions
244 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
245 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
246 for (ind=0; ind < nbcmd;ind++) {
247 gnuOptions [ind].name = cliOptions[ind].name;
248 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
249 gnuOptions [ind].flag = 0;
250 gnuOptions [ind].val = cliOptions[ind].val;
253 // get all options from command line
254 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
264 if (optarg == 0) goto needValueForOption;
265 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
269 if (optarg == 0) goto needValueForOption;
270 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
273 case SET_CNTXTIMEOUT:
274 if (optarg == 0) goto needValueForOption;
275 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
279 if (optarg == 0) goto needValueForOption;
280 config->rootdir = optarg;
281 INFO("Forcing Rootdir=%s",config->rootdir);
285 if (optarg == 0) goto needValueForOption;
286 config->rootbase = optarg;
287 INFO("Forcing Rootbase=%s",config->rootbase);
291 if (optarg == 0) goto needValueForOption;
292 config->rootapi = optarg;
293 INFO("Forcing Rootapi=%s",config->rootapi);
297 if (optarg == 0) goto needValueForOption;
298 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
299 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
300 if (optarg == NULL) {
301 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
303 config->aliasdir[config->aliascount].path = optarg;
304 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
305 config->aliascount++;
308 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
313 if (optarg == 0) goto needValueForOption;
314 config->token = optarg;
318 if (optarg == 0) goto needValueForOption;
319 config->ldpaths = optarg;
322 case SET_SESSION_DIR:
323 if (optarg == 0) goto needValueForOption;
324 config->sessiondir = optarg;
327 case SET_CACHE_TIMEOUT:
328 if (optarg == 0) goto needValueForOption;
329 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
333 if (optarg != 0) goto noValueForOption;
334 config->background = 0;
338 if (optarg != 0) goto noValueForOption;
339 config->background = 1;
343 if (optarg == 0) goto needValueForOption;
344 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
345 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
346 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
351 if (optarg == 0) goto needValueForOption;
352 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
355 case DISPLAY_VERSION:
356 if (optarg != 0) goto noValueForOption;
357 printVersion(stdout);
362 printHelp(stdout, programName);
368 config_set_default (config);
373 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
374 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
378 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
379 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
383 ERROR("AFB-daemon option [--%s] don't take value"
384 ,gnuOptions[optionIndex].name);
388 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
389 ,gnuOptions[optionIndex].name);
393 /*----------------------------------------------------------
395 | try to close everything before leaving
396 +--------------------------------------------------------- */
397 static void closeSession (int status, void *data) {
398 /* struct afb_config *config = data; */
401 /*----------------------------------------------------------
403 +--------------------------------------------------------- */
404 void signalQuit (int signum)
406 ERROR("Terminating signal received %s", strsignal(signum));
411 /*----------------------------------------------------------
414 +--------------------------------------------------------- */
415 __thread sigjmp_buf *error_handler;
416 static void signalError(int signum)
420 // unlock signal to allow a new signal to come
421 if (error_handler != NULL) {
422 sigemptyset(&sigset);
423 sigaddset(&sigset, signum);
424 sigprocmask(SIG_UNBLOCK, &sigset, 0);
425 longjmp(*error_handler, signum);
427 if (signum == SIGALRM)
429 ERROR("Unmonitored signal received %s", strsignal(signum));
433 static void install_error_handlers()
435 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
437 for (i = 0; signals[i] != 0; i++) {
438 if (signal(signals[i], signalError) == SIG_ERR) {
439 ERROR("Signal handler error");
445 /*----------------------------------------------------------
447 | set the process in background
448 +--------------------------------------------------------- */
449 static void daemonize(struct afb_config *config)
454 // open /dev/console to redirect output messAFBes
455 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
457 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
461 // fork process when running background mode
464 // if fail nothing much to do
466 ERROR("AFB-daemon Failed to fork son process");
470 // if in father process, just leave
471 if (pid != 0) _exit (0);
473 // son process get all data in standalone mode
474 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
476 // redirect default I/O on console
477 close (2); dup(consoleFD); // redirect stderr
478 close (1); dup(consoleFD); // redirect stdout
479 close (0); // no need for stdin
483 setsid(); // allow father process to fully exit
484 sleep (2); // allow main to leave and release port
488 /*---------------------------------------------------------
490 | Handles the HTTP server
491 +--------------------------------------------------------- */
492 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
496 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
499 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
502 for (idx = 0; idx < config->aliascount; idx++)
503 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0))
506 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10))
509 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
515 static struct afb_hsrv *start_http_server(struct afb_config * config)
518 struct afb_hsrv *hsrv;
520 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
521 ERROR("unable to set the tmp directory");
525 hsrv = afb_hsrv_create();
527 ERROR("memory allocation failure");
531 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
532 || !init_http_server(hsrv, config)) {
533 ERROR("initialisation of httpd failed");
538 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
539 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
541 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
543 ERROR("starting of httpd failed");
552 /*---------------------------------------------------------
554 | Parse option and launch action
555 +--------------------------------------------------------- */
557 int main(int argc, char *argv[]) {
558 struct afb_hsrv *hsrv;
559 struct afb_config *config;
560 struct sd_event *eventloop;
562 // open syslog if ever needed
563 openlog("afb-daemon", 0, LOG_DAEMON);
565 // ------------- Build session handler & init config -------
566 config = calloc (1, sizeof (struct afb_config));
568 on_exit(closeSession, config);
569 parse_arguments(argc, argv, config);
571 // ------------------ sanity check ----------------------------------------
572 if (config->httpdPort <= 0) {
573 ERROR("no port is defined");
578 afb_api_so_add_pathset(config->ldpaths);
580 ctxStoreInit(CTX_NBCLIENTS, config->cntxTimeout, config->token, afb_apis_count());
581 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
582 ERROR("initialisation of cookies failed");
586 install_error_handlers();
588 // ------------------ clean exit on CTR-C signal ------------------------
589 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
590 ERROR("main fail to install Signal handler");
594 // let's run this program with a low priority
597 // ------------------ Finaly Process Commands -----------------------------
598 // let's not take the risk to run as ROOT
599 //if (getuid() == 0) goto errorNoRoot;
601 DEBUG("Init config done");
603 // --------- run -----------
604 if (config->background) {
605 // --------- in background mode -----------
606 INFO("entering background mode");
609 // ---- in foreground mode --------------------
610 INFO("entering foreground mode");
613 hsrv = start_http_server(config);
617 if (config->readyfd != 0) {
618 static const char readystr[] = "READY=1";
619 write(config->readyfd, readystr, sizeof(readystr) - 1);
620 close(config->readyfd);
624 eventloop = afb_common_get_event_loop();
626 sd_event_run(eventloop, 30000000);
628 WARNING("hoops returned from infinite loop [report bug]");