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>
30 #include "afb-plugin.h"
32 #include "local-def.h"
33 #include "afb-hswitch.h"
34 #include "afb-api-so.h"
38 #include "utils-upoll.h"
40 #if !defined(PLUGIN_INSTALL_DIR)
41 #error "you should define PLUGIN_INSTALL_DIR"
44 #define AFB_VERSION "0.1"
46 // Define command line option
48 #define SET_BACKGROUND 2
49 #define SET_FORGROUND 3
51 #define SET_TCP_PORT 5
52 #define SET_ROOT_DIR 6
53 #define SET_ROOT_BASE 7
54 #define SET_ROOT_API 8
57 #define SET_CACHE_TIMEOUT 10
58 #define SET_SESSION_DIR 11
60 #define SET_AUTH_TOKEN 12
62 #define SET_APITIMEOUT 14
63 #define SET_CNTXTIMEOUT 15
65 #define DISPLAY_VERSION 16
66 #define DISPLAY_HELP 17
69 #define SET_READYFD 19
71 static struct afb_hsrv *start(AFB_config * config);
73 // Command line structure hold cli --command + help text
75 int val; // command number within application
76 int has_arg; // command number within application
77 char *name; // command as used in --xxxx cli
78 char *help; // help text
83 static AFB_options cliOptions [] = {
84 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
86 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
87 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
89 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
90 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
91 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
92 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
93 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
95 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
96 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
97 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
99 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
101 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
102 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
104 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
105 {DISPLAY_HELP ,0,"help" , "Display this help"},
107 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
108 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
112 static AFB_aliasdir aliasdir[MAX_ALIAS];
113 static int aliascount = 0;
116 /*----------------------------------------------------------
118 | print version and copyright
119 +--------------------------------------------------------- */
120 static void printVersion (void)
122 fprintf (stderr,"\n----------------------------------------- \n");
123 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
124 fprintf (stderr,"----------------------------------------- \n");
125 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
126 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
127 fprintf (stderr,"| Licence Apache 2\n\n");
131 // load config from disk and merge with CLI option
132 static void config_set_default (AFB_config * config)
135 if (config->httpdPort == 0)
136 config->httpdPort = 1234;
138 // default Plugin API timeout
139 if (config->apiTimeout == 0)
140 config->apiTimeout = DEFLT_API_TIMEOUT;
142 // default AUTH_TOKEN
143 if (config->token == NULL)
144 config->token = DEFLT_AUTH_TOKEN;
146 // cache timeout default one hour
147 if (config->cacheTimeout == 0)
148 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
150 // cache timeout default one hour
151 if (config->cntxTimeout == 0)
152 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
154 if (config->rootdir == NULL) {
155 config->rootdir = getenv("AFBDIR");
156 if (config->rootdir == NULL) {
157 config->rootdir = malloc (512);
158 strncpy (config->rootdir, getenv("HOME"),512);
159 strncat (config->rootdir, "/.AFB",512);
161 // if directory does not exist createit
162 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
165 // if no Angular/HTML5 rootbase let's try '/' as default
166 if (config->rootbase == NULL)
167 config->rootbase = "/opa";
169 if (config->rootapi == NULL)
170 config->rootapi = "/api";
172 if (config->ldpaths == NULL)
173 config->ldpaths = PLUGIN_INSTALL_DIR;
175 // if no session dir create a default path from rootdir
176 if (config->sessiondir == NULL) {
177 config->sessiondir = malloc (512);
178 strncpy (config->sessiondir, config->rootdir, 512);
179 strncat (config->sessiondir, "/sessions",512);
182 // if no config dir create a default path from sessiondir
183 if (config->console == NULL) {
184 config->console = malloc (512);
185 strncpy (config->console, config->sessiondir, 512);
186 strncat (config->console, "/AFB-console.out",512);
191 /*----------------------------------------------------------
193 | print information from long option array
194 +--------------------------------------------------------- */
196 static void printHelp(char *name) {
200 fprintf (stderr,"%s:\nallowed options\n", name);
201 for (ind=0; cliOptions [ind].name != NULL;ind++)
204 if (cliOptions [ind].has_arg == 0 )
206 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
208 sprintf(command,"%s=xxxx", cliOptions [ind].name);
209 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
212 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
215 /*---------------------------------------------------------
217 | Parse option and launch action
218 +--------------------------------------------------------- */
220 static void parse_arguments(int argc, char *argv[], AFB_session *session)
222 char* programName = argv [0];
226 struct option *gnuOptions;
228 // ------------- Build session handler & init config -------
229 memset(&aliasdir ,0,sizeof(aliasdir));
230 session->config->aliasdir = aliasdir;
232 // ------------------ Process Command Line -----------------------
234 // if no argument print help and return
236 printHelp(programName);
240 // build GNU getopt info from cliOptions
241 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
242 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
243 for (ind=0; ind < nbcmd;ind++) {
244 gnuOptions [ind].name = cliOptions[ind].name;
245 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
246 gnuOptions [ind].flag = 0;
247 gnuOptions [ind].val = cliOptions[ind].val;
250 // get all options from command line
251 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
261 if (optarg == 0) goto needValueForOption;
262 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
266 if (optarg == 0) goto needValueForOption;
267 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
270 case SET_CNTXTIMEOUT:
271 if (optarg == 0) goto needValueForOption;
272 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
276 if (optarg == 0) goto needValueForOption;
277 session->config->rootdir = optarg;
278 if (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
282 if (optarg == 0) goto needValueForOption;
283 session->config->rootbase = optarg;
284 if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
288 if (optarg == 0) goto needValueForOption;
289 session->config->rootapi = optarg;
290 if (verbosity) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
294 if (optarg == 0) goto needValueForOption;
295 if (aliascount < MAX_ALIAS) {
296 aliasdir[aliascount].url = strsep(&optarg,":");
297 if (optarg == NULL) {
298 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
300 aliasdir[aliascount].path = optarg;
301 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
302 if (verbosity) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
306 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
311 if (optarg == 0) goto needValueForOption;
312 session->config->token = optarg;
316 if (optarg == 0) goto needValueForOption;
317 session->config->ldpaths = optarg;
320 case SET_SESSION_DIR:
321 if (optarg == 0) goto needValueForOption;
322 session->config->sessiondir = optarg;
325 case SET_CACHE_TIMEOUT:
326 if (optarg == 0) goto needValueForOption;
327 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
331 if (optarg != 0) goto noValueForOption;
332 session->background = 0;
336 if (optarg != 0) goto noValueForOption;
337 session->background = 1;
341 if (optarg == 0) goto needValueForOption;
342 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
343 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
344 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
349 if (optarg == 0) goto needValueForOption;
350 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
353 case DISPLAY_VERSION:
354 if (optarg != 0) goto noValueForOption;
360 printHelp(programName);
366 config_set_default (session->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 /* AFB_session *session = 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(AFB_session *session)
452 // open /dev/console to redirect output messAFBes
453 consoleFD = open(session->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 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->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 | Parse option and launch action
493 +--------------------------------------------------------- */
495 int main(int argc, char *argv[]) {
496 AFB_session *session;
497 struct afb_hsrv *hsrv;
499 // open syslog if ever needed
500 openlog("afb-daemon", 0, LOG_DAEMON);
502 // ------------- Build session handler & init config -------
503 session = calloc (1, sizeof (AFB_session));
504 session->config = calloc (1, sizeof (AFB_config));
506 on_exit(closeSession, session);
507 parse_arguments(argc, argv, session);
509 // ------------------ sanity check ----------------------------------------
510 if (session->config->httpdPort <= 0) {
511 fprintf (stderr, "ERR: no port is defined\n");
515 if (session->config->ldpaths)
516 afb_api_so_add_pathset(session->config->ldpaths);
518 ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, session->config->token);
520 install_error_handlers();
522 // ------------------ clean exit on CTR-C signal ------------------------
523 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
524 fprintf (stderr, "ERR: main fail to install Signal handler\n");
528 // let's run this program with a low priority
531 // ------------------ Finaly Process Commands -----------------------------
532 // let's not take the risk to run as ROOT
533 //if (getuid() == 0) goto errorNoRoot;
535 if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
537 // --------- run -----------
538 if (session->background) {
539 // --------- in background mode -----------
540 if (verbosity) printf ("AFB: Entering background mode\n");
543 // ---- in foreground mode --------------------
544 if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
548 hsrv = start (session->config);
552 if (session->readyfd != 0) {
553 static const char readystr[] = "READY=1";
554 write(session->readyfd, readystr, sizeof(readystr) - 1);
555 close(session->readyfd);
563 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
568 static int init(struct afb_hsrv *hsrv, AFB_config * config)
572 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
575 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
578 for (idx = 0; config->aliasdir[idx].url != NULL; idx++)
579 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0))
582 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10))
585 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
591 static struct afb_hsrv *start(AFB_config * config)
594 struct afb_hsrv *hsrv;
596 hsrv = afb_hsrv_create();
598 fprintf(stderr, "memory allocation failure\n");
602 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
603 || !init(hsrv, config)) {
604 printf("Error: initialisation of httpd failed");
610 printf("AFB:notice Waiting port=%d rootdir=%s\n", config->httpdPort, config->rootdir);
611 printf("AFB:notice Browser URL= http:/*localhost:%d\n", config->httpdPort);
614 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
616 printf("Error: starting of httpd failed");