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"
39 #include "utils-upoll.h"
41 #if !defined(PLUGIN_INSTALL_DIR)
42 #error "you should define PLUGIN_INSTALL_DIR"
45 #define AFB_VERSION "0.1"
47 // Define command line option
49 #define SET_BACKGROUND 2
50 #define SET_FORGROUND 3
52 #define SET_TCP_PORT 5
53 #define SET_ROOT_DIR 6
54 #define SET_ROOT_BASE 7
55 #define SET_ROOT_API 8
58 #define SET_CACHE_TIMEOUT 10
59 #define SET_SESSION_DIR 11
61 #define SET_AUTH_TOKEN 12
63 #define SET_APITIMEOUT 14
64 #define SET_CNTXTIMEOUT 15
66 #define DISPLAY_VERSION 16
67 #define DISPLAY_HELP 17
70 #define SET_READYFD 19
72 static struct afb_hsrv *start(AFB_config * config);
74 // Command line structure hold cli --command + help text
76 int val; // command number within application
77 int has_arg; // command number within application
78 char *name; // command as used in --xxxx cli
79 char *help; // help text
84 static AFB_options cliOptions [] = {
85 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
87 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
88 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
90 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
91 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
92 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
93 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
94 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
96 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
97 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
98 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
100 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
102 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
103 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
105 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
106 {DISPLAY_HELP ,0,"help" , "Display this help"},
108 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
109 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
113 static AFB_aliasdir aliasdir[MAX_ALIAS];
114 static int aliascount = 0;
117 /*----------------------------------------------------------
119 | print version and copyright
120 +--------------------------------------------------------- */
121 static void printVersion (void)
123 fprintf (stderr,"\n----------------------------------------- \n");
124 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
125 fprintf (stderr,"----------------------------------------- \n");
126 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
127 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
128 fprintf (stderr,"| Licence Apache 2\n\n");
132 // load config from disk and merge with CLI option
133 static void config_set_default (AFB_config * config)
136 if (config->httpdPort == 0)
137 config->httpdPort = 1234;
139 // default Plugin API timeout
140 if (config->apiTimeout == 0)
141 config->apiTimeout = DEFLT_API_TIMEOUT;
143 // default AUTH_TOKEN
144 if (config->token == NULL)
145 config->token = DEFLT_AUTH_TOKEN;
147 // cache timeout default one hour
148 if (config->cacheTimeout == 0)
149 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
151 // cache timeout default one hour
152 if (config->cntxTimeout == 0)
153 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
155 if (config->rootdir == NULL) {
156 config->rootdir = getenv("AFBDIR");
157 if (config->rootdir == NULL) {
158 config->rootdir = malloc (512);
159 strncpy (config->rootdir, getenv("HOME"),512);
160 strncat (config->rootdir, "/.AFB",512);
162 // if directory does not exist createit
163 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
166 // if no Angular/HTML5 rootbase let's try '/' as default
167 if (config->rootbase == NULL)
168 config->rootbase = "/opa";
170 if (config->rootapi == NULL)
171 config->rootapi = "/api";
173 if (config->ldpaths == NULL)
174 config->ldpaths = PLUGIN_INSTALL_DIR;
176 // if no session dir create a default path from rootdir
177 if (config->sessiondir == NULL) {
178 config->sessiondir = malloc (512);
179 strncpy (config->sessiondir, config->rootdir, 512);
180 strncat (config->sessiondir, "/sessions",512);
183 // if no config dir create a default path from sessiondir
184 if (config->console == NULL) {
185 config->console = malloc (512);
186 strncpy (config->console, config->sessiondir, 512);
187 strncat (config->console, "/AFB-console.out",512);
192 /*----------------------------------------------------------
194 | print information from long option array
195 +--------------------------------------------------------- */
197 static void printHelp(char *name) {
201 fprintf (stderr,"%s:\nallowed options\n", name);
202 for (ind=0; cliOptions [ind].name != NULL;ind++)
205 if (cliOptions [ind].has_arg == 0 )
207 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
209 sprintf(command,"%s=xxxx", cliOptions [ind].name);
210 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
213 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
216 /*---------------------------------------------------------
218 | Parse option and launch action
219 +--------------------------------------------------------- */
221 static void parse_arguments(int argc, char *argv[], AFB_session *session)
223 char* programName = argv [0];
227 struct option *gnuOptions;
229 // ------------- Build session handler & init config -------
230 memset(&aliasdir ,0,sizeof(aliasdir));
231 session->config->aliasdir = aliasdir;
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", &session->config->httpdPort)) goto notAnInteger;
267 if (optarg == 0) goto needValueForOption;
268 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
271 case SET_CNTXTIMEOUT:
272 if (optarg == 0) goto needValueForOption;
273 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
277 if (optarg == 0) goto needValueForOption;
278 session->config->rootdir = optarg;
279 if (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
283 if (optarg == 0) goto needValueForOption;
284 session->config->rootbase = optarg;
285 if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
289 if (optarg == 0) goto needValueForOption;
290 session->config->rootapi = optarg;
291 if (verbosity) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
295 if (optarg == 0) goto needValueForOption;
296 if (aliascount < MAX_ALIAS) {
297 aliasdir[aliascount].url = strsep(&optarg,":");
298 if (optarg == NULL) {
299 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
301 aliasdir[aliascount].path = optarg;
302 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
303 if (verbosity) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
307 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
312 if (optarg == 0) goto needValueForOption;
313 session->config->token = optarg;
317 if (optarg == 0) goto needValueForOption;
318 session->config->ldpaths = optarg;
321 case SET_SESSION_DIR:
322 if (optarg == 0) goto needValueForOption;
323 session->config->sessiondir = optarg;
326 case SET_CACHE_TIMEOUT:
327 if (optarg == 0) goto needValueForOption;
328 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
332 if (optarg != 0) goto noValueForOption;
333 session->background = 0;
337 if (optarg != 0) goto noValueForOption;
338 session->background = 1;
342 if (optarg == 0) goto needValueForOption;
343 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
344 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
345 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
350 if (optarg == 0) goto needValueForOption;
351 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
354 case DISPLAY_VERSION:
355 if (optarg != 0) goto noValueForOption;
361 printHelp(programName);
367 config_set_default (session->config);
372 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
373 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
377 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
378 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
382 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
383 ,gnuOptions[optionIndex].name);
387 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
388 ,gnuOptions[optionIndex].name);
392 /*----------------------------------------------------------
394 | try to close everything before leaving
395 +--------------------------------------------------------- */
396 static void closeSession (int status, void *data) {
397 /* AFB_session *session = data; */
400 /*----------------------------------------------------------
402 +--------------------------------------------------------- */
403 void signalQuit (int signum)
405 fprintf(stderr, "Terminating signal received %s\n", strsignal(signum));
410 /*----------------------------------------------------------
413 +--------------------------------------------------------- */
414 __thread sigjmp_buf *error_handler;
415 static void signalError(int signum)
419 // unlock signal to allow a new signal to come
420 if (error_handler != NULL) {
421 sigemptyset(&sigset);
422 sigaddset(&sigset, signum);
423 sigprocmask(SIG_UNBLOCK, &sigset, 0);
424 longjmp(*error_handler, signum);
426 if (signum == SIGALRM)
428 fprintf(stderr, "Unmonitored signal received %s\n", strsignal(signum));
432 static void install_error_handlers()
434 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
436 for (i = 0; signals[i] != 0; i++) {
437 if (signal(signals[i], signalError) == SIG_ERR) {
438 fprintf(stderr, "Signal handler error\n");
444 /*----------------------------------------------------------
446 | set the process in background
447 +--------------------------------------------------------- */
448 static void daemonize(AFB_session *session)
453 // open /dev/console to redirect output messAFBes
454 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
456 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
460 // fork process when running background mode
463 // if fail nothing much to do
465 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
469 // if in father process, just leave
470 if (pid != 0) _exit (0);
472 // son process get all data in standalone mode
473 fprintf (stderr, "\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
475 // redirect default I/O on console
476 close (2); dup(consoleFD); // redirect stderr
477 close (1); dup(consoleFD); // redirect stdout
478 close (0); // no need for stdin
482 setsid(); // allow father process to fully exit
483 sleep (2); // allow main to leave and release port
486 fprintf (stderr, "----------------------------\n");
487 fprintf (stderr, "INF: main background pid=%d\n", getpid());
491 /*---------------------------------------------------------
493 | Parse option and launch action
494 +--------------------------------------------------------- */
496 int main(int argc, char *argv[]) {
497 AFB_session *session;
498 struct afb_hsrv *hsrv;
500 // open syslog if ever needed
501 openlog("afb-daemon", 0, LOG_DAEMON);
503 // ------------- Build session handler & init config -------
504 session = calloc (1, sizeof (AFB_session));
505 session->config = calloc (1, sizeof (AFB_config));
507 on_exit(closeSession, session);
508 parse_arguments(argc, argv, session);
510 // ------------------ sanity check ----------------------------------------
511 if (session->config->httpdPort <= 0) {
512 fprintf (stderr, "ERR: no port is defined\n");
516 if (session->config->ldpaths)
517 afb_api_so_add_pathset(session->config->ldpaths);
519 ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, session->config->token);
520 if (!afb_hreq_init_cookie(session->config->httpdPort, session->config->rootapi, DEFLT_CNTX_TIMEOUT)) {
521 fprintf (stderr, "ERR: initialisation of cookies failed\n");
525 install_error_handlers();
527 // ------------------ clean exit on CTR-C signal ------------------------
528 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
529 fprintf (stderr, "ERR: main fail to install Signal handler\n");
533 // let's run this program with a low priority
536 // ------------------ Finaly Process Commands -----------------------------
537 // let's not take the risk to run as ROOT
538 //if (getuid() == 0) goto errorNoRoot;
540 if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
542 // --------- run -----------
543 if (session->background) {
544 // --------- in background mode -----------
545 if (verbosity) fprintf (stderr, "AFB: Entering background mode\n");
548 // ---- in foreground mode --------------------
549 if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
553 hsrv = start (session->config);
557 if (session->readyfd != 0) {
558 static const char readystr[] = "READY=1";
559 write(session->readyfd, readystr, sizeof(readystr) - 1);
560 close(session->readyfd);
568 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
573 static int init(struct afb_hsrv *hsrv, AFB_config * config)
577 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
580 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
583 for (idx = 0; config->aliasdir[idx].url != NULL; idx++)
584 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0))
587 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10))
590 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
596 static struct afb_hsrv *start(AFB_config * config)
599 struct afb_hsrv *hsrv;
601 hsrv = afb_hsrv_create();
603 fprintf(stderr, "memory allocation failure\n");
607 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
608 || !init(hsrv, config)) {
609 fprintf (stderr, "Error: initialisation of httpd failed");
615 fprintf (stderr, "AFB:notice Waiting port=%d rootdir=%s\n", config->httpdPort, config->rootdir);
616 fprintf (stderr, "AFB:notice Browser URL= http:/*localhost:%d\n", config->httpdPort);
619 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
621 fprintf (stderr, "Error: starting of httpd failed");