2 * Copyright (C) 2015 "IoT.bzh"
3 * Author "Fulup Ar Foll"
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * Author: "Fulup Ar Foll"
23 * Created on 05 December 2015, 15:38
26 #include "local-def.h"
34 #define AFB_VERSION "0.1"
36 static sigjmp_buf exitPoint; // context save for set/longjmp
38 /*----------------------------------------------------------
40 | print version and copyright
41 +--------------------------------------------------------- */
42 static void printVersion (void) {
44 fprintf (stderr,"\n----------------------------------------- \n");
45 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
46 fprintf (stderr,"----------------------------------------- \n");
47 fprintf (stderr,"| Copyright(C) 2015 Fulup Ar Foll /IoT.bzh [fulup -at- iot.bzh]\n");
48 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
49 fprintf (stderr,"| Licence [what ever makes you happy] until you fix bugs by yourself :)\n\n");
54 // Define command line option
55 #define SET_VERBOSE 101
56 #define SET_BACKGROUND 105
57 #define SET_FORGROUND 106
58 #define KILL_PREV_EXIT 107
59 #define KILL_PREV_REST 108
60 #define SET_FAKE_MOD 109
62 #define SET_TCP_PORT 120
63 #define SET_ROOT_DIR 121
64 #define SET_ROOT_BASE 122
65 #define SET_ROOT_API 123
66 #define SET_ROOT_ALIAS 124
68 #define SET_CACHE_TO 130
69 #define SET_USERID 131
70 #define SET_PID_FILE 132
71 #define SET_SESSION_DIR 133
72 #define SET_CONFIG_FILE 134
73 #define SET_CONFIG_SAVE 135
74 #define SET_CONFIG_EXIT 138
76 #define SET_AUTH_TOKEN 141
77 #define SET_LDPATH 142
78 #define SET_APITIMEOUT 143
79 #define SET_CNTXTIMEOUT 144
81 #define DISPLAY_VERSION 150
82 #define DISPLAY_HELP 151
85 #define SET_READYFD 161
87 // Command line structure hold cli --command + help text
89 int val; // command number within application
90 int has_arg; // command number within application
91 char *name; // command as used in --xxxx cli
92 char *help; // help text
97 static AFB_options cliOptions [] = {
98 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
100 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
101 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
102 {KILL_PREV_EXIT ,0,"kill" , "Kill active process if any and exit"},
103 {KILL_PREV_REST ,0,"restart" , "Kill active process if any and restart"},
105 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
106 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
107 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
108 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
109 {SET_ROOT_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
111 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
112 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
113 {SET_CACHE_TO ,1,"cache-eol" , "Client cache end of live [default 3600s]"},
115 {SET_USERID ,1,"setuid" , "Change user id [default don't change]"},
116 {SET_PID_FILE ,1,"pidfile" , "PID file path [default none]"},
117 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
118 {SET_CONFIG_FILE ,1,"config" , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
120 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
121 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
123 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
124 {DISPLAY_HELP ,0,"help" , "Display this help"},
126 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
127 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
131 static AFB_aliasdir aliasdir[MAX_ALIAS];
132 static int aliascount=0;
134 /*----------------------------------------------------------
137 +--------------------------------------------------------- */
138 void signalQuit (int signum) {
142 // unlock timeout signal to allow a new signal to come
143 sigemptyset (&sigset);
144 sigaddset (&sigset, SIGABRT);
145 sigprocmask (SIG_UNBLOCK, &sigset, 0);
147 fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
148 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
149 longjmp (exitPoint, signum);
153 /*----------------------------------------------------------
155 | print information from long option array
156 +--------------------------------------------------------- */
158 static void printHelp(char *name) {
162 fprintf (stderr,"%s:\nallowed options\n", name);
163 for (ind=0; cliOptions [ind].name != NULL;ind++)
166 if (cliOptions [ind].has_arg == 0 )
168 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
170 sprintf(command,"%s=xxxx", cliOptions [ind].name);
171 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
174 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
177 /*----------------------------------------------------------
179 | write a file in /var/run/AFB with pid
180 +--------------------------------------------------------- */
181 static int writePidFile (AFB_config *config, int pid) {
184 // if no pid file configure just return
185 if (config->pidfile == NULL) return 0;
187 // open pid file in write mode
188 file = fopen(config->pidfile,"w");
190 fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
194 // write pid in file and close
195 fprintf (file, "%d\n", pid);
200 /*----------------------------------------------------------
202 | read file in /var/run/AFB with pid
203 +--------------------------------------------------------- */
204 static int readPidFile (AFB_config *config) {
209 if (config->pidfile == NULL) return -1;
211 // open pid file in write mode
212 file = fopen(config->pidfile,"r");
214 fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
218 // write pid in file and close
219 status = fscanf (file, "%d\n", &pid);
223 if (status != 1) return -1;
228 /*----------------------------------------------------------
230 | try to close everything before leaving
231 +--------------------------------------------------------- */
232 static void closeSession (AFB_session *session) {
237 /*----------------------------------------------------------
239 | Main listening HTTP loop
240 +--------------------------------------------------------- */
241 static void listenLoop (AFB_session *session) {
244 if (signal (SIGABRT, signalQuit) == SIG_ERR) {
245 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
249 // ------ Start httpd server
250 if (session->config->httpdPort > 0) {
252 err = httpdStart (session);
253 if (err != AFB_SUCCESS) return;
255 if (session->readyfd != 0) {
256 static const char readystr[] = "READY=1";
257 write(session->readyfd, readystr, sizeof(readystr) - 1);
258 close(session->readyfd);
264 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
268 /*---------------------------------------------------------
270 | Parse option and launch action
271 +--------------------------------------------------------- */
273 static void parse_arguments(int argc, char *argv[], AFB_session *session)
275 char* programName = argv [0];
279 struct option *gnuOptions;
280 AFB_config cliconfig; // temp structure to store CLI option before file config upload
282 // ------------- Build session handler & init config -------
283 memset(&cliconfig,0,sizeof(cliconfig));
284 memset(&aliasdir ,0,sizeof(aliasdir));
285 cliconfig.aliasdir = aliasdir;
287 // ------------------ Process Command Line -----------------------
289 // if no argument print help and return
291 printHelp(programName);
295 // build GNU getopt info from cliOptions
296 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
297 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
298 for (ind=0; ind < nbcmd;ind++) {
299 gnuOptions [ind].name = cliOptions[ind].name;
300 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
301 gnuOptions [ind].flag = 0;
302 gnuOptions [ind].val = cliOptions[ind].val;
305 // get all options from command line
306 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
316 if (optarg == 0) goto needValueForOption;
317 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
321 if (optarg == 0) goto needValueForOption;
322 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
325 case SET_CNTXTIMEOUT:
326 if (optarg == 0) goto needValueForOption;
327 if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
331 if (optarg == 0) goto needValueForOption;
332 cliconfig.rootdir = optarg;
333 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
337 if (optarg == 0) goto needValueForOption;
338 cliconfig.rootbase = optarg;
339 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
343 if (optarg == 0) goto needValueForOption;
344 cliconfig.rootapi = optarg;
345 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
349 if (optarg == 0) goto needValueForOption;
350 if (aliascount < MAX_ALIAS) {
351 aliasdir[aliascount].url = strsep(&optarg,":");
352 if (optarg == NULL) {
353 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
355 aliasdir[aliascount].path = optarg;
356 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
357 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
361 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
366 if (optarg == 0) goto needValueForOption;
367 cliconfig.token = optarg;
371 if (optarg == 0) goto needValueForOption;
372 cliconfig.ldpaths = optarg;
376 if (optarg == 0) goto needValueForOption;
377 cliconfig.pidfile = optarg;
380 case SET_SESSION_DIR:
381 if (optarg == 0) goto needValueForOption;
382 cliconfig.sessiondir = optarg;
385 case SET_CONFIG_FILE:
386 if (optarg == 0) goto needValueForOption;
387 cliconfig.configfile = optarg;
391 if (optarg == 0) goto needValueForOption;
392 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
396 if (optarg == 0) goto needValueForOption;
397 cliconfig.setuid = optarg;
401 if (optarg != 0) goto noValueForOption;
402 session->fakemod = 1;
406 if (optarg != 0) goto noValueForOption;
407 session->foreground = 1;
411 if (optarg != 0) goto noValueForOption;
412 session->background = 1;
416 if (optarg != 0) goto noValueForOption;
417 session->killPrevious = 1;
421 if (optarg != 0) goto noValueForOption;
422 session->killPrevious = 2;
426 if (optarg == 0) goto needValueForOption;
427 if (!strcmp(optarg, "local")) cliconfig.mode = AFB_MODE_LOCAL;
428 else if (!strcmp(optarg, "remote")) cliconfig.mode = AFB_MODE_REMOTE;
429 else if (!strcmp(optarg, "global")) cliconfig.mode = AFB_MODE_GLOBAL;
434 if (optarg == 0) goto needValueForOption;
435 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
438 case DISPLAY_VERSION:
439 if (optarg != 0) goto noValueForOption;
445 printHelp(programName);
451 // if exist merge config file with CLI arguments
452 configLoadFile (session, &cliconfig);
457 fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
458 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
462 fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
463 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
467 fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
468 ,gnuOptions[optionIndex].name);
472 fprintf (stderr,"\nERR:AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
473 ,gnuOptions[optionIndex].name);
477 /*---------------------------------------------------------
479 | Parse option and launch action
480 +--------------------------------------------------------- */
482 int main(int argc, char *argv[]) {
483 AFB_session *session;
484 char* programName = argv [0];
488 // ------------- Build session handler & init config -------
489 session = configInit ();
490 parse_arguments(argc, argv, session);
491 initPlugins(session);
493 // ------------------ sanity check ----------------------------------------
494 if ((session->background) && (session->foreground)) {
495 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
499 // ------------------ Some useful default values -------------------------
500 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
502 // open syslog if ever needed
503 openlog("AFB-log", 0, LOG_DAEMON);
505 // -------------- Try to kill any previous process if asked ---------------------
506 if (session->killPrevious) {
507 pid = readPidFile (session->config); // enforce commandline option
510 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
513 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
516 status = kill (pid,SIGINT );
518 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
521 status = kill (pid,9);
522 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
526 if (session->killPrevious >= 2) goto normalExit;
527 } // end killPrevious
530 // ------------------ clean exit on CTR-C signal ------------------------
531 if (signal (SIGINT, signalQuit) == SIG_ERR) {
532 fprintf (stderr, "%s Quit Signal received.",configTime());
536 // save exitPoint context when returning from longjmp closeSession and exit
537 status = setjmp (exitPoint); // return !+ when coming from longjmp
539 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
540 closeSession (session);
544 // let's run this program with a low priority
547 // ------------------ Finaly Process Commands -----------------------------
548 // if --save then store config on disk upfront
549 if (session->config->setuid) {
551 struct passwd *passwd;
552 passwd=getpwnam(session->config->setuid);
554 if (passwd == NULL) goto errorSetuid;
556 err = setuid(passwd->pw_uid);
557 if (err) goto errorSetuid;
560 // let's not take the risk to run as ROOT
561 //if (getuid() == 0) goto errorNoRoot;
563 // check session dir and create if it does not exist
564 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
565 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
569 // ---- run in foreground mode --------------------
570 if (session->foreground) {
572 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
574 // write a pid file for --kill-previous and --raise-debug option
575 status = writePidFile (session->config, getpid());
576 if (status == -1) goto errorPidFile;
578 // enter listening loop in foreground
584 // --------- run in background mode -----------
585 if (session->background) {
587 // if (status != 0) goto errorCommand;
588 if (verbose) printf ("AFB: Entering background mode\n");
590 // open /dev/console to redirect output messAFBes
591 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
592 if (consoleFD < 0) goto errConsole;
594 // fork process when running background mode
597 // son process get all data in standalone mode
600 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
601 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
603 // redirect default I/O on console
604 close (2); status=dup(consoleFD); // redirect stderr
605 close (1); status=dup(consoleFD); // redirect stdout
606 close (0); // no need for stdin
609 setsid(); // allow father process to fully exit
610 sleep (2); // allow main to leave and release port
612 fprintf (stderr, "----------------------------\n");
613 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
616 // if everything look OK then look forever
617 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
619 // should normally never return from this loop
621 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
626 // if fail nothing much to do
627 if (pid == -1) goto errorFork;
629 // fork worked and we are in father process
630 status = writePidFile (session->config, pid);
631 if (status == -1) goto errorPidFile;
633 // we are in father process, we don't need this one
636 } // end background-foreground
639 closeSession (session); // try to close everything before leaving
640 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
643 // ------------- Fatal ERROR display error and quit -------------
645 fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
649 // fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
653 fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
657 fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
661 fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
662 ,configTime(), getpid());
666 fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
670 fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
674 // try to unlink pid file if any
675 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);