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 static sigjmp_buf exitPoint; // context save for set/longjmp
36 /*----------------------------------------------------------
38 | print version and copyright
39 +--------------------------------------------------------- */
40 static void printVersion (void) {
42 fprintf (stderr,"\n----------------------------------------- \n");
43 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AJQ_VERSION);
44 fprintf (stderr,"----------------------------------------- \n");
45 fprintf (stderr,"| Copyright(C) 2015 Fulup Ar Foll /IoT.bzh [fulup -at- iot.bzh]\n");
46 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
47 fprintf (stderr,"| Licence [what ever makes you happy] until you fix bugs by yourself :)\n\n");
52 // Define command line option
53 #define SET_VERBOSE 101
54 #define SET_BACKGROUND 105
55 #define SET_FORGROUND 106
56 #define KILL_PREV_EXIT 107
57 #define KILL_PREV_REST 108
58 #define SET_FAKE_MOD 109
60 #define SET_TCP_PORT 120
61 #define SET_ROOT_DIR 121
62 #define SET_ROOT_BASE 122
63 #define SET_ROOT_API 123
64 #define SET_ROOT_ALIAS 124
66 #define SET_CACHE_TO 130
67 #define SET_USERID 131
68 #define SET_PID_FILE 132
69 #define SET_SESSION_DIR 133
70 #define SET_CONFIG_FILE 134
71 #define SET_CONFIG_SAVE 135
72 #define SET_CONFIG_EXIT 138
74 #define SET_AUTH_TOKEN 141
75 #define SET_LDPATH 142
76 #define SET_APITIMEOUT 143
77 #define SET_CNTXTIMEOUT 144
79 #define DISPLAY_VERSION 150
80 #define DISPLAY_HELP 151
83 #define SET_READYFD 161
87 static AFB_options cliOptions [] = {
88 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
90 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
91 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
92 {KILL_PREV_EXIT ,0,"kill" , "Kill active process if any and exit"},
93 {KILL_PREV_REST ,0,"restart" , "Kill active process if any and restart"},
95 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
96 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
97 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
98 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
99 {SET_ROOT_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
101 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
102 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
103 {SET_CACHE_TO ,1,"cache-eol" , "Client cache end of live [default 3600s]"},
105 {SET_USERID ,1,"setuid" , "Change user id [default don't change]"},
106 {SET_PID_FILE ,1,"pidfile" , "PID file path [default none]"},
107 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
108 {SET_CONFIG_FILE ,1,"config" , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
109 {SET_CONFIG_SAVE ,0,"save" , "Save config on disk [default no]"},
110 {SET_CONFIG_EXIT ,0,"saveonly" , "Save config on disk and then exit"},
112 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
113 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
115 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
116 {DISPLAY_HELP ,0,"help" , "Display this help"},
118 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
119 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
123 static AFB_aliasdir aliasdir[MAX_ALIAS];
124 static int aliascount=0;
126 /*----------------------------------------------------------
129 +--------------------------------------------------------- */
130 void signalQuit (int signum) {
134 // unlock timeout signal to allow a new signal to come
135 sigemptyset (&sigset);
136 sigaddset (&sigset, SIGABRT);
137 sigprocmask (SIG_UNBLOCK, &sigset, 0);
139 fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
140 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
141 longjmp (exitPoint, signum);
145 /*----------------------------------------------------------
147 | print information from long option array
148 +--------------------------------------------------------- */
150 static void printHelp(char *name) {
154 fprintf (stderr,"%s:\nallowed options\n", name);
155 for (ind=0; cliOptions [ind].name != NULL;ind++)
158 if (cliOptions [ind].has_arg == 0 )
160 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
162 sprintf(command,"%s=xxxx", cliOptions [ind].name);
163 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
166 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
169 /*----------------------------------------------------------
171 | write a file in /var/run/AFB with pid
172 +--------------------------------------------------------- */
173 static int writePidFile (AFB_config *config, int pid) {
176 // if no pid file configure just return
177 if (config->pidfile == NULL) return 0;
179 // open pid file in write mode
180 file = fopen(config->pidfile,"w");
182 fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
186 // write pid in file and close
187 fprintf (file, "%d\n", pid);
192 /*----------------------------------------------------------
194 | read file in /var/run/AFB with pid
195 +--------------------------------------------------------- */
196 static int readPidFile (AFB_config *config) {
201 if (config->pidfile == NULL) return -1;
203 // open pid file in write mode
204 file = fopen(config->pidfile,"r");
206 fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
210 // write pid in file and close
211 status = fscanf (file, "%d\n", &pid);
215 if (status != 1) return -1;
220 /*----------------------------------------------------------
222 | try to close everything before leaving
223 +--------------------------------------------------------- */
224 static void closeSession (AFB_session *session) {
229 /*----------------------------------------------------------
231 | Main listening HTTP loop
232 +--------------------------------------------------------- */
233 static void listenLoop (AFB_session *session) {
236 if (signal (SIGABRT, signalQuit) == SIG_ERR) {
237 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
241 // ------ Start httpd server
242 if (session->config->httpdPort > 0) {
244 err = httpdStart (session);
245 if (err != AFB_SUCCESS) return;
247 if (session->readyfd != 0) {
248 static const char readystr[] = "READY=1";
249 write(session->readyfd, readystr, sizeof(readystr) - 1);
250 close(session->readyfd);
256 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
260 /*---------------------------------------------------------
262 | Parse option and launch action
263 +--------------------------------------------------------- */
265 int main(int argc, char *argv[]) {
266 AFB_session *session;
267 char* programName = argv [0];
269 int optc, ind, consoleFD;
270 int pid, nbcmd, status;
271 AFB_config cliconfig; // temp structure to store CLI option before file config upload
273 // ------------- Build session handler & init config -------
274 session = configInit ();
275 memset(&cliconfig,0,sizeof(cliconfig));
276 memset(&aliasdir ,0,sizeof(aliasdir));
277 cliconfig.aliasdir = aliasdir;
279 // GNU CLI getopts nterface.
280 struct option ggcOption;
281 struct option *gnuOptions;
283 // ------------------ Process Command Line -----------------------
285 // if no argument print help and return
287 printHelp(programName);
291 // build GNU getopt info from cliOptions
292 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
293 gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
294 for (ind=0; ind < nbcmd;ind++) {
295 gnuOptions [ind].name = cliOptions[ind].name;
296 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
297 gnuOptions [ind].flag = 0;
298 gnuOptions [ind].val = cliOptions[ind].val;
301 // get all options from command line
302 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
312 if (optarg == 0) goto needValueForOption;
313 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
317 if (optarg == 0) goto needValueForOption;
318 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
321 case SET_CNTXTIMEOUT:
322 if (optarg == 0) goto needValueForOption;
323 if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
327 if (optarg == 0) goto needValueForOption;
328 cliconfig.rootdir = optarg;
329 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
333 if (optarg == 0) goto needValueForOption;
334 cliconfig.rootbase = optarg;
335 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
339 if (optarg == 0) goto needValueForOption;
340 cliconfig.rootapi = optarg;
341 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
345 if (optarg == 0) goto needValueForOption;
346 if (aliascount < MAX_ALIAS) {
347 aliasdir[aliascount].url = strsep(&optarg,":");
348 aliasdir[aliascount].path = strsep(&optarg,":");
349 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
350 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
353 fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
358 if (optarg == 0) goto needValueForOption;
359 cliconfig.token = optarg;
363 if (optarg == 0) goto needValueForOption;
364 cliconfig.ldpaths = optarg;
368 if (optarg == 0) goto needValueForOption;
369 cliconfig.pidfile = optarg;
372 case SET_SESSION_DIR:
373 if (optarg == 0) goto needValueForOption;
374 cliconfig.sessiondir = optarg;
377 case SET_CONFIG_FILE:
378 if (optarg == 0) goto needValueForOption;
379 cliconfig.configfile = optarg;
383 if (optarg == 0) goto needValueForOption;
384 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
387 case SET_CONFIG_EXIT:
388 if (optarg != 0) goto noValueForOption;
389 session->configsave = 1;
390 session->forceexit = 1;
393 case SET_CONFIG_SAVE:
394 if (optarg != 0) goto noValueForOption;
395 session->configsave = 1;
399 if (optarg == 0) goto needValueForOption;
400 if (!sscanf (optarg, "%s", &cliconfig.setuid)) goto notAnInteger;
404 if (optarg != 0) goto noValueForOption;
405 session->fakemod = 1;
409 if (optarg != 0) goto noValueForOption;
410 session->foreground = 1;
414 if (optarg != 0) goto noValueForOption;
415 session->background = 1;
419 if (optarg != 0) goto noValueForOption;
420 session->killPrevious = 1;
424 if (optarg != 0) goto noValueForOption;
425 session->killPrevious = 2;
429 if (optarg == 0) goto needValueForOption;
430 if (!strcmp(optarg, "local")) cliconfig.mode = AFB_MODE_LOCAL;
431 else if (!strcmp(optarg, "remote")) cliconfig.mode = AFB_MODE_REMOTE;
432 else if (!strcmp(optarg, "global")) cliconfig.mode = AFB_MODE_GLOBAL;
437 if (optarg == 0) goto needValueForOption;
438 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
441 case DISPLAY_VERSION:
442 if (optarg != 0) goto noValueForOption;
448 printHelp(programName);
454 // if exist merge config file with CLI arguments
455 configLoadFile (session, &cliconfig);
456 initPlugins(session);
458 // ------------------ sanity check ----------------------------------------
459 if ((session->background) && (session->foreground)) {
460 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
464 // ------------------ Some useful default values -------------------------
465 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
467 // open syslog if ever needed
468 openlog("AFB-log", 0, LOG_DAEMON);
470 // -------------- Try to kill any previous process if asked ---------------------
471 if (session->killPrevious) {
472 pid = readPidFile (session->config); // enforce commandline option
475 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
478 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
481 status = kill (pid,SIGINT );
483 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
486 status = kill (pid,9);
487 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
491 if (session->killPrevious >= 2) goto normalExit;
492 } // end killPrevious
495 // ------------------ clean exit on CTR-C signal ------------------------
496 if (signal (SIGINT, signalQuit) == SIG_ERR) {
497 fprintf (stderr, "%s Quit Signal received.",configTime());
501 // save exitPoint context when returning from longjmp closeSession and exit
502 status = setjmp (exitPoint); // return !+ when coming from longjmp
504 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
505 closeSession (session);
509 // let's run this program with a low priority
512 // ------------------ Finaly Process Commands -----------------------------
513 // if --save then store config on disk upfront
514 if (session->configsave) configStoreFile (session);
515 if (session->forceexit) exit (0);
517 if (session->config->setuid) {
519 struct passwd *passwd;
520 passwd=getpwnam(session->config->setuid);
522 if (passwd == NULL) goto errorSetuid;
524 err = setuid(passwd->pw_uid);
525 if (err) goto errorSetuid;
528 // let's not take the risk to run as ROOT
529 //if (getuid() == 0) goto errorNoRoot;
531 // check session dir and create if it does not exist
532 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
533 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
537 // ---- run in foreground mode --------------------
538 if (session->foreground) {
540 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
542 // write a pid file for --kill-previous and --raise-debug option
543 status = writePidFile (session->config, getpid());
544 if (status == -1) goto errorPidFile;
546 // enter listening loop in foreground
552 // --------- run in background mode -----------
553 if (session->background) {
555 // if (status != 0) goto errorCommand;
556 if (verbose) printf ("AFB: Entering background mode\n");
558 // open /dev/console to redirect output messAFBes
559 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
560 if (consoleFD < 0) goto errConsole;
562 // fork process when running background mode
565 // son process get all data in standalone mode
568 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
569 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
571 // redirect default I/O on console
572 close (2); status=dup(consoleFD); // redirect stderr
573 close (1); status=dup(consoleFD); // redirect stdout
574 close (0); // no need for stdin
577 setsid(); // allow father process to fully exit
578 sleep (2); // allow main to leave and release port
580 fprintf (stderr, "----------------------------\n");
581 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
584 // if everything look OK then look forever
585 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
587 // should normally never return from this loop
589 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
594 // if fail nothing much to do
595 if (pid == -1) goto errorFork;
597 // fork worked and we are in father process
598 status = writePidFile (session->config, pid);
599 if (status == -1) goto errorPidFile;
601 // we are in father process, we don't need this one
604 } // end background-foreground
607 closeSession (session); // try to close everything before leaving
608 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
611 // ------------- Fatal ERROR display error and quit -------------
613 fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
617 // fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
621 fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
625 fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
629 fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
630 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
634 fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
635 ,gnuOptions[optionIndex].name);
639 fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
640 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
644 fprintf (stderr,"\nERR:AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
645 ,gnuOptions[optionIndex].name);
649 fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
650 ,configTime(), getpid());
654 fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
658 fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
662 fprintf (stderr,"\nERR:AFB-daemon fail to probe sound cards\n\n");
666 // try to unlink pid file if any
667 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);
670 }; /* END AFB-daemon() */