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"
34 static sigjmp_buf exitPoint; // 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_USERID 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
77 #define SET_CNTXTIMEOUT 143
79 #define DISPLAY_VERSION 150
80 #define DISPLAY_HELP 151
84 static AFB_options cliOptions [] = {
85 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
87 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
88 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
89 {KILL_PREV_EXIT ,0,"kill" , "Kill active process if any and exit"},
90 {KILL_PREV_REST ,0,"restart" , "Kill active process if any and restart"},
92 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
93 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
94 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
95 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
96 {SET_ROOT_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
98 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
99 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
100 {SET_CACHE_TO ,1,"cache-eol" , "Client cache end of live [default 3600s]"},
102 {SET_USERID ,1,"setuid" , "Change user id [default don't change]"},
103 {SET_PID_FILE ,1,"pidfile" , "PID file path [default none]"},
104 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
105 {SET_CONFIG_FILE ,1,"config" , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
106 {SET_CONFIG_SAVE ,0,"save" , "Save config on disk [default no]"},
107 {SET_CONFIG_EXIT ,0,"saveonly" , "Save config on disk and then exit"},
109 {SET_SMACK ,1,"smack" , "Set Smack Label [default demo]"},
110 {SET_PLUGINS ,1,"mods" , "Enable module [default all]"},
112 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
113 {DISPLAY_HELP ,0,"help" , "Display this help"},
117 static AFB_aliasdir aliasdir[MAX_ALIAS];
118 static int aliascount=0;
120 /*----------------------------------------------------------
123 +--------------------------------------------------------- */
124 void signalQuit (int signum) {
128 // unlock timeout signal to allow a new signal to come
129 sigemptyset (&sigset);
130 sigaddset (&sigset, SIGABRT);
131 sigprocmask (SIG_UNBLOCK, &sigset, 0);
133 fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
134 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
135 longjmp (exitPoint, signum);
139 /*----------------------------------------------------------
141 | print information from long option array
142 +--------------------------------------------------------- */
144 static void printHelp(char *name) {
148 fprintf (stderr,"%s:\nallowed options\n", name);
149 for (ind=0; cliOptions [ind].name != NULL;ind++)
152 if (cliOptions [ind].has_arg == 0 )
154 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
156 sprintf(command,"%s=xxxx", cliOptions [ind].name);
157 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
160 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --smack=xxxx --mods=alsa:dbus\n", name);
163 /*----------------------------------------------------------
165 | write a file in /var/run/AFB with pid
166 +--------------------------------------------------------- */
167 static int writePidFile (AFB_config *config, int pid) {
170 // if no pid file configure just return
171 if (config->pidfile == NULL) return 0;
173 // open pid file in write mode
174 file = fopen(config->pidfile,"w");
176 fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
180 // write pid in file and close
181 fprintf (file, "%d\n", pid);
186 /*----------------------------------------------------------
188 | read file in /var/run/AFB with pid
189 +--------------------------------------------------------- */
190 static int readPidFile (AFB_config *config) {
195 if (config->pidfile == NULL) return -1;
197 // open pid file in write mode
198 file = fopen(config->pidfile,"r");
200 fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
204 // write pid in file and close
205 status = fscanf (file, "%d\n", &pid);
209 if (status != 1) return -1;
214 /*----------------------------------------------------------
216 | try to close everything before leaving
217 +--------------------------------------------------------- */
218 static void closeSession (AFB_session *session) {
223 /*----------------------------------------------------------
225 | Main listening HTTP loop
226 +--------------------------------------------------------- */
227 static void listenLoop (AFB_session *session) {
230 if (signal (SIGABRT, signalQuit) == SIG_ERR) {
231 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
235 // ------ Start httpd server
236 if (session->config->httpdPort > 0) {
238 err = httpdStart (session);
239 if (err != AFB_SUCCESS) return;
244 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
248 /*---------------------------------------------------------
250 | Parse option and launch action
251 +--------------------------------------------------------- */
253 int main(int argc, char *argv[]) {
254 AFB_session *session;
255 char* programName = argv [0];
257 int optc, ind, consoleFD;
258 int pid, nbcmd, status;
259 AFB_config cliconfig; // temp structure to store CLI option before file config upload
261 // ------------- Build session handler & init config -------
262 session = configInit ();
263 memset(&cliconfig,0,sizeof(cliconfig));
264 memset(&aliasdir ,0,sizeof(aliasdir));
265 cliconfig.aliasdir = aliasdir;
267 // GNU CLI getopts nterface.
268 struct option ggcOption;
269 struct option *gnuOptions;
271 // ------------------ Process Command Line -----------------------
273 // if no argument print help and return
275 printHelp(programName);
279 // build GNU getopt info from cliOptions
280 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
281 gnuOptions = malloc (sizeof (ggcOption) * nbcmd);
282 for (ind=0; ind < nbcmd;ind++) {
283 gnuOptions [ind].name = cliOptions[ind].name;
284 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
285 gnuOptions [ind].flag = 0;
286 gnuOptions [ind].val = cliOptions[ind].val;
289 // get all options from command line
290 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
300 if (optarg == 0) goto needValueForOption;
301 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
305 if (optarg == 0) goto needValueForOption;
306 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
309 case SET_CNTXTIMEOUT:
310 if (optarg == 0) goto needValueForOption;
311 if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
315 if (optarg == 0) goto needValueForOption;
316 cliconfig.rootdir = optarg;
317 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
321 if (optarg == 0) goto needValueForOption;
322 cliconfig.rootbase = optarg;
323 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
327 if (optarg == 0) goto needValueForOption;
328 cliconfig.rootapi = optarg;
329 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
333 if (optarg == 0) goto needValueForOption;
334 if (aliascount < MAX_ALIAS) {
335 aliasdir[aliascount].url = strsep(&optarg,":");
336 aliasdir[aliascount].path = strsep(&optarg,":");
337 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
338 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
341 fprintf(stderr, "Too many aliases [max:%s] %s ignored\n", optarg, MAX_ALIAS-1);
346 if (optarg == 0) goto needValueForOption;
347 fprintf (stderr, "Not Implemented yet\n");
348 cliconfig.smack = optarg;
352 if (optarg == 0) goto needValueForOption;
353 fprintf (stderr, "Not Implemented yet\n");
354 cliconfig.plugins = optarg;
358 if (optarg == 0) goto needValueForOption;
359 cliconfig.pidfile = optarg;
362 case SET_SESSION_DIR:
363 if (optarg == 0) goto needValueForOption;
364 cliconfig.sessiondir = optarg;
367 case SET_CONFIG_FILE:
368 if (optarg == 0) goto needValueForOption;
369 cliconfig.configfile = optarg;
373 if (optarg == 0) goto needValueForOption;
374 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
377 case SET_CONFIG_EXIT:
378 if (optarg != 0) goto noValueForOption;
379 session->configsave = 1;
380 session->forceexit = 1;
383 case SET_CONFIG_SAVE:
384 if (optarg != 0) goto noValueForOption;
385 session->configsave = 1;
389 if (optarg == 0) goto needValueForOption;
390 if (!sscanf (optarg, "%s", &cliconfig.setuid)) goto notAnInteger;
394 if (optarg != 0) goto noValueForOption;
395 session->fakemod = 1;
399 if (optarg != 0) goto noValueForOption;
400 session->foreground = 1;
404 if (optarg != 0) goto noValueForOption;
405 session->background = 1;
409 if (optarg != 0) goto noValueForOption;
410 session->killPrevious = 1;
414 if (optarg != 0) goto noValueForOption;
415 session->killPrevious = 2;
418 case DISPLAY_VERSION:
419 if (optarg != 0) goto noValueForOption;
425 printHelp(programName);
430 // Create session config
431 configInit (/* session & config are initialized globally */);
433 // if exist merge config file with CLI arguments
434 configLoadFile (session, &cliconfig);
436 // ------------------ sanity check ----------------------------------------
437 if ((session->background) && (session->foreground)) {
438 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
442 // ------------------ Some useful default values -------------------------
443 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
445 // open syslog if ever needed
446 openlog("AGB-log", 0, LOG_DAEMON);
448 // -------------- Try to kill any previsou process if asked ---------------------
449 if (session->killPrevious) {
450 pid = readPidFile (session->config); // enforce commandline option
453 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
456 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
459 status = kill (pid,SIGINT );
461 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
464 status = kill (pid,9);
465 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
469 if (session->killPrevious >= 2) goto normalExit;
470 } // end killPrevious
473 // ------------------ clean exit on CTR-C signal ------------------------
474 if (signal (SIGINT, signalQuit) == SIG_ERR) {
475 fprintf (stderr, "%s Quit Signal received.",configTime());
479 // save exitPoint context when returning from longjmp closeSession and exit
480 status = setjmp (exitPoint); // return !+ when coming from longjmp
482 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
483 closeSession (session);
487 // let's run this program with a low priority
490 // ------------------ Finaly Process Commands -----------------------------
491 // if --save then store config on disk upfront
492 if (session->configsave) configStoreFile (session);
493 if (session->forceexit) exit (0);
495 if (session->config->setuid) {
497 struct passwd *passwd;
498 passwd=getpwnam(session->config->setuid);
500 if (passwd == NULL) goto errorSetuid;
502 err = setuid(passwd->pw_uid);
503 if (err) goto errorSetuid;
506 // let's not take the risk to run as ROOT
507 if (getuid() == 0) goto errorNoRoot;
509 // check session dir and create if it does not exist
510 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
511 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
515 // ---- run in foreground mode --------------------
516 if (session->foreground) {
518 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
520 // write a pid file for --kill-previous and --raise-debug option
521 status = writePidFile (session->config, getpid());
522 if (status == -1) goto errorPidFile;
524 // enter listening loop in foreground
530 // --------- run in background mode -----------
531 if (session->background) {
533 // if (status != 0) goto errorCommand;
534 if (verbose) printf ("AFB: Entering background mode\n");
536 // open /dev/console to redirect output messAFBes
537 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
538 if (consoleFD < 0) goto errConsole;
540 // fork process when running background mode
543 // son process get all data in standalone mode
546 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
547 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
549 // redirect default I/O on console
550 close (2); status=dup(consoleFD); // redirect stderr
551 close (1); status=dup(consoleFD); // redirect stdout
552 close (0); // no need for stdin
555 setsid(); // allow father process to fully exit
556 sleep (2); // allow main to leave and release port
558 fprintf (stderr, "----------------------------\n");
559 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
562 // if everything look OK then look forever
563 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
565 // should normally never return from this loop
567 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
572 // if fail nothing much to do
573 if (pid == -1) goto errorFork;
575 // fork worked and we are in father process
576 status = writePidFile (session->config, pid);
577 if (status == -1) goto errorPidFile;
579 // we are in father process, we don't need this one
582 } // end background-foreground
585 closeSession (session); // try to close everything before leaving
586 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
589 // ------------- Fatal ERROR display error and quit -------------
591 fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
595 fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
599 fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
603 fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
607 fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
608 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
612 fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
613 ,gnuOptions[optionIndex].name);
617 fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
618 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
622 fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
623 ,configTime(), getpid());
627 fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
631 fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
635 fprintf (stderr,"\nERR:AFB-daemon fail to probe sound cards\n\n");
639 // try to unlink pid file if any
640 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);
643 }; /* END AFB-daemon() */