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>
31 #include "afb-plugin.h"
33 #include "local-def.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
50 #define SET_FAKE_MOD 4
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 // Command line structure hold cli --command + help text
74 int val; // command number within application
75 int has_arg; // command number within application
76 char *name; // command as used in --xxxx cli
77 char *help; // help text
82 static AFB_options cliOptions [] = {
83 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
85 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
86 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
88 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
89 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
90 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
91 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
92 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
94 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
95 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
96 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
98 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
100 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
101 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
103 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
104 {DISPLAY_HELP ,0,"help" , "Display this help"},
106 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
107 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
111 static AFB_aliasdir aliasdir[MAX_ALIAS];
112 static int aliascount = 0;
115 /*----------------------------------------------------------
117 | print version and copyright
118 +--------------------------------------------------------- */
119 static void printVersion (void)
121 fprintf (stderr,"\n----------------------------------------- \n");
122 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
123 fprintf (stderr,"----------------------------------------- \n");
124 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
125 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
126 fprintf (stderr,"| Licence Apache 2\n\n");
130 // load config from disk and merge with CLI option
131 static void config_set_default (AFB_session * session)
133 static char cacheTimeout [10];
136 if (session->config->httpdPort == 0)
137 session->config->httpdPort = 1234;
139 // default Plugin API timeout
140 if (session->config->apiTimeout == 0)
141 session->config->apiTimeout = DEFLT_API_TIMEOUT;
143 // default AUTH_TOKEN
144 if (session->config->token == NULL)
145 session->config->token = DEFLT_AUTH_TOKEN;
147 // cache timeout default one hour
148 if (session->config->cacheTimeout == 0)
149 session->config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
151 // cache timeout default one hour
152 if (session->config->cntxTimeout == 0)
153 session->config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
155 if (session->config->rootdir == NULL) {
156 session->config->rootdir = getenv("AFBDIR");
157 if (session->config->rootdir == NULL) {
158 session->config->rootdir = malloc (512);
159 strncpy (session->config->rootdir, getenv("HOME"),512);
160 strncat (session->config->rootdir, "/.AFB",512);
162 // if directory does not exist createit
163 mkdir (session->config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
166 // if no Angular/HTML5 rootbase let's try '/' as default
167 if (session->config->rootbase == NULL)
168 session->config->rootbase = "/opa";
170 if (session->config->rootapi == NULL)
171 session->config->rootapi = "/api";
173 if (session->config->ldpaths == NULL)
174 session->config->ldpaths = PLUGIN_INSTALL_DIR;
176 // if no session dir create a default path from rootdir
177 if (session->config->sessiondir == NULL) {
178 session->config->sessiondir = malloc (512);
179 strncpy (session->config->sessiondir, session->config->rootdir, 512);
180 strncat (session->config->sessiondir, "/sessions",512);
183 // if no config dir create a default path from sessiondir
184 if (session->config->console == NULL) {
185 session->config->console = malloc (512);
186 strncpy (session->config->console, session->config->sessiondir, 512);
187 strncat (session->config->console, "/AFB-console.out",512);
190 // cacheTimeout is an integer but HTTPd wants it as a string
191 snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
192 session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
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[], AFB_session *session)
227 char* programName = argv [0];
231 struct option *gnuOptions;
233 // ------------- Build session handler & init config -------
234 memset(&aliasdir ,0,sizeof(aliasdir));
235 session->config->aliasdir = aliasdir;
237 // ------------------ Process Command Line -----------------------
239 // if no argument print help and return
241 printHelp(programName);
245 // build GNU getopt info from cliOptions
246 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
247 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
248 for (ind=0; ind < nbcmd;ind++) {
249 gnuOptions [ind].name = cliOptions[ind].name;
250 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
251 gnuOptions [ind].flag = 0;
252 gnuOptions [ind].val = cliOptions[ind].val;
255 // get all options from command line
256 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
266 if (optarg == 0) goto needValueForOption;
267 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
271 if (optarg == 0) goto needValueForOption;
272 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
275 case SET_CNTXTIMEOUT:
276 if (optarg == 0) goto needValueForOption;
277 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
281 if (optarg == 0) goto needValueForOption;
282 session->config->rootdir = optarg;
283 if (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
287 if (optarg == 0) goto needValueForOption;
288 session->config->rootbase = optarg;
289 if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
293 if (optarg == 0) goto needValueForOption;
294 session->config->rootapi = optarg;
295 if (verbosity) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
299 if (optarg == 0) goto needValueForOption;
300 if (aliascount < MAX_ALIAS) {
301 aliasdir[aliascount].url = strsep(&optarg,":");
302 if (optarg == NULL) {
303 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
305 aliasdir[aliascount].path = optarg;
306 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
307 if (verbosity) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
311 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
316 if (optarg == 0) goto needValueForOption;
317 session->config->token = optarg;
321 if (optarg == 0) goto needValueForOption;
322 session->config->ldpaths = optarg;
325 case SET_SESSION_DIR:
326 if (optarg == 0) goto needValueForOption;
327 session->config->sessiondir = optarg;
330 case SET_CACHE_TIMEOUT:
331 if (optarg == 0) goto needValueForOption;
332 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
336 if (optarg != 0) goto noValueForOption;
337 session->fakemod = 1;
341 if (optarg != 0) goto noValueForOption;
342 session->foreground = 1;
346 if (optarg != 0) goto noValueForOption;
347 session->background = 1;
351 if (optarg == 0) goto needValueForOption;
352 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
353 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
354 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
359 if (optarg == 0) goto needValueForOption;
360 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
363 case DISPLAY_VERSION:
364 if (optarg != 0) goto noValueForOption;
370 printHelp(programName);
376 config_set_default (session);
381 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
382 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
386 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
387 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
391 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
392 ,gnuOptions[optionIndex].name);
396 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
397 ,gnuOptions[optionIndex].name);
401 /*----------------------------------------------------------
403 | try to close everything before leaving
404 +--------------------------------------------------------- */
405 static void closeSession (int status, void *data) {
406 /* AFB_session *session = data; */
409 /*----------------------------------------------------------
411 +--------------------------------------------------------- */
412 void signalQuit (int signum)
414 fprintf(stderr, "Terminating signal received %s\n", strsignal(signum));
419 /*----------------------------------------------------------
422 +--------------------------------------------------------- */
423 __thread sigjmp_buf *error_handler;
424 static void signalError(int signum)
428 // unlock signal to allow a new signal to come
429 if (error_handler != NULL) {
430 sigemptyset(&sigset);
431 sigaddset(&sigset, signum);
432 sigprocmask(SIG_UNBLOCK, &sigset, 0);
433 longjmp(*error_handler, signum);
435 if (signum == SIGALRM)
437 fprintf(stderr, "Unmonitored signal received %s\n", strsignal(signum));
441 static void install_error_handlers()
443 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
445 for (i = 0; signals[i] != 0; i++) {
446 if (signal(signals[i], signalError) == SIG_ERR) {
447 fprintf(stderr, "Signal handler error\n");
453 /*----------------------------------------------------------
455 | set the process in background
456 +--------------------------------------------------------- */
457 static void daemonize(AFB_session *session)
462 // open /dev/console to redirect output messAFBes
463 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
465 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
469 // fork process when running background mode
472 // if fail nothing much to do
474 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
478 // if in father process, just leave
479 if (pid != 0) _exit (0);
481 // son process get all data in standalone mode
482 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
484 // redirect default I/O on console
485 close (2); dup(consoleFD); // redirect stderr
486 close (1); dup(consoleFD); // redirect stdout
487 close (0); // no need for stdin
491 setsid(); // allow father process to fully exit
492 sleep (2); // allow main to leave and release port
495 fprintf (stderr, "----------------------------\n");
496 fprintf (stderr, "INF: main background pid=%d\n", getpid());
500 /*---------------------------------------------------------
502 | Parse option and launch action
503 +--------------------------------------------------------- */
505 int main(int argc, char *argv[]) {
507 AFB_session *session;
509 // open syslog if ever needed
510 openlog("afb-daemon", 0, LOG_DAEMON);
512 // ------------- Build session handler & init config -------
513 session = calloc (1, sizeof (AFB_session));
514 session->config = calloc (1, sizeof (AFB_config));
516 on_exit(closeSession, session);
517 parse_arguments(argc, argv, session);
519 // ------------------ sanity check ----------------------------------------
520 if ((session->background) && (session->foreground)) {
521 fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
524 if (session->config->httpdPort <= 0) {
525 fprintf (stderr, "ERR: no port is defined\n");
529 if (session->config->ldpaths)
530 afb_apis_add_pathset(session->config->ldpaths);
532 ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, afb_apis_count(), session->config->token);
534 install_error_handlers();
536 // ------------------ Some useful default values -------------------------
537 if ((session->background == 0) && (session->foreground == 0))
538 session->foreground = 1;
540 // ------------------ clean exit on CTR-C signal ------------------------
541 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
542 fprintf (stderr, "ERR: main fail to install Signal handler\n");
546 // let's run this program with a low priority
549 // ------------------ Finaly Process Commands -----------------------------
550 // let's not take the risk to run as ROOT
551 //if (getuid() == 0) goto errorNoRoot;
553 if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
555 // ---- run in foreground mode --------------------
556 if (session->foreground) {
558 if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
562 // --------- run in background mode -----------
563 if (session->background) {
565 if (verbosity) printf ("AFB: Entering background mode\n");
569 // if everything look OK then look forever
570 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
573 } // end background-foreground
576 // ------ Start httpd server
578 rc = afb_hsrv_start (session);
582 if (session->readyfd != 0) {
583 static const char readystr[] = "READY=1";
584 write(session->readyfd, readystr, sizeof(readystr) - 1);
585 close(session->readyfd);
593 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");