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
35 /*----------------------------------------------------------
37 | print version and copyright
38 +--------------------------------------------------------- */
39 static void printVersion (void) {
41 fprintf (stderr,"\n----------------------------------------- \n");
42 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AJQ_VERSION);
43 fprintf (stderr,"----------------------------------------- \n");
44 fprintf (stderr,"| Copyright(C) 2015 Fulup Ar Foll /IoT.bzh [fulup -at- iot.bzh]\n");
45 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
46 fprintf (stderr,"| Licence [what ever makes you happy] until you fix bugs by yourself :)\n\n");
51 // Define command line option
52 #define SET_VERBOSE 101
53 #define SET_BACKGROUND 105
54 #define SET_FORGROUND 106
55 #define KILL_PREV_EXIT 107
56 #define KILL_PREV_REST 108
57 #define SET_FAKE_MOD 109
59 #define SET_TCP_PORT 120
60 #define SET_ROOT_DIR 121
61 #define SET_ROOT_BASE 122
62 #define SET_ROOT_API 123
63 #define SET_ROOT_ALIAS 124
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
75 #define SET_APITIMEOUT 142
77 #define DISPLAY_VERSION 150
78 #define DISPLAY_HELP 151
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"},
87 {KILL_PREV_EXIT ,0,"kill" , "Kill active process if any and exit"},
88 {KILL_PREV_REST ,0,"restart" , "Kill active process if any and restart"},
90 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
91 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
92 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
93 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
94 {SET_ROOT_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
95 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
97 {SET_CACHE_TO ,1,"cache-eol" , "Client cache end of live [default 3600s]"},
98 {SET_cardid ,1,"setuid" , "Change user id [default don't change]"},
99 {SET_PID_FILE ,1,"pidfile" , "PID file path [default none]"},
100 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
101 {SET_CONFIG_FILE ,1,"config" , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
102 {SET_CONFIG_SAVE ,0,"save" , "Save config on disk [default no]"},
103 {SET_CONFIG_EXIT ,0,"saveonly" , "Save config on disk and then exit"},
105 {SET_SMACK ,1,"smack" , "Set Smack Label [default demo]"},
106 {SET_PLUGINS ,1,"mods" , "Enable module [default all]"},
108 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
109 {DISPLAY_HELP ,0,"help" , "Display this help"},
113 static AFB_aliasdir aliasdir[MAX_ALIAS];
114 static int aliascount=0;
116 /*----------------------------------------------------------
119 +--------------------------------------------------------- */
120 void signalQuit (int signum) {
124 // unlock timeout signal to allow a new signal to come
125 sigemptyset (&sigset);
126 sigaddset (&sigset, SIGABRT);
127 sigprocmask (SIG_UNBLOCK, &sigset, 0);
129 fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
130 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
131 longjmp (exitPoint, signum);
135 /*----------------------------------------------------------
137 | print information from long option array
138 +--------------------------------------------------------- */
140 static void printHelp(char *name) {
144 fprintf (stderr,"%s:\nallowed options\n", name);
145 for (ind=0; cliOptions [ind].name != NULL;ind++)
148 if (cliOptions [ind].has_arg == 0 )
150 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
152 sprintf(command,"%s=xxxx", cliOptions [ind].name);
153 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
156 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --smack=xxxx --mods=alsa:dbus\n", name);
159 /*----------------------------------------------------------
161 | write a file in /var/run/AFB with pid
162 +--------------------------------------------------------- */
163 static int writePidFile (AFB_config *config, int pid) {
166 // if no pid file configure just return
167 if (config->pidfile == NULL) return 0;
169 // open pid file in write mode
170 file = fopen(config->pidfile,"w");
172 fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
176 // write pid in file and close
177 fprintf (file, "%d\n", pid);
182 /*----------------------------------------------------------
184 | read file in /var/run/AFB with pid
185 +--------------------------------------------------------- */
186 static int readPidFile (AFB_config *config) {
191 if (config->pidfile == NULL) return -1;
193 // open pid file in write mode
194 file = fopen(config->pidfile,"r");
196 fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
200 // write pid in file and close
201 status = fscanf (file, "%d\n", &pid);
205 if (status != 1) return -1;
210 /*----------------------------------------------------------
212 | try to close everything before leaving
213 +--------------------------------------------------------- */
214 static void closeSession (AFB_session *session) {
219 /*----------------------------------------------------------
221 | Main listening HTTP loop
222 +--------------------------------------------------------- */
223 static void listenLoop (AFB_session *session) {
226 if (signal (SIGABRT, signalQuit) == SIG_ERR) {
227 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
231 // ------ Start httpd server
232 if (session->config->httpdPort > 0) {
234 err = httpdStart (session);
235 if (err != AFB_SUCCESS) return;
240 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
244 /*---------------------------------------------------------
246 | Parse option and launch action
247 +--------------------------------------------------------- */
249 int main(int argc, char *argv[]) {
250 AFB_session *session;
251 char* programName = argv [0];
253 int optc, ind, consoleFD;
254 int pid, nbcmd, status;
255 AFB_config cliconfig; // temp structure to store CLI option before file config upload
257 // ------------- Build session handler & init config -------
258 session = configInit ();
259 memset(&cliconfig,0,sizeof(cliconfig));
260 memset(&aliasdir ,0,sizeof(aliasdir));
261 cliconfig.aliasdir = aliasdir;
263 // GNU CLI getopts nterface.
264 struct option ggcOption;
265 struct option *gnuOptions;
267 // ------------------ Process Command Line -----------------------
269 // if no argument print help and return
271 printHelp(programName);
275 // build GNU getopt info from cliOptions
276 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
277 gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
278 for (ind=0; ind < nbcmd;ind++) {
279 gnuOptions [ind].name = cliOptions[ind].name;
280 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
281 gnuOptions [ind].flag = 0;
282 gnuOptions [ind].val = cliOptions[ind].val;
285 // get all options from command line
286 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
296 if (optarg == 0) goto needValueForOption;
297 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
301 if (optarg == 0) goto needValueForOption;
302 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
306 if (optarg == 0) goto needValueForOption;
307 cliconfig.rootdir = optarg;
308 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
312 if (optarg == 0) goto needValueForOption;
313 cliconfig.rootbase = optarg;
314 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
318 if (optarg == 0) goto needValueForOption;
319 cliconfig.rootapi = optarg;
320 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
324 if (optarg == 0) goto needValueForOption;
325 if (aliascount < MAX_ALIAS) {
326 aliasdir[aliascount].url = strsep(&optarg,":");
327 aliasdir[aliascount].path = strsep(&optarg,":");
328 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
329 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
332 fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
337 if (optarg == 0) goto needValueForOption;
338 fprintf (stderr, "Not Implemented yet\n");
339 cliconfig.smack = optarg;
343 if (optarg == 0) goto needValueForOption;
344 fprintf (stderr, "Not Implemented yet\n");
345 cliconfig.plugins = optarg;
349 if (optarg == 0) goto needValueForOption;
350 cliconfig.pidfile = optarg;
353 case SET_SESSION_DIR:
354 if (optarg == 0) goto needValueForOption;
355 cliconfig.sessiondir = optarg;
358 case SET_CONFIG_FILE:
359 if (optarg == 0) goto needValueForOption;
360 cliconfig.configfile = optarg;
364 if (optarg == 0) goto needValueForOption;
365 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
368 case SET_CONFIG_EXIT:
369 if (optarg != 0) goto noValueForOption;
370 session->configsave = 1;
371 session->forceexit = 1;
374 case SET_CONFIG_SAVE:
375 if (optarg != 0) goto noValueForOption;
376 session->configsave = 1;
380 if (optarg == 0) goto needValueForOption;
381 if (!sscanf (optarg, "%d", &cliconfig.setuid)) goto notAnInteger;
385 if (optarg != 0) goto noValueForOption;
386 session->fakemod = 1;
390 if (optarg != 0) goto noValueForOption;
391 session->foreground = 1;
395 if (optarg != 0) goto noValueForOption;
396 session->background = 1;
400 if (optarg != 0) goto noValueForOption;
401 session->killPrevious = 1;
405 if (optarg != 0) goto noValueForOption;
406 session->killPrevious = 2;
409 case DISPLAY_VERSION:
410 if (optarg != 0) goto noValueForOption;
416 printHelp(programName);
421 // Create session config
422 configInit (/* session & config are initialized globally */);
424 // if exist merge config file with CLI arguments
425 configLoadFile (session, &cliconfig);
427 // ------------------ sanity check ----------------------------------------
428 if ((session->background) && (session->foreground)) {
429 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
433 // ------------------ Some useful default values -------------------------
434 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
436 // open syslog if ever needed
437 openlog("AGB-log", 0, LOG_DAEMON);
439 // -------------- Try to kill any previsou process if asked ---------------------
440 if (session->killPrevious) {
441 pid = readPidFile (session->config); // enforce commandline option
444 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
447 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
450 status = kill (pid,SIGINT );
452 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
455 status = kill (pid,9);
456 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
460 if (session->killPrevious >= 2) goto normalExit;
461 } // end killPrevious
464 // ------------------ clean exit on CTR-C signal ------------------------
465 if (signal (SIGINT, signalQuit) == SIG_ERR) {
466 fprintf (stderr, "%s Quit Signal received.",configTime());
470 // save exitPoint context when returning from longjmp closeSession and exit
471 status = setjmp (exitPoint); // return !+ when coming from longjmp
473 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
474 closeSession (session);
478 // let's run this program with a low priority
481 // ------------------ Finaly Process Commands -----------------------------
482 // if --save then store config on disk upfront
483 if (session->configsave) configStoreFile (session);
484 if (session->forceexit) exit (0);
486 if (session->config->setuid) {
489 err = setuid(session->config->setuid);
490 if (err) fprintf (stderr, "Fail to change program cardid error=%s", strerror(err));
493 // let's not take the risk to run as ROOT
494 if (getuid() == 0) status=setuid(65534); // run as nobody
496 // check session dir and create if it does not exist
497 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
498 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
502 // ---- run in foreground mode --------------------
503 if (session->foreground) {
505 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
507 // write a pid file for --kill-previous and --raise-debug option
508 status = writePidFile (session->config, getpid());
509 if (status == -1) goto errorPidFile;
511 // enter listening loop in foreground
517 // --------- run in background mode -----------
518 if (session->background) {
520 // if (status != 0) goto errorCommand;
521 if (verbose) printf ("AFB: Entering background mode\n");
523 // open /dev/console to redirect output messAFBes
524 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
525 if (consoleFD < 0) goto errConsole;
527 // fork process when running background mode
530 // son process get all data in standalone mode
533 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
534 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
536 // redirect default I/O on console
537 close (2); status=dup(consoleFD); // redirect stderr
538 close (1); status=dup(consoleFD); // redirect stdout
539 close (0); // no need for stdin
542 setsid(); // allow father process to fully exit
543 sleep (2); // allow main to leave and release port
545 fprintf (stderr, "----------------------------\n");
546 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
549 // if everything look OK then look forever
550 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
552 // should normally never return from this loop
554 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
559 // if fail nothing much to do
560 if (pid == -1) goto errorFork;
562 // fork worked and we are in father process
563 status = writePidFile (session->config, pid);
564 if (status == -1) goto errorPidFile;
566 // we are in father process, we don't need this one
569 } // end background-foreground
572 closeSession (session); // try to close everything before leaving
573 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
576 // ------------- Fatal ERROR display error and quit -------------
578 fprintf (stderr,"\nERR:main Failled to write pid file [%s]\n\n", session->config->pidfile);
582 fprintf (stderr,"\nERR:main Failled to fork son process\n\n");
586 fprintf (stderr,"\nERR:main option [--%s] need a value i.e. --%s=xxx\n\n"
587 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
591 fprintf (stderr,"\nERR:main option [--%s] don't take value\n\n"
592 ,gnuOptions[optionIndex].name);
596 fprintf (stderr,"\nERR:main option [--%s] requirer an interger i.e. --%s=9\n\n"
597 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
601 fprintf (stderr,"\n%s INF:main pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
602 ,configTime(), getpid());
606 fprintf (stderr,"\nERR:cannot open /dev/console (use --foreground)\n\n");
610 fprintf (stderr,"\nERR:cannot read/write session dir\n\n");
614 fprintf (stderr,"\nERR:fail to probe sound cards\n\n");
618 // try to unlink pid file if any
619 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);