2 * Copyright (C) 2015 "IoT.bzh"
3 * Author "Fulup Ar Foll"
4 * Author José Bollo <jose.bollo@iot.bzh>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
25 #include <sys/types.h>
27 #include "local-def.h"
29 #if !defined(PLUGIN_INSTALL_DIR)
30 #error "you should define PLUGIN_INSTALL_DIR"
33 #define AFB_VERSION "0.1"
35 // Define command line option
37 #define SET_BACKGROUND 2
38 #define SET_FORGROUND 3
39 #define SET_FAKE_MOD 4
41 #define SET_TCP_PORT 5
42 #define SET_ROOT_DIR 6
43 #define SET_ROOT_BASE 7
44 #define SET_ROOT_API 8
47 #define SET_CACHE_TIMEOUT 10
48 #define SET_SESSION_DIR 11
50 #define SET_AUTH_TOKEN 12
52 #define SET_APITIMEOUT 14
53 #define SET_CNTXTIMEOUT 15
55 #define DISPLAY_VERSION 16
56 #define DISPLAY_HELP 17
59 #define SET_READYFD 19
61 // Command line structure hold cli --command + help text
63 int val; // command number within application
64 int has_arg; // command number within application
65 char *name; // command as used in --xxxx cli
66 char *help; // help text
71 static AFB_options cliOptions [] = {
72 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
74 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
75 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
77 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
78 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
79 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
80 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
81 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
83 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
84 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
85 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
87 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
89 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
90 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
92 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
93 {DISPLAY_HELP ,0,"help" , "Display this help"},
95 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
96 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
100 static AFB_aliasdir aliasdir[MAX_ALIAS];
101 static int aliascount = 0;
104 /*----------------------------------------------------------
106 | print version and copyright
107 +--------------------------------------------------------- */
108 static void printVersion (void)
110 fprintf (stderr,"\n----------------------------------------- \n");
111 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
112 fprintf (stderr,"----------------------------------------- \n");
113 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
114 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
115 fprintf (stderr,"| Licence Apache 2\n\n");
119 // load config from disk and merge with CLI option
120 static AFB_error config_set_default (AFB_session * session)
122 static char cacheTimeout [10];
125 if (session->config->httpdPort == 0) session->config->httpdPort=1234;
127 // default Plugin API timeout
128 if (session->config->apiTimeout == 0) session->config->apiTimeout=DEFLT_API_TIMEOUT;
130 // default AUTH_TOKEN
131 if (session->config->token == NULL) session->config->token= DEFLT_AUTH_TOKEN;
133 // cache timeout default one hour
134 if (session->config->cacheTimeout == 0) session->config->cacheTimeout=DEFLT_CACHE_TIMEOUT;
136 // cache timeout default one hour
137 if (session->config->cntxTimeout == 0) session->config->cntxTimeout=DEFLT_CNTX_TIMEOUT;
139 if (session->config->rootdir == NULL) {
140 session->config->rootdir = getenv("AFBDIR");
141 if (session->config->rootdir == NULL) {
142 session->config->rootdir = malloc (512);
143 strncpy (session->config->rootdir, getenv("HOME"),512);
144 strncat (session->config->rootdir, "/.AFB",512);
146 // if directory does not exist createit
147 mkdir (session->config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
150 // if no Angular/HTML5 rootbase let's try '/' as default
151 if (session->config->rootbase == NULL) {
152 session->config->rootbase = "/opa";
155 if (session->config->rootapi == NULL) {
156 session->config->rootapi = "/api";
159 if (session->config->ldpaths == NULL) {
160 session->config->ldpaths = PLUGIN_INSTALL_DIR;
163 // if no session dir create a default path from rootdir
164 if (session->config->sessiondir == NULL) {
165 session->config->sessiondir = malloc (512);
166 strncpy (session->config->sessiondir, session->config->rootdir, 512);
167 strncat (session->config->sessiondir, "/sessions",512);
170 // if no config dir create a default path from sessiondir
171 if (session->config->console == NULL) {
172 session->config->console = malloc (512);
173 strncpy (session->config->console, session->config->sessiondir, 512);
174 strncat (session->config->console, "/AFB-console.out",512);
177 // cacheTimeout is an integer but HTTPd wants it as a string
178 snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
179 session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
185 /*----------------------------------------------------------
187 | print information from long option array
188 +--------------------------------------------------------- */
190 static void printHelp(char *name) {
194 fprintf (stderr,"%s:\nallowed options\n", name);
195 for (ind=0; cliOptions [ind].name != NULL;ind++)
198 if (cliOptions [ind].has_arg == 0 )
200 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
202 sprintf(command,"%s=xxxx", cliOptions [ind].name);
203 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
206 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
209 /*---------------------------------------------------------
211 | Parse option and launch action
212 +--------------------------------------------------------- */
214 static void parse_arguments(int argc, char *argv[], AFB_session *session)
216 char* programName = argv [0];
220 struct option *gnuOptions;
222 // ------------- Build session handler & init config -------
223 memset(&aliasdir ,0,sizeof(aliasdir));
224 session->config->aliasdir = aliasdir;
226 // ------------------ Process Command Line -----------------------
228 // if no argument print help and return
230 printHelp(programName);
234 // build GNU getopt info from cliOptions
235 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
236 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
237 for (ind=0; ind < nbcmd;ind++) {
238 gnuOptions [ind].name = cliOptions[ind].name;
239 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
240 gnuOptions [ind].flag = 0;
241 gnuOptions [ind].val = cliOptions[ind].val;
244 // get all options from command line
245 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
255 if (optarg == 0) goto needValueForOption;
256 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
260 if (optarg == 0) goto needValueForOption;
261 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
264 case SET_CNTXTIMEOUT:
265 if (optarg == 0) goto needValueForOption;
266 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
270 if (optarg == 0) goto needValueForOption;
271 session->config->rootdir = optarg;
272 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
276 if (optarg == 0) goto needValueForOption;
277 session->config->rootbase = optarg;
278 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
282 if (optarg == 0) goto needValueForOption;
283 session->config->rootapi = optarg;
284 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
288 if (optarg == 0) goto needValueForOption;
289 if (aliascount < MAX_ALIAS) {
290 aliasdir[aliascount].url = strsep(&optarg,":");
291 if (optarg == NULL) {
292 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
294 aliasdir[aliascount].path = optarg;
295 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
296 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
300 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
305 if (optarg == 0) goto needValueForOption;
306 session->config->token = optarg;
310 if (optarg == 0) goto needValueForOption;
311 session->config->ldpaths = optarg;
314 case SET_SESSION_DIR:
315 if (optarg == 0) goto needValueForOption;
316 session->config->sessiondir = optarg;
319 case SET_CACHE_TIMEOUT:
320 if (optarg == 0) goto needValueForOption;
321 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
325 if (optarg != 0) goto noValueForOption;
326 session->fakemod = 1;
330 if (optarg != 0) goto noValueForOption;
331 session->foreground = 1;
335 if (optarg != 0) goto noValueForOption;
336 session->background = 1;
340 if (optarg == 0) goto needValueForOption;
341 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
342 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
343 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
348 if (optarg == 0) goto needValueForOption;
349 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
352 case DISPLAY_VERSION:
353 if (optarg != 0) goto noValueForOption;
359 printHelp(programName);
365 config_set_default (session);
370 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
371 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
375 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
376 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
380 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
381 ,gnuOptions[optionIndex].name);
385 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
386 ,gnuOptions[optionIndex].name);
390 /*----------------------------------------------------------
392 | try to close everything before leaving
393 +--------------------------------------------------------- */
394 static void closeSession (int status, void *data) {
395 /* AFB_session *session = data; */
398 /*----------------------------------------------------------
401 +--------------------------------------------------------- */
402 void signalQuit (int signum) {
406 // unlock timeout signal to allow a new signal to come
407 sigemptyset (&sigset);
408 sigaddset (&sigset, SIGABRT);
409 sigprocmask (SIG_UNBLOCK, &sigset, 0);
411 fprintf (stderr, "ERR: Received signal quit\n");
412 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
417 /*----------------------------------------------------------
419 | Main listening HTTP loop
420 +--------------------------------------------------------- */
421 static void listenLoop (AFB_session *session) {
424 // ------ Start httpd server
426 err = httpdStart (session);
427 if (err != AFB_SUCCESS) return;
429 if (session->readyfd != 0) {
430 static const char readystr[] = "READY=1";
431 write(session->readyfd, readystr, sizeof(readystr) - 1);
432 close(session->readyfd);
438 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
441 /*----------------------------------------------------------
443 | set the process in background
444 +--------------------------------------------------------- */
445 static void daemonize(AFB_session *session)
450 // open /dev/console to redirect output messAFBes
451 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
453 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
457 // fork process when running background mode
460 // if fail nothing much to do
462 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
466 // if in father process, just leave
467 if (pid != 0) _exit (0);
469 // son process get all data in standalone mode
470 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
472 // redirect default I/O on console
473 close (2); dup(consoleFD); // redirect stderr
474 close (1); dup(consoleFD); // redirect stdout
475 close (0); // no need for stdin
479 setsid(); // allow father process to fully exit
480 sleep (2); // allow main to leave and release port
483 fprintf (stderr, "----------------------------\n");
484 fprintf (stderr, "INF: main background pid=%d\n", getpid());
488 /*---------------------------------------------------------
490 | Parse option and launch action
491 +--------------------------------------------------------- */
493 int main(int argc, char *argv[]) {
494 AFB_session *session;
496 // open syslog if ever needed
497 openlog("afb-daemon", 0, LOG_DAEMON);
499 // ------------- Build session handler & init config -------
500 session = calloc (1, sizeof (AFB_session));
501 session->config = calloc (1, sizeof (AFB_config));
503 on_exit(closeSession, session);
504 parse_arguments(argc, argv, session);
506 // ------------------ sanity check ----------------------------------------
507 if ((session->background) && (session->foreground)) {
508 fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
511 if (session->config->httpdPort <= 0) {
512 fprintf (stderr, "ERR: no port is defined\n");
516 initPlugins(session);
517 ctxStoreInit(CTX_NBCLIENTS);
519 // ------------------ Some useful default values -------------------------
520 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
522 // ------------------ clean exit on CTR-C signal ------------------------
523 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
524 fprintf (stderr, "ERR: main fail to install Signal handler\n");
529 // let's run this program with a low priority
532 // ------------------ Finaly Process Commands -----------------------------
533 // let's not take the risk to run as ROOT
534 //if (getuid() == 0) goto errorNoRoot;
536 #if defined(ALLOWS_SESSION_FILES)
537 // check session dir and create if it does not exist
538 if (sessionCheckdir (session) != AFB_SUCCESS) {
539 fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");
543 if (verbose) fprintf (stderr, "AFB: notice Init config done\n");
545 // ---- run in foreground mode --------------------
546 if (session->foreground) {
548 if (verbose) fprintf (stderr,"AFB: notice Foreground mode\n");
552 // --------- run in background mode -----------
553 if (session->background) {
555 if (verbose) printf ("AFB: Entering background mode\n");
559 // if everything look OK then look forever
560 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
563 } // end background-foreground
567 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");