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"
33 static sigjmp_buf exitpoint; // context save for set/longjmp
34 static sigjmp_buf restartpoint; // 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
65 #define SET_CACHE_TO 130
66 #define SET_cardid 131
67 #define SET_PID_FILE 132
68 #define SET_SESSION_DIR 133
69 #define SET_CONFIG_FILE 134
70 #define SET_CONFIG_SAVE 135
71 #define SET_CONFIG_EXIT 138
74 #define SET_PLUGINS 141
76 #define DISPLAY_VERSION 150
77 #define DISPLAY_HELP 151
81 static AFB_options cliOptions [] = {
82 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
84 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
85 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
86 {KILL_PREV_EXIT ,0,"kill" , "Kill active process if any and exit"},
87 {KILL_PREV_REST ,0,"restart" , "Kill active process if any and restart"},
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"},
94 {SET_CACHE_TO ,1,"cache-eol" , "Client cache end of live [default 3600s]"},
95 {SET_cardid ,1,"setuid" , "Change user id [default don't change]"},
96 {SET_PID_FILE ,1,"pidfile" , "PID file path [default none]"},
97 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
98 {SET_CONFIG_FILE ,1,"config" , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
99 {SET_CONFIG_SAVE ,0,"save" , "Save config on disk [default no]"},
100 {SET_CONFIG_EXIT ,0,"saveonly" , "Save config on disk and then exit"},
102 {SET_SMACK ,1,"smack" , "Set Smack Label [default=demo"},
103 {SET_PLUGINS ,1,"mods" , "Enable module [default=all"},
105 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
106 {DISPLAY_HELP ,0,"help" , "Display this help"},
110 /*----------------------------------------------------------
112 | return to intitial exitpoint on order to close backend
114 +--------------------------------------------------------- */
115 void signalQuit (int signum)
117 if (verbose) printf ("INF:signalQuit received signal to quit\n");
118 longjmp (exitpoint, signum);
121 /*----------------------------------------------------------
124 +--------------------------------------------------------- */
125 void signalFail (int signum) {
129 // unlock timeout signal to allow a new signal to come
130 sigemptyset (&sigset);
131 sigaddset (&sigset, SIGABRT);
132 sigprocmask (SIG_UNBLOCK, &sigset, 0);
134 fprintf (stderr, "%s ERR:getAllBlock acquisition timeout\n",configTime());
135 syslog (LOG_ERR, "Daemon fail and restart [please report bug]");
136 longjmp (restartpoint, signum);
140 /*----------------------------------------------------------
142 | print information from long option array
143 +--------------------------------------------------------- */
145 static void printHelp(char *name) {
149 fprintf (stderr,"%s:\nallowed options\n", name);
150 for (ind=0; cliOptions [ind].name != NULL;ind++)
153 if (cliOptions [ind].has_arg == 0 )
155 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
157 sprintf(command,"%s=xxxx", cliOptions [ind].name);
158 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
161 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --smack=xxxx --mods=alsa:dbus\n", name);
164 /*----------------------------------------------------------
166 | write a file in /var/run/AFB with pid
167 +--------------------------------------------------------- */
168 static int writePidFile (AFB_config *config, int pid) {
171 // if no pid file configure just return
172 if (config->pidfile == NULL) return 0;
174 // open pid file in write mode
175 file = fopen(config->pidfile,"w");
177 fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
181 // write pid in file and close
182 fprintf (file, "%d\n", pid);
187 /*----------------------------------------------------------
189 | read file in /var/run/AFB with pid
190 +--------------------------------------------------------- */
191 static int readPidFile (AFB_config *config) {
196 if (config->pidfile == NULL) return -1;
198 // open pid file in write mode
199 file = fopen(config->pidfile,"r");
201 fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
205 // write pid in file and close
206 status = fscanf (file, "%d\n", &pid);
210 if (status != 1) return -1;
215 /*----------------------------------------------------------
217 | try to close everything before leaving
218 +--------------------------------------------------------- */
219 static void closeSession (AFB_session *session) {
225 /*----------------------------------------------------------
227 | Main listening HTTP loop
228 +--------------------------------------------------------- */
229 static void listenLoop (AFB_session *session) {
232 if (signal (SIGABRT, signalFail) == SIG_ERR) {
233 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
237 // ------ Start httpd server
238 if (session->config->httpdPort > 0) {
240 err = httpdStart (session);
241 if (err != AFB_SUCCESS) return;
246 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
251 /*---------------------------------------------------------
253 | Parse option and launch action
254 +--------------------------------------------------------- */
256 int main(int argc, char *argv[]) {
257 AFB_session *session;
258 char* programName = argv [0];
260 int optc, ind, consoleFD;
261 int pid, nbcmd, status;
262 AFB_config cliconfig; // temp structure to store CLI option before file config upload
264 // ------------- Build session handler & init config -------
265 session = configInit ();
266 memset (&cliconfig,0,sizeof(cliconfig));
268 // GNU CLI getopts nterface.
269 struct option ggcOption;
270 struct option *gnuOptions;
272 // ------------------ Process Command Line -----------------------
274 // if no argument print help and return
276 printHelp(programName);
280 // build GNU getopt info from cliOptions
281 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
282 gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
283 for (ind=0; ind < nbcmd;ind++) {
284 gnuOptions [ind].name = cliOptions[ind].name;
285 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
286 gnuOptions [ind].flag = 0;
287 gnuOptions [ind].val = cliOptions[ind].val;
290 // get all options from command line
291 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
301 if (optarg == 0) goto needValueForOption;
302 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
306 if (optarg == 0) goto needValueForOption;
307 cliconfig.rootdir = optarg;
311 if (optarg == 0) goto needValueForOption;
312 cliconfig.rootbase = optarg;
316 if (optarg == 0) goto needValueForOption;
317 cliconfig.rootapi = optarg;
321 if (optarg == 0) goto needValueForOption;
322 fprintf (stderr, "Not Implemented yet\n");
323 cliconfig.smack = optarg;
327 if (optarg == 0) goto needValueForOption;
328 fprintf (stderr, "Not Implemented yet\n");
329 cliconfig.plugins = optarg;
333 if (optarg == 0) goto needValueForOption;
334 cliconfig.pidfile = optarg;
337 case SET_SESSION_DIR:
338 if (optarg == 0) goto needValueForOption;
339 cliconfig.sessiondir = optarg;
342 case SET_CONFIG_FILE:
343 if (optarg == 0) goto needValueForOption;
344 cliconfig.configfile = optarg;
348 if (optarg == 0) goto needValueForOption;
349 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
352 case SET_CONFIG_EXIT:
353 if (optarg != 0) goto noValueForOption;
354 session->configsave = 1;
355 session->forceexit = 1;
358 case SET_CONFIG_SAVE:
359 if (optarg != 0) goto noValueForOption;
360 session->configsave = 1;
364 if (optarg == 0) goto needValueForOption;
365 if (!sscanf (optarg, "%d", &cliconfig.setuid)) goto notAnInteger;
369 if (optarg != 0) goto noValueForOption;
370 session->fakemod = 1;
374 if (optarg != 0) goto noValueForOption;
375 session->foreground = 1;
379 if (optarg != 0) goto noValueForOption;
380 session->background = 1;
384 if (optarg != 0) goto noValueForOption;
385 session->killPrevious = 1;
389 if (optarg != 0) goto noValueForOption;
390 session->killPrevious = 2;
393 case DISPLAY_VERSION:
394 if (optarg != 0) goto noValueForOption;
400 printHelp(programName);
405 // Create session config
406 configInit (/* session & config are initialized globally */);
408 // if exist merge config file with CLI arguments
409 configLoadFile (session, &cliconfig);
411 // ------------------ sanity check ----------------------------------------
412 if ((session->background) && (session->foreground)) {
413 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
417 // ------------------ Some useful default values -------------------------
418 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
420 // open syslog if ever needed
421 openlog("AGB-log", 0, LOG_DAEMON);
423 // -------------- Try to kill any previsou process if asked ---------------------
424 if (session->killPrevious) {
425 pid = readPidFile (session->config); // enforce commandline option
428 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
431 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
434 status = kill (pid,SIGINT );
436 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
439 status = kill (pid,9);
440 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
444 if (session->killPrevious >= 2) goto normalExit;
445 } // end killPrevious
448 // ------------------ clean exit on CTR-C signal ------------------------
449 if (signal (SIGINT, signalQuit) == SIG_ERR) {
450 fprintf (stderr, "%s Quit Signal received.",configTime());
454 // save exitpoint context when returning from longjmp closeSession and exit
455 status = setjmp (exitpoint); // return !+ when coming from longjmp
457 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
458 closeSession (session);
462 // let's run this program with a low priority
466 // ------------------ Finaly Process Commands -----------------------------
470 // if --save then store config on disk upfront
471 if (session->configsave) configStoreFile (session);
472 if (session->forceexit) exit (0);
474 if (session->config->setuid) {
477 err = setuid(session->config->setuid);
478 if (err) fprintf (stderr, "Fail to change program cardid error=%s", strerror(err));
481 // let's not take the risk to run as ROOT
482 if (getuid() == 0) status=setuid(65534); // run as nobody
484 // check session dir and create if it does not exist
485 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
486 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
490 // ---- run in foreground mode --------------------
491 if (session->foreground) {
493 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
495 // write a pid file for --kill-previous and --raise-debug option
496 status = writePidFile (session->config, getpid());
497 if (status == -1) goto errorPidFile;
499 // enter listening loop in foreground
505 // --------- run in background mode -----------
506 if (session->background) {
508 // if (status != 0) goto errorCommand;
509 if (verbose) printf ("AFB: Entering background mode\n");
511 // open /dev/console to redirect output messAFBes
512 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
513 if (consoleFD < 0) goto errConsole;
515 // fork process when running background mode
518 // son process get all data in standalone mode
521 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
522 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
524 // redirect default I/O on console
525 close (2); status=dup(consoleFD); // redirect stderr
526 close (1); status=dup(consoleFD); // redirect stdout
527 close (0); // no need for stdin
530 setsid(); // allow father process to fully exit
531 sleep (2); // allow main to leave and release port
533 fprintf (stderr, "----------------------------\n");
534 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
537 // if everything look OK then look forever
538 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
540 // should normally never return from this loop
542 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
547 // if fail nothing much to do
548 if (pid == -1) goto errorFork;
550 // fork worked and we are in father process
551 status = writePidFile (session->config, pid);
552 if (status == -1) goto errorPidFile;
554 // we are in father process, we don't need this one
557 } // end background-foreground
560 closeSession (session); // try to close everything before leaving
561 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
564 // ------------- Fatal ERROR display error and quit -------------
566 fprintf (stderr,"\nERR:main Failled to write pid file [%s]\n\n", session->config->pidfile);
570 fprintf (stderr,"\nERR:main Failled to fork son process\n\n");
574 fprintf (stderr,"\nERR:main option [--%s] need a value i.e. --%s=xxx\n\n"
575 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
579 fprintf (stderr,"\nERR:main option [--%s] don't take value\n\n"
580 ,gnuOptions[optionIndex].name);
584 fprintf (stderr,"\nERR:main option [--%s] requirer an interger i.e. --%s=9\n\n"
585 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
589 fprintf (stderr,"\n%s INF:main pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
590 ,configTime(), getpid());
594 fprintf (stderr,"\nERR:cannot open /dev/console (use --foreground)\n\n");
598 fprintf (stderr,"\nERR:cannot read/write session dir\n\n");
602 fprintf (stderr,"\nERR:fail to probe sound cards\n\n");
606 // try to unlink pid file if any
607 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);