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 #define AFB_VERSION "0.1"
36 static sigjmp_buf exitPoint; // context save for set/longjmp
38 /*----------------------------------------------------------
40 | print version and copyright
41 +--------------------------------------------------------- */
42 static void printVersion (void) {
44 fprintf (stderr,"\n----------------------------------------- \n");
45 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
46 fprintf (stderr,"----------------------------------------- \n");
47 fprintf (stderr,"| Copyright(C) 2015 Fulup Ar Foll /IoT.bzh [fulup -at- iot.bzh]\n");
48 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
49 fprintf (stderr,"| Licence [what ever makes you happy] until you fix bugs by yourself :)\n\n");
54 // Define command line option
55 #define SET_VERBOSE 101
56 #define SET_BACKGROUND 105
57 #define SET_FORGROUND 106
58 #define KILL_PREV_EXIT 107
59 #define KILL_PREV_REST 108
60 #define SET_FAKE_MOD 109
62 #define SET_TCP_PORT 120
63 #define SET_ROOT_DIR 121
64 #define SET_ROOT_BASE 122
65 #define SET_ROOT_API 123
66 #define SET_ROOT_ALIAS 124
68 #define SET_CACHE_TO 130
69 #define SET_USERID 131
70 #define SET_PID_FILE 132
71 #define SET_SESSION_DIR 133
72 #define SET_CONFIG_FILE 134
73 #define SET_CONFIG_SAVE 135
74 #define SET_CONFIG_EXIT 138
76 #define SET_AUTH_TOKEN 141
77 #define SET_LDPATH 142
78 #define SET_APITIMEOUT 143
79 #define SET_CNTXTIMEOUT 144
81 #define DISPLAY_VERSION 150
82 #define DISPLAY_HELP 151
85 #define SET_READYFD 161
89 static AFB_options cliOptions [] = {
90 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
92 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
93 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
94 {KILL_PREV_EXIT ,0,"kill" , "Kill active process if any and exit"},
95 {KILL_PREV_REST ,0,"restart" , "Kill active process if any and restart"},
97 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
98 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
99 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
100 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
101 {SET_ROOT_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
103 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
104 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
105 {SET_CACHE_TO ,1,"cache-eol" , "Client cache end of live [default 3600s]"},
107 {SET_USERID ,1,"setuid" , "Change user id [default don't change]"},
108 {SET_PID_FILE ,1,"pidfile" , "PID file path [default none]"},
109 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
110 {SET_CONFIG_FILE ,1,"config" , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
111 {SET_CONFIG_SAVE ,0,"save" , "Save config on disk [default no]"},
112 {SET_CONFIG_EXIT ,0,"saveonly" , "Save config on disk and then exit"},
114 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
115 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
117 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
118 {DISPLAY_HELP ,0,"help" , "Display this help"},
120 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
121 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
125 static AFB_aliasdir aliasdir[MAX_ALIAS];
126 static int aliascount=0;
128 /*----------------------------------------------------------
131 +--------------------------------------------------------- */
132 void signalQuit (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:Received signal quit\n",configTime());
142 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
143 longjmp (exitPoint, 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 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\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) {
231 /*----------------------------------------------------------
233 | Main listening HTTP loop
234 +--------------------------------------------------------- */
235 static void listenLoop (AFB_session *session) {
238 if (signal (SIGABRT, signalQuit) == SIG_ERR) {
239 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
243 // ------ Start httpd server
244 if (session->config->httpdPort > 0) {
246 err = httpdStart (session);
247 if (err != AFB_SUCCESS) return;
249 if (session->readyfd != 0) {
250 static const char readystr[] = "READY=1";
251 write(session->readyfd, readystr, sizeof(readystr) - 1);
252 close(session->readyfd);
258 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
262 /*---------------------------------------------------------
264 | Parse option and launch action
265 +--------------------------------------------------------- */
267 int main(int argc, char *argv[]) {
268 AFB_session *session;
269 char* programName = argv [0];
271 int optc, ind, consoleFD;
272 int pid, nbcmd, status;
273 AFB_config cliconfig; // temp structure to store CLI option before file config upload
275 // ------------- Build session handler & init config -------
276 session = configInit ();
277 memset(&cliconfig,0,sizeof(cliconfig));
278 memset(&aliasdir ,0,sizeof(aliasdir));
279 cliconfig.aliasdir = aliasdir;
281 // GNU CLI getopts nterface.
282 struct option ggcOption;
283 struct option *gnuOptions;
285 // ------------------ Process Command Line -----------------------
287 // if no argument print help and return
289 printHelp(programName);
293 // build GNU getopt info from cliOptions
294 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
295 gnuOptions = malloc (sizeof (ggcOption) * (unsigned)nbcmd);
296 for (ind=0; ind < nbcmd;ind++) {
297 gnuOptions [ind].name = cliOptions[ind].name;
298 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
299 gnuOptions [ind].flag = 0;
300 gnuOptions [ind].val = cliOptions[ind].val;
303 // get all options from command line
304 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
314 if (optarg == 0) goto needValueForOption;
315 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
319 if (optarg == 0) goto needValueForOption;
320 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
323 case SET_CNTXTIMEOUT:
324 if (optarg == 0) goto needValueForOption;
325 if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
329 if (optarg == 0) goto needValueForOption;
330 cliconfig.rootdir = optarg;
331 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
335 if (optarg == 0) goto needValueForOption;
336 cliconfig.rootbase = optarg;
337 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
341 if (optarg == 0) goto needValueForOption;
342 cliconfig.rootapi = optarg;
343 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
347 if (optarg == 0) goto needValueForOption;
348 if (aliascount < MAX_ALIAS) {
349 aliasdir[aliascount].url = strsep(&optarg,":");
350 if (optarg == NULL) {
351 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
353 aliasdir[aliascount].path = optarg;
354 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
355 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
359 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
364 if (optarg == 0) goto needValueForOption;
365 cliconfig.token = optarg;
369 if (optarg == 0) goto needValueForOption;
370 cliconfig.ldpaths = optarg;
374 if (optarg == 0) goto needValueForOption;
375 cliconfig.pidfile = optarg;
378 case SET_SESSION_DIR:
379 if (optarg == 0) goto needValueForOption;
380 cliconfig.sessiondir = optarg;
383 case SET_CONFIG_FILE:
384 if (optarg == 0) goto needValueForOption;
385 cliconfig.configfile = optarg;
389 if (optarg == 0) goto needValueForOption;
390 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
393 case SET_CONFIG_EXIT:
394 if (optarg != 0) goto noValueForOption;
395 session->configsave = 1;
396 session->forceexit = 1;
399 case SET_CONFIG_SAVE:
400 if (optarg != 0) goto noValueForOption;
401 session->configsave = 1;
405 if (optarg == 0) goto needValueForOption;
406 cliconfig.setuid = optarg;
410 if (optarg != 0) goto noValueForOption;
411 session->fakemod = 1;
415 if (optarg != 0) goto noValueForOption;
416 session->foreground = 1;
420 if (optarg != 0) goto noValueForOption;
421 session->background = 1;
425 if (optarg != 0) goto noValueForOption;
426 session->killPrevious = 1;
430 if (optarg != 0) goto noValueForOption;
431 session->killPrevious = 2;
435 if (optarg == 0) goto needValueForOption;
436 if (!strcmp(optarg, "local")) cliconfig.mode = AFB_MODE_LOCAL;
437 else if (!strcmp(optarg, "remote")) cliconfig.mode = AFB_MODE_REMOTE;
438 else if (!strcmp(optarg, "global")) cliconfig.mode = AFB_MODE_GLOBAL;
443 if (optarg == 0) goto needValueForOption;
444 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
447 case DISPLAY_VERSION:
448 if (optarg != 0) goto noValueForOption;
454 printHelp(programName);
460 // if exist merge config file with CLI arguments
461 configLoadFile (session, &cliconfig);
462 initPlugins(session);
464 // ------------------ sanity check ----------------------------------------
465 if ((session->background) && (session->foreground)) {
466 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
470 // ------------------ Some useful default values -------------------------
471 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
473 // open syslog if ever needed
474 openlog("AFB-log", 0, LOG_DAEMON);
476 // -------------- Try to kill any previous process if asked ---------------------
477 if (session->killPrevious) {
478 pid = readPidFile (session->config); // enforce commandline option
481 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
484 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
487 status = kill (pid,SIGINT );
489 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
492 status = kill (pid,9);
493 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
497 if (session->killPrevious >= 2) goto normalExit;
498 } // end killPrevious
501 // ------------------ clean exit on CTR-C signal ------------------------
502 if (signal (SIGINT, signalQuit) == SIG_ERR) {
503 fprintf (stderr, "%s Quit Signal received.",configTime());
507 // save exitPoint context when returning from longjmp closeSession and exit
508 status = setjmp (exitPoint); // return !+ when coming from longjmp
510 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
511 closeSession (session);
515 // let's run this program with a low priority
518 // ------------------ Finaly Process Commands -----------------------------
519 // if --save then store config on disk upfront
520 if (session->configsave) configStoreFile (session);
521 if (session->forceexit) exit (0);
523 if (session->config->setuid) {
525 struct passwd *passwd;
526 passwd=getpwnam(session->config->setuid);
528 if (passwd == NULL) goto errorSetuid;
530 err = setuid(passwd->pw_uid);
531 if (err) goto errorSetuid;
534 // let's not take the risk to run as ROOT
535 //if (getuid() == 0) goto errorNoRoot;
537 // check session dir and create if it does not exist
538 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
539 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
543 // ---- run in foreground mode --------------------
544 if (session->foreground) {
546 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
548 // write a pid file for --kill-previous and --raise-debug option
549 status = writePidFile (session->config, getpid());
550 if (status == -1) goto errorPidFile;
552 // enter listening loop in foreground
558 // --------- run in background mode -----------
559 if (session->background) {
561 // if (status != 0) goto errorCommand;
562 if (verbose) printf ("AFB: Entering background mode\n");
564 // open /dev/console to redirect output messAFBes
565 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
566 if (consoleFD < 0) goto errConsole;
568 // fork process when running background mode
571 // son process get all data in standalone mode
574 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
575 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
577 // redirect default I/O on console
578 close (2); status=dup(consoleFD); // redirect stderr
579 close (1); status=dup(consoleFD); // redirect stdout
580 close (0); // no need for stdin
583 setsid(); // allow father process to fully exit
584 sleep (2); // allow main to leave and release port
586 fprintf (stderr, "----------------------------\n");
587 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
590 // if everything look OK then look forever
591 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
593 // should normally never return from this loop
595 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
600 // if fail nothing much to do
601 if (pid == -1) goto errorFork;
603 // fork worked and we are in father process
604 status = writePidFile (session->config, pid);
605 if (status == -1) goto errorPidFile;
607 // we are in father process, we don't need this one
610 } // end background-foreground
613 closeSession (session); // try to close everything before leaving
614 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
617 // ------------- Fatal ERROR display error and quit -------------
619 fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
623 // fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
627 fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
631 fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
635 fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
636 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
640 fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
641 ,gnuOptions[optionIndex].name);
645 fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
646 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
650 fprintf (stderr,"\nERR:AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
651 ,gnuOptions[optionIndex].name);
655 fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
656 ,configTime(), getpid());
660 fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
664 fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
668 // try to unlink pid file if any
669 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);
672 } /* END AFB-daemon() */