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) {
220 /*----------------------------------------------------------
222 | Main listening HTTP loop
223 +--------------------------------------------------------- */
224 static void listenLoop (AFB_session *session) {
227 if (signal (SIGABRT, signalQuit) == SIG_ERR) {
228 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
232 // ------ Start httpd server
233 if (session->config->httpdPort > 0) {
235 err = httpdStart (session);
236 if (err != AFB_SUCCESS) return;
241 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
246 /*---------------------------------------------------------
248 | Parse option and launch action
249 +--------------------------------------------------------- */
251 int main(int argc, char *argv[]) {
252 AFB_session *session;
253 char* programName = argv [0];
255 int optc, ind, consoleFD;
256 int pid, nbcmd, status;
257 AFB_config cliconfig; // temp structure to store CLI option before file config upload
259 // ------------- Build session handler & init config -------
260 session = configInit ();
261 memset(&cliconfig,0,sizeof(cliconfig));
262 memset(&aliasdir ,0,sizeof(aliasdir));
263 cliconfig.aliasdir = aliasdir;
265 // GNU CLI getopts nterface.
266 struct option ggcOption;
267 struct option *gnuOptions;
269 // ------------------ Process Command Line -----------------------
271 // if no argument print help and return
273 printHelp(programName);
277 // build GNU getopt info from cliOptions
278 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
279 gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
280 for (ind=0; ind < nbcmd;ind++) {
281 gnuOptions [ind].name = cliOptions[ind].name;
282 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
283 gnuOptions [ind].flag = 0;
284 gnuOptions [ind].val = cliOptions[ind].val;
287 // get all options from command line
288 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
298 if (optarg == 0) goto needValueForOption;
299 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
303 if (optarg == 0) goto needValueForOption;
304 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
308 if (optarg == 0) goto needValueForOption;
309 cliconfig.rootdir = optarg;
310 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
314 if (optarg == 0) goto needValueForOption;
315 cliconfig.rootbase = optarg;
316 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
320 if (optarg == 0) goto needValueForOption;
321 cliconfig.rootapi = optarg;
322 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
326 if (optarg == 0) goto needValueForOption;
327 if (aliascount < MAX_ALIAS) {
328 aliasdir[aliascount].url = strsep(&optarg,":");
329 aliasdir[aliascount].path = strsep(&optarg,":");
330 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
331 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
334 fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
339 if (optarg == 0) goto needValueForOption;
340 fprintf (stderr, "Not Implemented yet\n");
341 cliconfig.smack = optarg;
345 if (optarg == 0) goto needValueForOption;
346 fprintf (stderr, "Not Implemented yet\n");
347 cliconfig.plugins = optarg;
351 if (optarg == 0) goto needValueForOption;
352 cliconfig.pidfile = optarg;
355 case SET_SESSION_DIR:
356 if (optarg == 0) goto needValueForOption;
357 cliconfig.sessiondir = optarg;
360 case SET_CONFIG_FILE:
361 if (optarg == 0) goto needValueForOption;
362 cliconfig.configfile = optarg;
366 if (optarg == 0) goto needValueForOption;
367 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
370 case SET_CONFIG_EXIT:
371 if (optarg != 0) goto noValueForOption;
372 session->configsave = 1;
373 session->forceexit = 1;
376 case SET_CONFIG_SAVE:
377 if (optarg != 0) goto noValueForOption;
378 session->configsave = 1;
382 if (optarg == 0) goto needValueForOption;
383 if (!sscanf (optarg, "%d", &cliconfig.setuid)) goto notAnInteger;
387 if (optarg != 0) goto noValueForOption;
388 session->fakemod = 1;
392 if (optarg != 0) goto noValueForOption;
393 session->foreground = 1;
397 if (optarg != 0) goto noValueForOption;
398 session->background = 1;
402 if (optarg != 0) goto noValueForOption;
403 session->killPrevious = 1;
407 if (optarg != 0) goto noValueForOption;
408 session->killPrevious = 2;
411 case DISPLAY_VERSION:
412 if (optarg != 0) goto noValueForOption;
418 printHelp(programName);
423 // Create session config
424 configInit (/* session & config are initialized globally */);
426 // if exist merge config file with CLI arguments
427 configLoadFile (session, &cliconfig);
429 // ------------------ sanity check ----------------------------------------
430 if ((session->background) && (session->foreground)) {
431 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
435 // ------------------ Some useful default values -------------------------
436 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
438 // open syslog if ever needed
439 openlog("AGB-log", 0, LOG_DAEMON);
441 // -------------- Try to kill any previsou process if asked ---------------------
442 if (session->killPrevious) {
443 pid = readPidFile (session->config); // enforce commandline option
446 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
449 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
452 status = kill (pid,SIGINT );
454 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
457 status = kill (pid,9);
458 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
462 if (session->killPrevious >= 2) goto normalExit;
463 } // end killPrevious
466 // ------------------ clean exit on CTR-C signal ------------------------
467 if (signal (SIGINT, signalQuit) == SIG_ERR) {
468 fprintf (stderr, "%s Quit Signal received.",configTime());
472 // save exitPoint context when returning from longjmp closeSession and exit
473 status = setjmp (exitPoint); // return !+ when coming from longjmp
475 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
476 closeSession (session);
480 // let's run this program with a low priority
483 // ------------------ Finaly Process Commands -----------------------------
484 // if --save then store config on disk upfront
485 if (session->configsave) configStoreFile (session);
486 if (session->forceexit) exit (0);
488 if (session->config->setuid) {
491 err = setuid(session->config->setuid);
492 if (err) fprintf (stderr, "Fail to change program cardid error=%s", strerror(err));
495 // let's not take the risk to run as ROOT
496 if (getuid() == 0) status=setuid(65534); // run as nobody
498 // check session dir and create if it does not exist
499 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
500 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
504 // ---- run in foreground mode --------------------
505 if (session->foreground) {
507 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
509 // write a pid file for --kill-previous and --raise-debug option
510 status = writePidFile (session->config, getpid());
511 if (status == -1) goto errorPidFile;
513 // enter listening loop in foreground
519 // --------- run in background mode -----------
520 if (session->background) {
522 // if (status != 0) goto errorCommand;
523 if (verbose) printf ("AFB: Entering background mode\n");
525 // open /dev/console to redirect output messAFBes
526 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
527 if (consoleFD < 0) goto errConsole;
529 // fork process when running background mode
532 // son process get all data in standalone mode
535 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
536 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
538 // redirect default I/O on console
539 close (2); status=dup(consoleFD); // redirect stderr
540 close (1); status=dup(consoleFD); // redirect stdout
541 close (0); // no need for stdin
544 setsid(); // allow father process to fully exit
545 sleep (2); // allow main to leave and release port
547 fprintf (stderr, "----------------------------\n");
548 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
551 // if everything look OK then look forever
552 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
554 // should normally never return from this loop
556 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
561 // if fail nothing much to do
562 if (pid == -1) goto errorFork;
564 // fork worked and we are in father process
565 status = writePidFile (session->config, pid);
566 if (status == -1) goto errorPidFile;
568 // we are in father process, we don't need this one
571 } // end background-foreground
574 closeSession (session); // try to close everything before leaving
575 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
578 // ------------- Fatal ERROR display error and quit -------------
580 fprintf (stderr,"\nERR:main Failled to write pid file [%s]\n\n", session->config->pidfile);
584 fprintf (stderr,"\nERR:main Failled to fork son process\n\n");
588 fprintf (stderr,"\nERR:main option [--%s] need a value i.e. --%s=xxx\n\n"
589 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
593 fprintf (stderr,"\nERR:main option [--%s] don't take value\n\n"
594 ,gnuOptions[optionIndex].name);
598 fprintf (stderr,"\nERR:main option [--%s] requirer an interger i.e. --%s=9\n\n"
599 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
603 fprintf (stderr,"\n%s INF:main pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
604 ,configTime(), getpid());
608 fprintf (stderr,"\nERR:cannot open /dev/console (use --foreground)\n\n");
612 fprintf (stderr,"\nERR:cannot read/write session dir\n\n");
616 fprintf (stderr,"\nERR:fail to probe sound cards\n\n");
620 // try to unlink pid file if any
621 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);