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"
45 #include "afb-common.h"
47 #include "afb-plugin.h"
49 #if !defined(PLUGIN_INSTALL_DIR)
50 #error "you should define PLUGIN_INSTALL_DIR"
53 #define AFB_VERSION "0.1"
55 // Define command line option
57 #define SET_BACKGROUND 2
58 #define SET_FORGROUND 3
60 #define SET_TCP_PORT 5
61 #define SET_ROOT_DIR 6
62 #define SET_ROOT_BASE 7
63 #define SET_ROOT_API 8
66 #define SET_CACHE_TIMEOUT 10
67 #define SET_SESSION_DIR 11
69 #define SET_AUTH_TOKEN 12
71 #define SET_APITIMEOUT 14
72 #define SET_CNTXTIMEOUT 15
74 #define DISPLAY_VERSION 16
75 #define DISPLAY_HELP 17
78 #define SET_READYFD 19
80 // Command line structure hold cli --command + help text
82 int val; // command number within application
83 int has_arg; // command number within application
84 char *name; // command as used in --xxxx cli
85 char *help; // help text
90 static AFB_options cliOptions [] = {
91 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
93 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
94 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
96 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
97 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
98 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
99 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
100 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
102 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
103 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
104 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
106 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
108 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
109 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
111 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
112 {DISPLAY_HELP ,0,"help" , "Display this help"},
114 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
115 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
121 /*----------------------------------------------------------
123 | print version and copyright
124 +--------------------------------------------------------- */
125 static void printVersion (void)
127 fprintf (stderr,"\n----------------------------------------- \n");
128 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
129 fprintf (stderr,"----------------------------------------- \n");
130 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
131 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
132 fprintf (stderr,"| Licence Apache 2\n\n");
136 // load config from disk and merge with CLI option
137 static void config_set_default (struct afb_config * config)
140 if (config->httpdPort == 0)
141 config->httpdPort = 1234;
143 // default Plugin API timeout
144 if (config->apiTimeout == 0)
145 config->apiTimeout = DEFLT_API_TIMEOUT;
147 // default AUTH_TOKEN
148 if (config->token == NULL)
149 config->token = DEFLT_AUTH_TOKEN;
151 // cache timeout default one hour
152 if (config->cacheTimeout == 0)
153 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
155 // cache timeout default one hour
156 if (config->cntxTimeout == 0)
157 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
159 if (config->rootdir == NULL) {
160 config->rootdir = getenv("AFBDIR");
161 if (config->rootdir == NULL) {
162 config->rootdir = malloc (512);
163 strncpy (config->rootdir, getenv("HOME"),512);
164 strncat (config->rootdir, "/.AFB",512);
166 // if directory does not exist createit
167 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
170 // if no Angular/HTML5 rootbase let's try '/' as default
171 if (config->rootbase == NULL)
172 config->rootbase = "/opa";
174 if (config->rootapi == NULL)
175 config->rootapi = "/api";
177 if (config->ldpaths == NULL)
178 config->ldpaths = PLUGIN_INSTALL_DIR;
180 // if no session dir create a default path from rootdir
181 if (config->sessiondir == NULL) {
182 config->sessiondir = malloc (512);
183 strncpy (config->sessiondir, config->rootdir, 512);
184 strncat (config->sessiondir, "/sessions",512);
187 // if no config dir create a default path from sessiondir
188 if (config->console == NULL) {
189 config->console = malloc (512);
190 strncpy (config->console, config->sessiondir, 512);
191 strncat (config->console, "/AFB-console.out",512);
196 /*----------------------------------------------------------
198 | print information from long option array
199 +--------------------------------------------------------- */
201 static void printHelp(char *name) {
205 fprintf (stderr,"%s:\nallowed options\n", name);
206 for (ind=0; cliOptions [ind].name != NULL;ind++)
209 if (cliOptions [ind].has_arg == 0 )
211 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
213 sprintf(command,"%s=xxxx", cliOptions [ind].name);
214 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
217 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
220 /*---------------------------------------------------------
222 | Parse option and launch action
223 +--------------------------------------------------------- */
225 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
227 char* programName = argv [0];
231 struct option *gnuOptions;
233 // ------------------ Process Command Line -----------------------
235 // if no argument print help and return
237 printHelp(programName);
241 // build GNU getopt info from cliOptions
242 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
243 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
244 for (ind=0; ind < nbcmd;ind++) {
245 gnuOptions [ind].name = cliOptions[ind].name;
246 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
247 gnuOptions [ind].flag = 0;
248 gnuOptions [ind].val = cliOptions[ind].val;
251 // get all options from command line
252 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
262 if (optarg == 0) goto needValueForOption;
263 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
267 if (optarg == 0) goto needValueForOption;
268 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
271 case SET_CNTXTIMEOUT:
272 if (optarg == 0) goto needValueForOption;
273 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
277 if (optarg == 0) goto needValueForOption;
278 config->rootdir = optarg;
279 if (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",config->rootdir);
283 if (optarg == 0) goto needValueForOption;
284 config->rootbase = optarg;
285 if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",config->rootbase);
289 if (optarg == 0) goto needValueForOption;
290 config->rootapi = optarg;
291 if (verbosity) fprintf(stderr, "Forcing Rootapi=%s\n",config->rootapi);
295 if (optarg == 0) goto needValueForOption;
296 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
297 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
298 if (optarg == NULL) {
299 fprintf(stderr, "missing ':' in alias %s, ignored\n", config->aliasdir[config->aliascount].url);
301 config->aliasdir[config->aliascount].path = optarg;
302 if (verbosity) fprintf(stderr, "Alias url=%s path=%s\n", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
303 config->aliascount++;
306 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
311 if (optarg == 0) goto needValueForOption;
312 config->token = optarg;
316 if (optarg == 0) goto needValueForOption;
317 config->ldpaths = optarg;
320 case SET_SESSION_DIR:
321 if (optarg == 0) goto needValueForOption;
322 config->sessiondir = optarg;
325 case SET_CACHE_TIMEOUT:
326 if (optarg == 0) goto needValueForOption;
327 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
331 if (optarg != 0) goto noValueForOption;
332 config->background = 0;
336 if (optarg != 0) goto noValueForOption;
337 config->background = 1;
341 if (optarg == 0) goto needValueForOption;
342 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
343 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
344 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
349 if (optarg == 0) goto needValueForOption;
350 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
353 case DISPLAY_VERSION:
354 if (optarg != 0) goto noValueForOption;
360 printHelp(programName);
366 config_set_default (config);
371 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
372 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
376 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
377 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
381 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
382 ,gnuOptions[optionIndex].name);
386 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
387 ,gnuOptions[optionIndex].name);
391 /*----------------------------------------------------------
393 | try to close everything before leaving
394 +--------------------------------------------------------- */
395 static void closeSession (int status, void *data) {
396 /* struct afb_config *config = data; */
399 /*----------------------------------------------------------
401 +--------------------------------------------------------- */
402 void signalQuit (int signum)
404 fprintf(stderr, "Terminating signal received %s\n", strsignal(signum));
409 /*----------------------------------------------------------
412 +--------------------------------------------------------- */
413 __thread sigjmp_buf *error_handler;
414 static void signalError(int signum)
418 // unlock signal to allow a new signal to come
419 if (error_handler != NULL) {
420 sigemptyset(&sigset);
421 sigaddset(&sigset, signum);
422 sigprocmask(SIG_UNBLOCK, &sigset, 0);
423 longjmp(*error_handler, signum);
425 if (signum == SIGALRM)
427 fprintf(stderr, "Unmonitored signal received %s\n", strsignal(signum));
431 static void install_error_handlers()
433 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
435 for (i = 0; signals[i] != 0; i++) {
436 if (signal(signals[i], signalError) == SIG_ERR) {
437 fprintf(stderr, "Signal handler error\n");
443 /*----------------------------------------------------------
445 | set the process in background
446 +--------------------------------------------------------- */
447 static void daemonize(struct afb_config *config)
452 // open /dev/console to redirect output messAFBes
453 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
455 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
459 // fork process when running background mode
462 // if fail nothing much to do
464 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
468 // if in father process, just leave
469 if (pid != 0) _exit (0);
471 // son process get all data in standalone mode
472 fprintf (stderr, "\nAFB: background mode [pid:%d console:%s]\n", getpid(),config->console);
474 // redirect default I/O on console
475 close (2); dup(consoleFD); // redirect stderr
476 close (1); dup(consoleFD); // redirect stdout
477 close (0); // no need for stdin
481 setsid(); // allow father process to fully exit
482 sleep (2); // allow main to leave and release port
485 fprintf (stderr, "----------------------------\n");
486 fprintf (stderr, "INF: main background pid=%d\n", getpid());
490 /*---------------------------------------------------------
492 | Handles the HTTP server
493 +--------------------------------------------------------- */
494 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
498 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
501 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
504 for (idx = 0; idx < config->aliascount; idx++)
505 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0))
508 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10))
511 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
517 static struct afb_hsrv *start_http_server(struct afb_config * config)
520 struct afb_hsrv *hsrv;
522 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
523 fprintf(stderr, "unable to set the tmp directory\n");
527 hsrv = afb_hsrv_create();
529 fprintf(stderr, "memory allocation failure\n");
533 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
534 || !init_http_server(hsrv, config)) {
535 fprintf (stderr, "Error: initialisation of httpd failed");
541 fprintf (stderr, "AFB:notice Waiting port=%d rootdir=%s\n", config->httpdPort, config->rootdir);
542 fprintf (stderr, "AFB:notice Browser URL= http:/*localhost:%d\n", config->httpdPort);
545 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
547 fprintf (stderr, "Error: starting of httpd failed");
556 /*---------------------------------------------------------
558 | Parse option and launch action
559 +--------------------------------------------------------- */
561 int main(int argc, char *argv[]) {
562 struct afb_hsrv *hsrv;
563 struct afb_config *config;
564 struct sd_event *eventloop;
566 // open syslog if ever needed
567 openlog("afb-daemon", 0, LOG_DAEMON);
569 // ------------- Build session handler & init config -------
570 config = calloc (1, sizeof (struct afb_config));
572 on_exit(closeSession, config);
573 parse_arguments(argc, argv, config);
575 // ------------------ sanity check ----------------------------------------
576 if (config->httpdPort <= 0) {
577 fprintf (stderr, "ERR: no port is defined\n");
582 afb_api_so_add_pathset(config->ldpaths);
584 ctxStoreInit(CTX_NBCLIENTS, config->cntxTimeout, config->token, afb_apis_count());
585 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
586 fprintf (stderr, "ERR: initialisation of cookies failed\n");
590 install_error_handlers();
592 // ------------------ clean exit on CTR-C signal ------------------------
593 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
594 fprintf (stderr, "ERR: main fail to install Signal handler\n");
598 // let's run this program with a low priority
601 // ------------------ Finaly Process Commands -----------------------------
602 // let's not take the risk to run as ROOT
603 //if (getuid() == 0) goto errorNoRoot;
605 if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
607 // --------- run -----------
608 if (config->background) {
609 // --------- in background mode -----------
610 if (verbosity) fprintf (stderr, "AFB: Entering background mode\n");
613 // ---- in foreground mode --------------------
614 if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
618 hsrv = start_http_server(config);
622 if (config->readyfd != 0) {
623 static const char readystr[] = "READY=1";
624 write(config->readyfd, readystr, sizeof(readystr) - 1);
625 close(config->readyfd);
629 eventloop = afb_common_get_event_loop();
631 sd_event_run(eventloop, 30000000);
634 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");