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 | try to close everything before leaving
212 +--------------------------------------------------------- */
213 static void closeSession (int status, void *data) {
214 // AFB_session *session = data;
217 /*----------------------------------------------------------
220 +--------------------------------------------------------- */
221 void signalQuit (int signum) {
225 // unlock timeout signal to allow a new signal to come
226 sigemptyset (&sigset);
227 sigaddset (&sigset, SIGABRT);
228 sigprocmask (SIG_UNBLOCK, &sigset, 0);
230 fprintf (stderr, "ERR: Received signal quit\n");
231 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
236 /*----------------------------------------------------------
238 | Main listening HTTP loop
239 +--------------------------------------------------------- */
240 static void listenLoop (AFB_session *session) {
243 // ------ Start httpd server
245 err = httpdStart (session);
246 if (err != AFB_SUCCESS) return;
248 if (session->readyfd != 0) {
249 static const char readystr[] = "READY=1";
250 write(session->readyfd, readystr, sizeof(readystr) - 1);
251 close(session->readyfd);
257 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
260 /*---------------------------------------------------------
262 | Parse option and launch action
263 +--------------------------------------------------------- */
265 static void parse_arguments(int argc, char *argv[], AFB_session *session)
267 char* programName = argv [0];
271 struct option *gnuOptions;
273 // ------------- Build session handler & init config -------
274 memset(&aliasdir ,0,sizeof(aliasdir));
275 session->config->aliasdir = aliasdir;
277 // ------------------ Process Command Line -----------------------
279 // if no argument print help and return
281 printHelp(programName);
285 // build GNU getopt info from cliOptions
286 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
287 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
288 for (ind=0; ind < nbcmd;ind++) {
289 gnuOptions [ind].name = cliOptions[ind].name;
290 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
291 gnuOptions [ind].flag = 0;
292 gnuOptions [ind].val = cliOptions[ind].val;
295 // get all options from command line
296 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
306 if (optarg == 0) goto needValueForOption;
307 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
311 if (optarg == 0) goto needValueForOption;
312 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
315 case SET_CNTXTIMEOUT:
316 if (optarg == 0) goto needValueForOption;
317 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
321 if (optarg == 0) goto needValueForOption;
322 session->config->rootdir = optarg;
323 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
327 if (optarg == 0) goto needValueForOption;
328 session->config->rootbase = optarg;
329 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
333 if (optarg == 0) goto needValueForOption;
334 session->config->rootapi = optarg;
335 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
339 if (optarg == 0) goto needValueForOption;
340 if (aliascount < MAX_ALIAS) {
341 aliasdir[aliascount].url = strsep(&optarg,":");
342 if (optarg == NULL) {
343 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
345 aliasdir[aliascount].path = optarg;
346 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
347 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
351 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
356 if (optarg == 0) goto needValueForOption;
357 session->config->token = optarg;
361 if (optarg == 0) goto needValueForOption;
362 session->config->ldpaths = optarg;
365 case SET_SESSION_DIR:
366 if (optarg == 0) goto needValueForOption;
367 session->config->sessiondir = optarg;
370 case SET_CACHE_TIMEOUT:
371 if (optarg == 0) goto needValueForOption;
372 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
376 if (optarg != 0) goto noValueForOption;
377 session->fakemod = 1;
381 if (optarg != 0) goto noValueForOption;
382 session->foreground = 1;
386 if (optarg != 0) goto noValueForOption;
387 session->background = 1;
391 if (optarg == 0) goto needValueForOption;
392 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
393 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
394 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
399 if (optarg == 0) goto needValueForOption;
400 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
403 case DISPLAY_VERSION:
404 if (optarg != 0) goto noValueForOption;
410 printHelp(programName);
416 config_set_default (session);
421 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
422 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
426 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
427 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
431 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
432 ,gnuOptions[optionIndex].name);
436 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
437 ,gnuOptions[optionIndex].name);
441 /*---------------------------------------------------------
443 | Parse option and launch action
444 +--------------------------------------------------------- */
446 int main(int argc, char *argv[]) {
447 AFB_session *session;
451 // open syslog if ever needed
452 openlog("afb-daemon", 0, LOG_DAEMON);
454 // ------------- Build session handler & init config -------
455 session = calloc (1, sizeof (AFB_session));
456 session->config = calloc (1, sizeof (AFB_config));
458 on_exit(closeSession, session);
459 parse_arguments(argc, argv, session);
461 initPlugins(session);
463 // ------------------ sanity check ----------------------------------------
464 if ((session->background) && (session->foreground)) {
465 fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
468 if (session->config->httpdPort <= 0) {
469 fprintf (stderr, "ERR: no port is defined\n");
473 // ------------------ Some useful default values -------------------------
474 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
476 // ------------------ clean exit on CTR-C signal ------------------------
477 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
478 fprintf (stderr, "ERR: main fail to install Signal handler\n");
483 // let's run this program with a low priority
486 // ------------------ Finaly Process Commands -----------------------------
487 // let's not take the risk to run as ROOT
488 //if (getuid() == 0) goto errorNoRoot;
490 // check session dir and create if it does not exist
491 if (sessionCheckdir (session) != AFB_SUCCESS) goto errSessiondir;
492 if (verbose) fprintf (stderr, "AFB: notice Init config done\n");
494 // ---- run in foreground mode --------------------
495 if (session->foreground) {
497 if (verbose) fprintf (stderr,"AFB: notice Foreground mode\n");
499 // enter listening loop in foreground
505 // --------- run in background mode -----------
506 if (session->background) {
508 // if (status != 0) goto errorCommand;
509 if (verbose) printf ("AFB: Entering background mode\n");
511 // open /dev/console to redirect output messAFBes
512 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
513 if (consoleFD < 0) goto errConsole;
515 // fork process when running background mode
518 // son process get all data in standalone mode
521 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
523 // redirect default I/O on console
524 close (2); dup(consoleFD); // redirect stderr
525 close (1); dup(consoleFD); // redirect stdout
526 close (0); // no need for stdin
529 setsid(); // allow father process to fully exit
530 sleep (2); // allow main to leave and release port
532 fprintf (stderr, "----------------------------\n");
533 fprintf (stderr, "INF: main background pid=%d\n", getpid());
536 // if everything look OK then look forever
537 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
539 // should normally never return from this loop
541 syslog (LOG_ERR, "AFB: FAIL background infinite loop exited check [%s]\n", session->config->console);
546 // if fail nothing much to do
547 if (pid == -1) goto errorFork;
549 // we are in father process, we don't need this one
552 } // end background-foreground
554 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");
557 // ------------- Fatal ERROR display error and quit -------------
559 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
563 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
567 fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");