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
64 #define SET_ROOT_ALIAS 124
66 #define SET_CACHE_TO 130
67 #define SET_cardid 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
75 #define SET_PLUGINS 141
76 #define SET_APITIMEOUT 142
78 #define DISPLAY_VERSION 150
79 #define DISPLAY_HELP 151
83 static AFB_options cliOptions [] = {
84 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
86 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
87 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
88 {KILL_PREV_EXIT ,0,"kill" , "Kill active process if any and exit"},
89 {KILL_PREV_REST ,0,"restart" , "Kill active process if any and restart"},
91 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
92 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB"},
93 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa"},
94 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api"},
95 {SET_ROOT_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]"},
98 {SET_CACHE_TO ,1,"cache-eol" , "Client cache end of live [default 3600s]"},
99 {SET_cardid ,1,"setuid" , "Change user id [default don't change]"},
100 {SET_PID_FILE ,1,"pidfile" , "PID file path [default none]"},
101 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
102 {SET_CONFIG_FILE ,1,"config" , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
103 {SET_CONFIG_SAVE ,0,"save" , "Save config on disk [default no]"},
104 {SET_CONFIG_EXIT ,0,"saveonly" , "Save config on disk and then exit"},
106 {SET_SMACK ,1,"smack" , "Set Smack Label [default=demo"},
107 {SET_PLUGINS ,1,"mods" , "Enable module [default=all"},
109 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
110 {DISPLAY_HELP ,0,"help" , "Display this help"},
114 static AFB_aliasdir aliasdir[MAX_ALIAS];
115 static int aliascount=0;
117 /*----------------------------------------------------------
119 | return to intitial exitpoint on order to close backend
121 +--------------------------------------------------------- */
122 void signalQuit (int signum)
124 if (verbose) printf ("INF:signalQuit received signal to quit\n");
125 longjmp (exitpoint, signum);
128 /*----------------------------------------------------------
131 +--------------------------------------------------------- */
132 void signalFail (int signum) {
136 // unlock timeout signal to allow a new signal to come
137 sigemptyset (&sigset);
138 sigaddset (&sigset, SIGABRT);
139 sigprocmask (SIG_UNBLOCK, &sigset, 0);
141 fprintf (stderr, "%s ERR:getAllBlock acquisition timeout\n",configTime());
142 syslog (LOG_ERR, "Daemon fail and restart [please report bug]");
143 longjmp (restartpoint, signum);
147 /*----------------------------------------------------------
149 | print information from long option array
150 +--------------------------------------------------------- */
152 static void printHelp(char *name) {
156 fprintf (stderr,"%s:\nallowed options\n", name);
157 for (ind=0; cliOptions [ind].name != NULL;ind++)
160 if (cliOptions [ind].has_arg == 0 )
162 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
164 sprintf(command,"%s=xxxx", cliOptions [ind].name);
165 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
168 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --smack=xxxx --mods=alsa:dbus\n", name);
171 /*----------------------------------------------------------
173 | write a file in /var/run/AFB with pid
174 +--------------------------------------------------------- */
175 static int writePidFile (AFB_config *config, int pid) {
178 // if no pid file configure just return
179 if (config->pidfile == NULL) return 0;
181 // open pid file in write mode
182 file = fopen(config->pidfile,"w");
184 fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
188 // write pid in file and close
189 fprintf (file, "%d\n", pid);
194 /*----------------------------------------------------------
196 | read file in /var/run/AFB with pid
197 +--------------------------------------------------------- */
198 static int readPidFile (AFB_config *config) {
203 if (config->pidfile == NULL) return -1;
205 // open pid file in write mode
206 file = fopen(config->pidfile,"r");
208 fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
212 // write pid in file and close
213 status = fscanf (file, "%d\n", &pid);
217 if (status != 1) return -1;
222 /*----------------------------------------------------------
224 | try to close everything before leaving
225 +--------------------------------------------------------- */
226 static void closeSession (AFB_session *session) {
232 /*----------------------------------------------------------
234 | Main listening HTTP loop
235 +--------------------------------------------------------- */
236 static void listenLoop (AFB_session *session) {
239 if (signal (SIGABRT, signalFail) == SIG_ERR) {
240 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
244 // ------ Start httpd server
245 if (session->config->httpdPort > 0) {
247 err = httpdStart (session);
248 if (err != AFB_SUCCESS) return;
253 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
258 /*---------------------------------------------------------
260 | Parse option and launch action
261 +--------------------------------------------------------- */
263 int main(int argc, char *argv[]) {
264 AFB_session *session;
265 char* programName = argv [0];
267 int optc, ind, consoleFD;
268 int pid, nbcmd, status;
269 AFB_config cliconfig; // temp structure to store CLI option before file config upload
271 // ------------- Build session handler & init config -------
272 session = configInit ();
273 memset(&cliconfig,0,sizeof(cliconfig));
274 memset(&aliasdir ,0,sizeof(aliasdir));
275 cliconfig.aliasdir = aliasdir;
277 // GNU CLI getopts nterface.
278 struct option ggcOption;
279 struct option *gnuOptions;
281 // ------------------ Process Command Line -----------------------
283 // if no argument print help and return
285 printHelp(programName);
289 // build GNU getopt info from cliOptions
290 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
291 gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
292 for (ind=0; ind < nbcmd;ind++) {
293 gnuOptions [ind].name = cliOptions[ind].name;
294 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
295 gnuOptions [ind].flag = 0;
296 gnuOptions [ind].val = cliOptions[ind].val;
299 // get all options from command line
300 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
310 if (optarg == 0) goto needValueForOption;
311 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
315 if (optarg == 0) goto needValueForOption;
316 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
320 if (optarg == 0) goto needValueForOption;
321 cliconfig.rootdir = optarg;
322 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
326 if (optarg == 0) goto needValueForOption;
327 cliconfig.rootbase = optarg;
328 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
332 if (optarg == 0) goto needValueForOption;
333 cliconfig.rootapi = optarg;
334 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
338 if (optarg == 0) goto needValueForOption;
339 if (aliascount < MAX_ALIAS) {
340 aliasdir[aliascount].url = strsep(&optarg,":");
341 aliasdir[aliascount].path = strsep(&optarg,":");
342 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
343 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
346 fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
353 if (optarg == 0) goto needValueForOption;
354 fprintf (stderr, "Not Implemented yet\n");
355 cliconfig.smack = optarg;
359 if (optarg == 0) goto needValueForOption;
360 fprintf (stderr, "Not Implemented yet\n");
361 cliconfig.plugins = optarg;
365 if (optarg == 0) goto needValueForOption;
366 cliconfig.pidfile = optarg;
369 case SET_SESSION_DIR:
370 if (optarg == 0) goto needValueForOption;
371 cliconfig.sessiondir = optarg;
374 case SET_CONFIG_FILE:
375 if (optarg == 0) goto needValueForOption;
376 cliconfig.configfile = optarg;
380 if (optarg == 0) goto needValueForOption;
381 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
384 case SET_CONFIG_EXIT:
385 if (optarg != 0) goto noValueForOption;
386 session->configsave = 1;
387 session->forceexit = 1;
390 case SET_CONFIG_SAVE:
391 if (optarg != 0) goto noValueForOption;
392 session->configsave = 1;
396 if (optarg == 0) goto needValueForOption;
397 if (!sscanf (optarg, "%d", &cliconfig.setuid)) goto notAnInteger;
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;
425 case DISPLAY_VERSION:
426 if (optarg != 0) goto noValueForOption;
432 printHelp(programName);
437 // Create session config
438 configInit (/* session & config are initialized globally */);
440 // if exist merge config file with CLI arguments
441 configLoadFile (session, &cliconfig);
443 // ------------------ sanity check ----------------------------------------
444 if ((session->background) && (session->foreground)) {
445 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
449 // ------------------ Some useful default values -------------------------
450 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
452 // open syslog if ever needed
453 openlog("AGB-log", 0, LOG_DAEMON);
455 // -------------- Try to kill any previsou process if asked ---------------------
456 if (session->killPrevious) {
457 pid = readPidFile (session->config); // enforce commandline option
460 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
463 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
466 status = kill (pid,SIGINT );
468 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
471 status = kill (pid,9);
472 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
476 if (session->killPrevious >= 2) goto normalExit;
477 } // end killPrevious
480 // ------------------ clean exit on CTR-C signal ------------------------
481 if (signal (SIGINT, signalQuit) == SIG_ERR) {
482 fprintf (stderr, "%s Quit Signal received.",configTime());
486 // save exitpoint context when returning from longjmp closeSession and exit
487 status = setjmp (exitpoint); // return !+ when coming from longjmp
489 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
490 closeSession (session);
494 // let's run this program with a low priority
498 // ------------------ Finaly Process Commands -----------------------------
502 // if --save then store config on disk upfront
503 if (session->configsave) configStoreFile (session);
504 if (session->forceexit) exit (0);
506 if (session->config->setuid) {
509 err = setuid(session->config->setuid);
510 if (err) fprintf (stderr, "Fail to change program cardid error=%s", strerror(err));
513 // let's not take the risk to run as ROOT
514 if (getuid() == 0) status=setuid(65534); // run as nobody
516 // check session dir and create if it does not exist
517 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
518 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
522 // ---- run in foreground mode --------------------
523 if (session->foreground) {
525 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
527 // write a pid file for --kill-previous and --raise-debug option
528 status = writePidFile (session->config, getpid());
529 if (status == -1) goto errorPidFile;
531 // enter listening loop in foreground
537 // --------- run in background mode -----------
538 if (session->background) {
540 // if (status != 0) goto errorCommand;
541 if (verbose) printf ("AFB: Entering background mode\n");
543 // open /dev/console to redirect output messAFBes
544 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
545 if (consoleFD < 0) goto errConsole;
547 // fork process when running background mode
550 // son process get all data in standalone mode
553 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
554 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
556 // redirect default I/O on console
557 close (2); status=dup(consoleFD); // redirect stderr
558 close (1); status=dup(consoleFD); // redirect stdout
559 close (0); // no need for stdin
562 setsid(); // allow father process to fully exit
563 sleep (2); // allow main to leave and release port
565 fprintf (stderr, "----------------------------\n");
566 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
569 // if everything look OK then look forever
570 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
572 // should normally never return from this loop
574 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
579 // if fail nothing much to do
580 if (pid == -1) goto errorFork;
582 // fork worked and we are in father process
583 status = writePidFile (session->config, pid);
584 if (status == -1) goto errorPidFile;
586 // we are in father process, we don't need this one
589 } // end background-foreground
592 closeSession (session); // try to close everything before leaving
593 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
596 // ------------- Fatal ERROR display error and quit -------------
598 fprintf (stderr,"\nERR:main Failled to write pid file [%s]\n\n", session->config->pidfile);
602 fprintf (stderr,"\nERR:main Failled to fork son process\n\n");
606 fprintf (stderr,"\nERR:main option [--%s] need a value i.e. --%s=xxx\n\n"
607 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
611 fprintf (stderr,"\nERR:main option [--%s] don't take value\n\n"
612 ,gnuOptions[optionIndex].name);
616 fprintf (stderr,"\nERR:main option [--%s] requirer an interger i.e. --%s=9\n\n"
617 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
621 fprintf (stderr,"\n%s INF:main pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
622 ,configTime(), getpid());
626 fprintf (stderr,"\nERR:cannot open /dev/console (use --foreground)\n\n");
630 fprintf (stderr,"\nERR:cannot read/write session dir\n\n");
634 fprintf (stderr,"\nERR:fail to probe sound cards\n\n");
638 // try to unlink pid file if any
639 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);