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
87 // Command line structure hold cli --command + help text
89 int val; // command number within application
90 int has_arg; // command number within application
91 char *name; // command as used in --xxxx cli
92 char *help; // help text
97 static AFB_options cliOptions [] = {
98 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
100 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
101 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
102 {KILL_PREV_EXIT ,0,"kill" , "Kill active process if any and exit"},
103 {KILL_PREV_REST ,0,"restart" , "Kill active process if any and restart"},
105 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
106 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
107 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
108 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
109 {SET_ROOT_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
111 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
112 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
113 {SET_CACHE_TO ,1,"cache-eol" , "Client cache end of live [default 3600s]"},
115 {SET_USERID ,1,"setuid" , "Change user id [default don't change]"},
116 {SET_PID_FILE ,1,"pidfile" , "PID file path [default none]"},
117 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
118 {SET_CONFIG_FILE ,1,"config" , "Config Filename [default rootdir/sessions/configs/default.AFB]"},
119 {SET_CONFIG_SAVE ,0,"save" , "Save config on disk [default no]"},
120 {SET_CONFIG_EXIT ,0,"saveonly" , "Save config on disk and then exit"},
122 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
123 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
125 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
126 {DISPLAY_HELP ,0,"help" , "Display this help"},
128 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
129 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
133 static AFB_aliasdir aliasdir[MAX_ALIAS];
134 static int aliascount=0;
136 /*----------------------------------------------------------
139 +--------------------------------------------------------- */
140 void signalQuit (int signum) {
144 // unlock timeout signal to allow a new signal to come
145 sigemptyset (&sigset);
146 sigaddset (&sigset, SIGABRT);
147 sigprocmask (SIG_UNBLOCK, &sigset, 0);
149 fprintf (stderr, "%s ERR:Received signal quit\n",configTime());
150 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
151 longjmp (exitPoint, signum);
155 /*----------------------------------------------------------
157 | print information from long option array
158 +--------------------------------------------------------- */
160 static void printHelp(char *name) {
164 fprintf (stderr,"%s:\nallowed options\n", name);
165 for (ind=0; cliOptions [ind].name != NULL;ind++)
168 if (cliOptions [ind].has_arg == 0 )
170 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
172 sprintf(command,"%s=xxxx", cliOptions [ind].name);
173 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
176 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
179 /*----------------------------------------------------------
181 | write a file in /var/run/AFB with pid
182 +--------------------------------------------------------- */
183 static int writePidFile (AFB_config *config, int pid) {
186 // if no pid file configure just return
187 if (config->pidfile == NULL) return 0;
189 // open pid file in write mode
190 file = fopen(config->pidfile,"w");
192 fprintf (stderr,"%s ERR:writePidFile fail to open [%s]\n",configTime(), config->pidfile);
196 // write pid in file and close
197 fprintf (file, "%d\n", pid);
202 /*----------------------------------------------------------
204 | read file in /var/run/AFB with pid
205 +--------------------------------------------------------- */
206 static int readPidFile (AFB_config *config) {
211 if (config->pidfile == NULL) return -1;
213 // open pid file in write mode
214 file = fopen(config->pidfile,"r");
216 fprintf (stderr,"%s ERR:readPidFile fail to open [%s]\n",configTime(), config->pidfile);
220 // write pid in file and close
221 status = fscanf (file, "%d\n", &pid);
225 if (status != 1) return -1;
230 /*----------------------------------------------------------
232 | try to close everything before leaving
233 +--------------------------------------------------------- */
234 static void closeSession (AFB_session *session) {
239 /*----------------------------------------------------------
241 | Main listening HTTP loop
242 +--------------------------------------------------------- */
243 static void listenLoop (AFB_session *session) {
246 if (signal (SIGABRT, signalQuit) == SIG_ERR) {
247 fprintf (stderr, "%s ERR: main fail to install Signal handler\n", configTime());
251 // ------ Start httpd server
252 if (session->config->httpdPort > 0) {
254 err = httpdStart (session);
255 if (err != AFB_SUCCESS) return;
257 if (session->readyfd != 0) {
258 static const char readystr[] = "READY=1";
259 write(session->readyfd, readystr, sizeof(readystr) - 1);
260 close(session->readyfd);
266 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
270 /*---------------------------------------------------------
272 | Parse option and launch action
273 +--------------------------------------------------------- */
275 static void parse_arguments(int argc, char *argv[], AFB_session *session)
277 char* programName = argv [0];
281 struct option *gnuOptions;
282 AFB_config cliconfig; // temp structure to store CLI option before file config upload
284 // ------------- Build session handler & init config -------
285 memset(&cliconfig,0,sizeof(cliconfig));
286 memset(&aliasdir ,0,sizeof(aliasdir));
287 cliconfig.aliasdir = aliasdir;
289 // ------------------ Process Command Line -----------------------
291 // if no argument print help and return
293 printHelp(programName);
297 // build GNU getopt info from cliOptions
298 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
299 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
300 for (ind=0; ind < nbcmd;ind++) {
301 gnuOptions [ind].name = cliOptions[ind].name;
302 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
303 gnuOptions [ind].flag = 0;
304 gnuOptions [ind].val = cliOptions[ind].val;
307 // get all options from command line
308 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
318 if (optarg == 0) goto needValueForOption;
319 if (!sscanf (optarg, "%d", &cliconfig.httpdPort)) goto notAnInteger;
323 if (optarg == 0) goto needValueForOption;
324 if (!sscanf (optarg, "%d", &cliconfig.apiTimeout)) goto notAnInteger;
327 case SET_CNTXTIMEOUT:
328 if (optarg == 0) goto needValueForOption;
329 if (!sscanf (optarg, "%d", &cliconfig.cntxTimeout)) goto notAnInteger;
333 if (optarg == 0) goto needValueForOption;
334 cliconfig.rootdir = optarg;
335 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",cliconfig.rootdir);
339 if (optarg == 0) goto needValueForOption;
340 cliconfig.rootbase = optarg;
341 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",cliconfig.rootbase);
345 if (optarg == 0) goto needValueForOption;
346 cliconfig.rootapi = optarg;
347 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",cliconfig.rootapi);
351 if (optarg == 0) goto needValueForOption;
352 if (aliascount < MAX_ALIAS) {
353 aliasdir[aliascount].url = strsep(&optarg,":");
354 if (optarg == NULL) {
355 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
357 aliasdir[aliascount].path = optarg;
358 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
359 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
363 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
368 if (optarg == 0) goto needValueForOption;
369 cliconfig.token = optarg;
373 if (optarg == 0) goto needValueForOption;
374 cliconfig.ldpaths = optarg;
378 if (optarg == 0) goto needValueForOption;
379 cliconfig.pidfile = optarg;
382 case SET_SESSION_DIR:
383 if (optarg == 0) goto needValueForOption;
384 cliconfig.sessiondir = optarg;
387 case SET_CONFIG_FILE:
388 if (optarg == 0) goto needValueForOption;
389 cliconfig.configfile = optarg;
393 if (optarg == 0) goto needValueForOption;
394 if (!sscanf (optarg, "%d", &cliconfig.cacheTimeout)) goto notAnInteger;
397 case SET_CONFIG_EXIT:
398 if (optarg != 0) goto noValueForOption;
399 session->configsave = 1;
400 session->forceexit = 1;
403 case SET_CONFIG_SAVE:
404 if (optarg != 0) goto noValueForOption;
405 session->configsave = 1;
409 if (optarg == 0) goto needValueForOption;
410 cliconfig.setuid = optarg;
414 if (optarg != 0) goto noValueForOption;
415 session->fakemod = 1;
419 if (optarg != 0) goto noValueForOption;
420 session->foreground = 1;
424 if (optarg != 0) goto noValueForOption;
425 session->background = 1;
429 if (optarg != 0) goto noValueForOption;
430 session->killPrevious = 1;
434 if (optarg != 0) goto noValueForOption;
435 session->killPrevious = 2;
439 if (optarg == 0) goto needValueForOption;
440 if (!strcmp(optarg, "local")) cliconfig.mode = AFB_MODE_LOCAL;
441 else if (!strcmp(optarg, "remote")) cliconfig.mode = AFB_MODE_REMOTE;
442 else if (!strcmp(optarg, "global")) cliconfig.mode = AFB_MODE_GLOBAL;
447 if (optarg == 0) goto needValueForOption;
448 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
451 case DISPLAY_VERSION:
452 if (optarg != 0) goto noValueForOption;
458 printHelp(programName);
464 // if exist merge config file with CLI arguments
465 configLoadFile (session, &cliconfig);
470 fprintf (stderr,"\nERR:AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
471 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
475 fprintf (stderr,"\nERR:AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
476 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
480 fprintf (stderr,"\nERR:AFB-daemon option [--%s] don't take value\n\n"
481 ,gnuOptions[optionIndex].name);
485 fprintf (stderr,"\nERR:AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
486 ,gnuOptions[optionIndex].name);
490 /*---------------------------------------------------------
492 | Parse option and launch action
493 +--------------------------------------------------------- */
495 int main(int argc, char *argv[]) {
496 AFB_session *session;
497 char* programName = argv [0];
501 // ------------- Build session handler & init config -------
502 session = configInit ();
503 parse_arguments(argc, argv, session);
504 initPlugins(session);
506 // ------------------ sanity check ----------------------------------------
507 if ((session->background) && (session->foreground)) {
508 fprintf (stderr, "%s ERR: cannot select foreground & background at the same time\n",configTime());
512 // ------------------ Some useful default values -------------------------
513 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
515 // open syslog if ever needed
516 openlog("AFB-log", 0, LOG_DAEMON);
518 // -------------- Try to kill any previous process if asked ---------------------
519 if (session->killPrevious) {
520 pid = readPidFile (session->config); // enforce commandline option
523 fprintf (stderr, "%s ERR:main --kill ignored no PID file [%s]\n",configTime(), session->config->pidfile);
526 fprintf (stderr, "%s ERR:main --kill ignored no active AFB process\n",configTime());
529 status = kill (pid,SIGINT );
531 if (verbose) printf ("%s INF:main signal INTR sent to pid:%d \n", configTime(), pid);
534 status = kill (pid,9);
535 if (status != 0) fprintf (stderr, "%s ERR:main failled to killed pid=%d \n",configTime(), pid);
539 if (session->killPrevious >= 2) goto normalExit;
540 } // end killPrevious
543 // ------------------ clean exit on CTR-C signal ------------------------
544 if (signal (SIGINT, signalQuit) == SIG_ERR) {
545 fprintf (stderr, "%s Quit Signal received.",configTime());
549 // save exitPoint context when returning from longjmp closeSession and exit
550 status = setjmp (exitPoint); // return !+ when coming from longjmp
552 if (verbose) printf ("INF:main returning from longjump after signal [%d]\n", status);
553 closeSession (session);
557 // let's run this program with a low priority
560 // ------------------ Finaly Process Commands -----------------------------
561 // if --save then store config on disk upfront
562 if (session->configsave) configStoreFile (session);
563 if (session->forceexit) exit (0);
565 if (session->config->setuid) {
567 struct passwd *passwd;
568 passwd=getpwnam(session->config->setuid);
570 if (passwd == NULL) goto errorSetuid;
572 err = setuid(passwd->pw_uid);
573 if (err) goto errorSetuid;
576 // let's not take the risk to run as ROOT
577 //if (getuid() == 0) goto errorNoRoot;
579 // check session dir and create if it does not exist
580 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
581 if (verbose) fprintf (stderr, "AFB:notice Init config done\n");
585 // ---- run in foreground mode --------------------
586 if (session->foreground) {
588 if (verbose) fprintf (stderr,"AFB:notice Foreground mode\n");
590 // write a pid file for --kill-previous and --raise-debug option
591 status = writePidFile (session->config, getpid());
592 if (status == -1) goto errorPidFile;
594 // enter listening loop in foreground
600 // --------- run in background mode -----------
601 if (session->background) {
603 // if (status != 0) goto errorCommand;
604 if (verbose) printf ("AFB: Entering background mode\n");
606 // open /dev/console to redirect output messAFBes
607 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
608 if (consoleFD < 0) goto errConsole;
610 // fork process when running background mode
613 // son process get all data in standalone mode
616 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
617 if (verbose) printf ("AFB:info use '%s --restart --rootdir=%s # [--pidfile=%s] to restart daemon\n", programName,session->config->rootdir, session->config->pidfile);
619 // redirect default I/O on console
620 close (2); status=dup(consoleFD); // redirect stderr
621 close (1); status=dup(consoleFD); // redirect stdout
622 close (0); // no need for stdin
625 setsid(); // allow father process to fully exit
626 sleep (2); // allow main to leave and release port
628 fprintf (stderr, "----------------------------\n");
629 fprintf (stderr, "%s INF:main background pid=%d\n", configTime(), getpid());
632 // if everything look OK then look forever
633 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
635 // should normally never return from this loop
637 syslog (LOG_ERR, "AFB:FAIL background infinite loop exited check [%s]\n", session->config->console);
642 // if fail nothing much to do
643 if (pid == -1) goto errorFork;
645 // fork worked and we are in father process
646 status = writePidFile (session->config, pid);
647 if (status == -1) goto errorPidFile;
649 // we are in father process, we don't need this one
652 } // end background-foreground
655 closeSession (session); // try to close everything before leaving
656 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
659 // ------------- Fatal ERROR display error and quit -------------
661 fprintf (stderr,"\nERR:AFB-daemon Failed to change UID to username=[%s]\n\n", session->config->setuid);
665 // fprintf (stderr,"\nERR:AFB-daemon Not allow to run as root [use --seteuid=username option]\n\n");
669 fprintf (stderr,"\nERR:AFB-daemon Failed to write pid file [%s]\n\n", session->config->pidfile);
673 fprintf (stderr,"\nERR:AFB-daemon Failed to fork son process\n\n");
677 fprintf (stderr,"\n%s INF:AFB-daemon pid=%d received exit signal (Hopefully crtl-C or --kill-previous !!!)\n\n"
678 ,configTime(), getpid());
682 fprintf (stderr,"\nERR:AFB-daemon cannot open /dev/console (use --foreground)\n\n");
686 fprintf (stderr,"\nERR:AFB-daemon cannot read/write session dir\n\n");
690 // try to unlink pid file if any
691 if (session->background && session->config->pidfile != NULL) unlink (session->config->pidfile);