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");
245 /*---------------------------------------------------------
247 | Parse option and launch action
248 +--------------------------------------------------------- */
250 int main(int argc, char *argv[]) {
251 AFB_session *session;
252 char* programName = argv [0];
254 int optc, ind, consoleFD;
255 int pid, nbcmd, status;
256 AFB_config cliconfig; // temp structure to store CLI option before file config upload
258 // ------------- Build session handler & init config -------
259 session = configInit ();
260 memset(&cliconfig,0,sizeof(cliconfig));
261 memset(&aliasdir ,0,sizeof(aliasdir));
262 cliconfig.aliasdir = aliasdir;
264 // GNU CLI getopts nterface.
265 struct option ggcOption;
266 struct option *gnuOptions;
268 // ------------------ Process Command Line -----------------------
270 // if no argument print help and return
272 printHelp(programName);
276 // build GNU getopt info from cliOptions
277 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
278 gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
279 for (ind=0; ind < nbcmd;ind++) {
280 gnuOptions [ind].name = cliOptions[ind].name;
281 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
282 gnuOptions [ind].flag = 0;
283 gnuOptions [ind].val = cliOptions[ind].val;
286 // get all options from command line
287 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
297 if (optarg == 0) goto needValueForOption;
298 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
302 if (optarg == 0) goto needValueForOption;
303 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
307 if (optarg == 0) goto needValueForOption;
308 cliconfig.rootdir = optarg;
309 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
313 if (optarg == 0) goto needValueForOption;
314 cliconfig.rootbase = optarg;
315 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
319 if (optarg == 0) goto needValueForOption;
320 cliconfig.rootapi = optarg;
321 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
325 if (optarg == 0) goto needValueForOption;
326 if (aliascount < MAX_ALIAS) {
327 aliasdir[aliascount].url = strsep(&optarg,":");
328 aliasdir[aliascount].path = strsep(&optarg,":");
329 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
330 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
333 fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
338 if (optarg == 0) goto needValueForOption;
339 fprintf (stderr, "Not Implemented yet\n");
340 cliconfig.smack = optarg;
344 if (optarg == 0) goto needValueForOption;
345 fprintf (stderr, "Not Implemented yet\n");
346 cliconfig.plugins = optarg;
350 if (optarg == 0) goto needValueForOption;
351 cliconfig.pidfile = optarg;
354 case SET_SESSION_DIR:
355 if (optarg == 0) goto needValueForOption;
356 cliconfig.sessiondir = optarg;
359 case SET_CONFIG_FILE:
360 if (optarg == 0) goto needValueForOption;
361 cliconfig.configfile = optarg;
365 if (optarg == 0) goto needValueForOption;
366 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
369 case SET_CONFIG_EXIT:
370 if (optarg != 0) goto noValueForOption;
371 session->configsave = 1;
372 session->forceexit = 1;
375 case SET_CONFIG_SAVE:
376 if (optarg != 0) goto noValueForOption;
377 session->configsave = 1;
381 if (optarg == 0) goto needValueForOption;
382 if (!sscanf (optarg, "%d", &cliconfig.setuid)) goto notAnInteger;
386 if (optarg != 0) goto noValueForOption;
387 session->fakemod = 1;
391 if (optarg != 0) goto noValueForOption;
392 session->foreground = 1;
396 if (optarg != 0) goto noValueForOption;
397 session->background = 1;
401 if (optarg != 0) goto noValueForOption;
402 session->killPrevious = 1;
406 if (optarg != 0) goto noValueForOption;
407 session->killPrevious = 2;
410 case DISPLAY_VERSION:
411 if (optarg != 0) goto noValueForOption;
417 printHelp(programName);
422 // Create session config
423 configInit (/* session & config are initialized globally */);
425 // if exist merge config file with CLI arguments
426 configLoadFile (session, &cliconfig);
428 // ------------------ sanity check ----------------------------------------
429 if ((session->background) && (session->foreground)) {
430 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
434 // ------------------ Some useful default values -------------------------
435 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
437 // open syslog if ever needed
438 openlog("AGB-log", 0, LOG_DAEMON);
440 // -------------- Try to kill any previsou process if asked ---------------------
441 if (session->killPrevious) {
442 pid = readPidFile (session->config); // enforce commandline option
445 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
448 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
451 status = kill (pid,SIGINT );
453 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
456 status = kill (pid,9);
457 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
461 if (session->killPrevious >= 2) goto normalExit;
462 } // end killPrevious
465 // ------------------ clean exit on CTR-C signal ------------------------
466 if (signal (SIGINT, signalQuit) == SIG_ERR) {
467 fprintf (stderr, "%s Quit Signal received.",configTime());
471 // save exitPoint context when returning from longjmp closeSession and exit
472 status = setjmp (exitPoint); // return !+ when coming from longjmp
474 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
475 closeSession (session);
479 // let's run this program with a low priority
482 // ------------------ Finaly Process Commands -----------------------------
483 // if --save then store config on disk upfront
484 if (session->configsave) configStoreFile (session);
485 if (session->forceexit) exit (0);
487 if (session->config->setuid) {
490 err = setuid(session->config->setuid);
491 if (err) fprintf (stderr, "Fail to change program cardid error=%s", strerror(err));
494 // let's not take the risk to run as ROOT
495 if (getuid() == 0) status=setuid(65534); // run as nobody
497 // check session dir and create if it does not exist
498 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
499 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
503 // ---- run in foreground mode --------------------
504 if (session->foreground) {
506 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
508 // write a pid file for --kill-previous and --raise-debug option
509 status = writePidFile (session->config, getpid());
510 if (status == -1) goto errorPidFile;
512 // enter listening loop in foreground
518 // --------- run in background mode -----------
519 if (session->background) {
521 // if (status != 0) goto errorCommand;
522 if (verbose) printf ("AFB: Entering background mode\n");
524 // open /dev/console to redirect output messAFBes
525 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
526 if (consoleFD < 0) goto errConsole;
528 // fork process when running background mode
531 // son process get all data in standalone mode
534 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
535 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
537 // redirect default I/O on console
538 close (2); status=dup(consoleFD); // redirect stderr
539 close (1); status=dup(consoleFD); // redirect stdout
540 close (0); // no need for stdin
543 setsid(); // allow father process to fully exit
544 sleep (2); // allow main to leave and release port
546 fprintf (stderr, "----------------------------\n");
547 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
550 // if everything look OK then look forever
551 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
553 // should normally never return from this loop
555 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
560 // if fail nothing much to do
561 if (pid == -1) goto errorFork;
563 // fork worked and we are in father process
564 status = writePidFile (session->config, pid);
565 if (status == -1) goto errorPidFile;
567 // we are in father process, we don't need this one
570 } // end background-foreground
573 closeSession (session); // try to close everything before leaving
574 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
577 // ------------- Fatal ERROR display error and quit -------------
579 fprintf (stderr,"\nERR:main Failled to write pid file [%s]\n\n", session->config->pidfile);
583 fprintf (stderr,"\nERR:main Failled to fork son process\n\n");
587 fprintf (stderr,"\nERR:main option [--%s] need a value i.e. --%s=xxx\n\n"
588 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
592 fprintf (stderr,"\nERR:main option [--%s] don't take value\n\n"
593 ,gnuOptions[optionIndex].name);
597 fprintf (stderr,"\nERR:main option [--%s] requirer an interger i.e. --%s=9\n\n"
598 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
602 fprintf (stderr,"\n%s INF:main pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
603 ,configTime(), getpid());
607 fprintf (stderr,"\nERR:cannot open /dev/console (use --foreground)\n\n");
611 fprintf (stderr,"\nERR:cannot read/write session dir\n\n");
615 fprintf (stderr,"\nERR:fail to probe sound cards\n\n");
619 // try to unlink pid file if any
620 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);