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"
28 #include "afb-plugins.h"
30 #if !defined(PLUGIN_INSTALL_DIR)
31 #error "you should define PLUGIN_INSTALL_DIR"
34 #define AFB_VERSION "0.1"
36 // Define command line option
38 #define SET_BACKGROUND 2
39 #define SET_FORGROUND 3
40 #define SET_FAKE_MOD 4
42 #define SET_TCP_PORT 5
43 #define SET_ROOT_DIR 6
44 #define SET_ROOT_BASE 7
45 #define SET_ROOT_API 8
48 #define SET_CACHE_TIMEOUT 10
49 #define SET_SESSION_DIR 11
51 #define SET_AUTH_TOKEN 12
53 #define SET_APITIMEOUT 14
54 #define SET_CNTXTIMEOUT 15
56 #define DISPLAY_VERSION 16
57 #define DISPLAY_HELP 17
60 #define SET_READYFD 19
62 // Command line structure hold cli --command + help text
64 int val; // command number within application
65 int has_arg; // command number within application
66 char *name; // command as used in --xxxx cli
67 char *help; // help text
72 static AFB_options cliOptions [] = {
73 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
75 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
76 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
78 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
79 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
80 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
81 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
82 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
84 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
85 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
86 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
88 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
90 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
91 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
93 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
94 {DISPLAY_HELP ,0,"help" , "Display this help"},
96 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
97 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
101 static AFB_aliasdir aliasdir[MAX_ALIAS];
102 static int aliascount = 0;
105 /*----------------------------------------------------------
107 | print version and copyright
108 +--------------------------------------------------------- */
109 static void printVersion (void)
111 fprintf (stderr,"\n----------------------------------------- \n");
112 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
113 fprintf (stderr,"----------------------------------------- \n");
114 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
115 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
116 fprintf (stderr,"| Licence Apache 2\n\n");
120 // load config from disk and merge with CLI option
121 static AFB_error config_set_default (AFB_session * session)
123 static char cacheTimeout [10];
126 if (session->config->httpdPort == 0) session->config->httpdPort=1234;
128 // default Plugin API timeout
129 if (session->config->apiTimeout == 0) session->config->apiTimeout=DEFLT_API_TIMEOUT;
131 // default AUTH_TOKEN
132 if (session->config->token == NULL) session->config->token= DEFLT_AUTH_TOKEN;
134 // cache timeout default one hour
135 if (session->config->cacheTimeout == 0) session->config->cacheTimeout=DEFLT_CACHE_TIMEOUT;
137 // cache timeout default one hour
138 if (session->config->cntxTimeout == 0) session->config->cntxTimeout=DEFLT_CNTX_TIMEOUT;
140 if (session->config->rootdir == NULL) {
141 session->config->rootdir = getenv("AFBDIR");
142 if (session->config->rootdir == NULL) {
143 session->config->rootdir = malloc (512);
144 strncpy (session->config->rootdir, getenv("HOME"),512);
145 strncat (session->config->rootdir, "/.AFB",512);
147 // if directory does not exist createit
148 mkdir (session->config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
151 // if no Angular/HTML5 rootbase let's try '/' as default
152 if (session->config->rootbase == NULL) {
153 session->config->rootbase = "/opa";
156 if (session->config->rootapi == NULL) {
157 session->config->rootapi = "/api";
160 if (session->config->ldpaths == NULL) {
161 session->config->ldpaths = PLUGIN_INSTALL_DIR;
164 // if no session dir create a default path from rootdir
165 if (session->config->sessiondir == NULL) {
166 session->config->sessiondir = malloc (512);
167 strncpy (session->config->sessiondir, session->config->rootdir, 512);
168 strncat (session->config->sessiondir, "/sessions",512);
171 // if no config dir create a default path from sessiondir
172 if (session->config->console == NULL) {
173 session->config->console = malloc (512);
174 strncpy (session->config->console, session->config->sessiondir, 512);
175 strncat (session->config->console, "/AFB-console.out",512);
178 // cacheTimeout is an integer but HTTPd wants it as a string
179 snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
180 session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
186 /*----------------------------------------------------------
188 | print information from long option array
189 +--------------------------------------------------------- */
191 static void printHelp(char *name) {
195 fprintf (stderr,"%s:\nallowed options\n", name);
196 for (ind=0; cliOptions [ind].name != NULL;ind++)
199 if (cliOptions [ind].has_arg == 0 )
201 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
203 sprintf(command,"%s=xxxx", cliOptions [ind].name);
204 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
207 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
210 /*---------------------------------------------------------
212 | Parse option and launch action
213 +--------------------------------------------------------- */
215 static void parse_arguments(int argc, char *argv[], AFB_session *session)
217 char* programName = argv [0];
221 struct option *gnuOptions;
223 // ------------- Build session handler & init config -------
224 memset(&aliasdir ,0,sizeof(aliasdir));
225 session->config->aliasdir = aliasdir;
227 // ------------------ Process Command Line -----------------------
229 // if no argument print help and return
231 printHelp(programName);
235 // build GNU getopt info from cliOptions
236 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
237 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
238 for (ind=0; ind < nbcmd;ind++) {
239 gnuOptions [ind].name = cliOptions[ind].name;
240 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
241 gnuOptions [ind].flag = 0;
242 gnuOptions [ind].val = cliOptions[ind].val;
245 // get all options from command line
246 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
256 if (optarg == 0) goto needValueForOption;
257 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
261 if (optarg == 0) goto needValueForOption;
262 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
265 case SET_CNTXTIMEOUT:
266 if (optarg == 0) goto needValueForOption;
267 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
271 if (optarg == 0) goto needValueForOption;
272 session->config->rootdir = optarg;
273 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
277 if (optarg == 0) goto needValueForOption;
278 session->config->rootbase = optarg;
279 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
283 if (optarg == 0) goto needValueForOption;
284 session->config->rootapi = optarg;
285 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
289 if (optarg == 0) goto needValueForOption;
290 if (aliascount < MAX_ALIAS) {
291 aliasdir[aliascount].url = strsep(&optarg,":");
292 if (optarg == NULL) {
293 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
295 aliasdir[aliascount].path = optarg;
296 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
297 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
301 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
306 if (optarg == 0) goto needValueForOption;
307 session->config->token = optarg;
311 if (optarg == 0) goto needValueForOption;
312 session->config->ldpaths = optarg;
315 case SET_SESSION_DIR:
316 if (optarg == 0) goto needValueForOption;
317 session->config->sessiondir = optarg;
320 case SET_CACHE_TIMEOUT:
321 if (optarg == 0) goto needValueForOption;
322 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
326 if (optarg != 0) goto noValueForOption;
327 session->fakemod = 1;
331 if (optarg != 0) goto noValueForOption;
332 session->foreground = 1;
336 if (optarg != 0) goto noValueForOption;
337 session->background = 1;
341 if (optarg == 0) goto needValueForOption;
342 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
343 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
344 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
349 if (optarg == 0) goto needValueForOption;
350 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
353 case DISPLAY_VERSION:
354 if (optarg != 0) goto noValueForOption;
360 printHelp(programName);
366 config_set_default (session);
371 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
372 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
376 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
377 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
381 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
382 ,gnuOptions[optionIndex].name);
386 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
387 ,gnuOptions[optionIndex].name);
391 /*----------------------------------------------------------
393 | try to close everything before leaving
394 +--------------------------------------------------------- */
395 static void closeSession (int status, void *data) {
396 /* AFB_session *session = data; */
399 /*----------------------------------------------------------
402 +--------------------------------------------------------- */
403 void signalQuit (int signum) {
407 // unlock timeout signal to allow a new signal to come
408 sigemptyset (&sigset);
409 sigaddset (&sigset, SIGABRT);
410 sigprocmask (SIG_UNBLOCK, &sigset, 0);
412 fprintf (stderr, "ERR: Received signal quit\n");
413 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
418 /*----------------------------------------------------------
420 | Main listening HTTP loop
421 +--------------------------------------------------------- */
422 static void listenLoop (AFB_session *session) {
425 // ------ Start httpd server
427 err = httpdStart (session);
428 if (err != AFB_SUCCESS) return;
430 if (session->readyfd != 0) {
431 static const char readystr[] = "READY=1";
432 write(session->readyfd, readystr, sizeof(readystr) - 1);
433 close(session->readyfd);
439 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
442 /*----------------------------------------------------------
444 | set the process in background
445 +--------------------------------------------------------- */
446 static void daemonize(AFB_session *session)
451 // open /dev/console to redirect output messAFBes
452 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
454 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
458 // fork process when running background mode
461 // if fail nothing much to do
463 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
467 // if in father process, just leave
468 if (pid != 0) _exit (0);
470 // son process get all data in standalone mode
471 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
473 // redirect default I/O on console
474 close (2); dup(consoleFD); // redirect stderr
475 close (1); dup(consoleFD); // redirect stdout
476 close (0); // no need for stdin
480 setsid(); // allow father process to fully exit
481 sleep (2); // allow main to leave and release port
484 fprintf (stderr, "----------------------------\n");
485 fprintf (stderr, "INF: main background pid=%d\n", getpid());
489 /*---------------------------------------------------------
491 | Parse option and launch action
492 +--------------------------------------------------------- */
494 int main(int argc, char *argv[]) {
495 AFB_session *session;
497 // open syslog if ever needed
498 openlog("afb-daemon", 0, LOG_DAEMON);
500 // ------------- Build session handler & init config -------
501 session = calloc (1, sizeof (AFB_session));
502 session->config = calloc (1, sizeof (AFB_config));
504 on_exit(closeSession, session);
505 parse_arguments(argc, argv, session);
507 // ------------------ sanity check ----------------------------------------
508 if ((session->background) && (session->foreground)) {
509 fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
512 if (session->config->httpdPort <= 0) {
513 fprintf (stderr, "ERR: no port is defined\n");
517 initPlugins(session);
518 ctxStoreInit(CTX_NBCLIENTS);
520 // ------------------ Some useful default values -------------------------
521 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
523 // ------------------ clean exit on CTR-C signal ------------------------
524 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
525 fprintf (stderr, "ERR: main fail to install Signal handler\n");
530 // let's run this program with a low priority
533 // ------------------ Finaly Process Commands -----------------------------
534 // let's not take the risk to run as ROOT
535 //if (getuid() == 0) goto errorNoRoot;
537 #if defined(ALLOWS_SESSION_FILES)
538 // check session dir and create if it does not exist
539 if (sessionCheckdir (session) != AFB_SUCCESS) {
540 fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");
544 if (verbose) fprintf (stderr, "AFB: notice Init config done\n");
546 // ---- run in foreground mode --------------------
547 if (session->foreground) {
549 if (verbose) fprintf (stderr,"AFB: notice Foreground mode\n");
553 // --------- run in background mode -----------
554 if (session->background) {
556 if (verbose) printf ("AFB: Entering background mode\n");
560 // if everything look OK then look forever
561 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
564 } // end background-foreground
568 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");