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.
26 #include <sys/types.h>
28 #include "local-def.h"
32 #if !defined(PLUGIN_INSTALL_DIR)
33 #error "you should define PLUGIN_INSTALL_DIR"
36 #define AFB_VERSION "0.1"
38 // Define command line option
40 #define SET_BACKGROUND 2
41 #define SET_FORGROUND 3
42 #define SET_FAKE_MOD 4
44 #define SET_TCP_PORT 5
45 #define SET_ROOT_DIR 6
46 #define SET_ROOT_BASE 7
47 #define SET_ROOT_API 8
50 #define SET_CACHE_TIMEOUT 10
51 #define SET_SESSION_DIR 11
53 #define SET_AUTH_TOKEN 12
55 #define SET_APITIMEOUT 14
56 #define SET_CNTXTIMEOUT 15
58 #define DISPLAY_VERSION 16
59 #define DISPLAY_HELP 17
62 #define SET_READYFD 19
64 // Command line structure hold cli --command + help text
66 int val; // command number within application
67 int has_arg; // command number within application
68 char *name; // command as used in --xxxx cli
69 char *help; // help text
74 static AFB_options cliOptions [] = {
75 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
77 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
78 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
80 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
81 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
82 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
83 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
84 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
86 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
87 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
88 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
90 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
92 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
93 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
95 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
96 {DISPLAY_HELP ,0,"help" , "Display this help"},
98 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
99 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
103 static AFB_aliasdir aliasdir[MAX_ALIAS];
104 static int aliascount = 0;
107 /*----------------------------------------------------------
109 | print version and copyright
110 +--------------------------------------------------------- */
111 static void printVersion (void)
113 fprintf (stderr,"\n----------------------------------------- \n");
114 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
115 fprintf (stderr,"----------------------------------------- \n");
116 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
117 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
118 fprintf (stderr,"| Licence Apache 2\n\n");
122 // load config from disk and merge with CLI option
123 static AFB_error config_set_default (AFB_session * session)
125 static char cacheTimeout [10];
128 if (session->config->httpdPort == 0) session->config->httpdPort=1234;
130 // default Plugin API timeout
131 if (session->config->apiTimeout == 0) session->config->apiTimeout=DEFLT_API_TIMEOUT;
133 // default AUTH_TOKEN
134 if (session->config->token == NULL) session->config->token= DEFLT_AUTH_TOKEN;
136 // cache timeout default one hour
137 if (session->config->cacheTimeout == 0) session->config->cacheTimeout=DEFLT_CACHE_TIMEOUT;
139 // cache timeout default one hour
140 if (session->config->cntxTimeout == 0) session->config->cntxTimeout=DEFLT_CNTX_TIMEOUT;
142 if (session->config->rootdir == NULL) {
143 session->config->rootdir = getenv("AFBDIR");
144 if (session->config->rootdir == NULL) {
145 session->config->rootdir = malloc (512);
146 strncpy (session->config->rootdir, getenv("HOME"),512);
147 strncat (session->config->rootdir, "/.AFB",512);
149 // if directory does not exist createit
150 mkdir (session->config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
153 // if no Angular/HTML5 rootbase let's try '/' as default
154 if (session->config->rootbase == NULL) {
155 session->config->rootbase = "/opa";
158 if (session->config->rootapi == NULL) {
159 session->config->rootapi = "/api";
162 if (session->config->ldpaths == NULL) {
163 session->config->ldpaths = PLUGIN_INSTALL_DIR;
166 // if no session dir create a default path from rootdir
167 if (session->config->sessiondir == NULL) {
168 session->config->sessiondir = malloc (512);
169 strncpy (session->config->sessiondir, session->config->rootdir, 512);
170 strncat (session->config->sessiondir, "/sessions",512);
173 // if no config dir create a default path from sessiondir
174 if (session->config->console == NULL) {
175 session->config->console = malloc (512);
176 strncpy (session->config->console, session->config->sessiondir, 512);
177 strncat (session->config->console, "/AFB-console.out",512);
180 // cacheTimeout is an integer but HTTPd wants it as a string
181 snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
182 session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
188 /*----------------------------------------------------------
190 | print information from long option array
191 +--------------------------------------------------------- */
193 static void printHelp(char *name) {
197 fprintf (stderr,"%s:\nallowed options\n", name);
198 for (ind=0; cliOptions [ind].name != NULL;ind++)
201 if (cliOptions [ind].has_arg == 0 )
203 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
205 sprintf(command,"%s=xxxx", cliOptions [ind].name);
206 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
209 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
212 /*---------------------------------------------------------
214 | Parse option and launch action
215 +--------------------------------------------------------- */
217 static void parse_arguments(int argc, char *argv[], AFB_session *session)
219 char* programName = argv [0];
223 struct option *gnuOptions;
225 // ------------- Build session handler & init config -------
226 memset(&aliasdir ,0,sizeof(aliasdir));
227 session->config->aliasdir = aliasdir;
229 // ------------------ Process Command Line -----------------------
231 // if no argument print help and return
233 printHelp(programName);
237 // build GNU getopt info from cliOptions
238 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
239 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
240 for (ind=0; ind < nbcmd;ind++) {
241 gnuOptions [ind].name = cliOptions[ind].name;
242 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
243 gnuOptions [ind].flag = 0;
244 gnuOptions [ind].val = cliOptions[ind].val;
247 // get all options from command line
248 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
258 if (optarg == 0) goto needValueForOption;
259 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
263 if (optarg == 0) goto needValueForOption;
264 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
267 case SET_CNTXTIMEOUT:
268 if (optarg == 0) goto needValueForOption;
269 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
273 if (optarg == 0) goto needValueForOption;
274 session->config->rootdir = optarg;
275 if (verbose) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
279 if (optarg == 0) goto needValueForOption;
280 session->config->rootbase = optarg;
281 if (verbose) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
285 if (optarg == 0) goto needValueForOption;
286 session->config->rootapi = optarg;
287 if (verbose) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
291 if (optarg == 0) goto needValueForOption;
292 if (aliascount < MAX_ALIAS) {
293 aliasdir[aliascount].url = strsep(&optarg,":");
294 if (optarg == NULL) {
295 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
297 aliasdir[aliascount].path = optarg;
298 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
299 if (verbose) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
303 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
308 if (optarg == 0) goto needValueForOption;
309 session->config->token = optarg;
313 if (optarg == 0) goto needValueForOption;
314 session->config->ldpaths = optarg;
317 case SET_SESSION_DIR:
318 if (optarg == 0) goto needValueForOption;
319 session->config->sessiondir = optarg;
322 case SET_CACHE_TIMEOUT:
323 if (optarg == 0) goto needValueForOption;
324 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
328 if (optarg != 0) goto noValueForOption;
329 session->fakemod = 1;
333 if (optarg != 0) goto noValueForOption;
334 session->foreground = 1;
338 if (optarg != 0) goto noValueForOption;
339 session->background = 1;
343 if (optarg == 0) goto needValueForOption;
344 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
345 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
346 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
351 if (optarg == 0) goto needValueForOption;
352 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
355 case DISPLAY_VERSION:
356 if (optarg != 0) goto noValueForOption;
362 printHelp(programName);
368 config_set_default (session);
373 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
374 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
378 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
379 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
383 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
384 ,gnuOptions[optionIndex].name);
388 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
389 ,gnuOptions[optionIndex].name);
393 /*----------------------------------------------------------
395 | try to close everything before leaving
396 +--------------------------------------------------------- */
397 static void closeSession (int status, void *data) {
398 /* AFB_session *session = data; */
401 /*----------------------------------------------------------
404 +--------------------------------------------------------- */
405 void signalQuit (int signum) {
409 // unlock timeout signal to allow a new signal to come
410 sigemptyset (&sigset);
411 sigaddset (&sigset, SIGABRT);
412 sigprocmask (SIG_UNBLOCK, &sigset, 0);
414 fprintf (stderr, "ERR: Received signal quit\n");
415 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
420 /*----------------------------------------------------------
423 +--------------------------------------------------------- */
424 __thread sigjmp_buf *error_handler;
425 static void signalError(int signum)
429 // unlock signal to allow a new signal to come
430 sigemptyset(&sigset);
431 sigaddset(&sigset, signum);
432 sigprocmask(SIG_UNBLOCK, &sigset, 0);
433 if (error_handler != NULL) {
434 longjmp(*error_handler, signum);
438 static void install_error_handlers()
440 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
442 for (i = 0; signals[i] != 0; i++) {
443 if (signal(signals[i], signalError) == SIG_ERR) {
444 fprintf(stderr, "Signal handler error\n");
450 /*----------------------------------------------------------
452 | Main listening HTTP loop
453 +--------------------------------------------------------- */
454 static void listenLoop (AFB_session *session) {
457 // ------ Start httpd server
459 err = httpdStart (session);
460 if (err != AFB_SUCCESS) return;
462 if (session->readyfd != 0) {
463 static const char readystr[] = "READY=1";
464 write(session->readyfd, readystr, sizeof(readystr) - 1);
465 close(session->readyfd);
471 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
474 /*----------------------------------------------------------
476 | set the process in background
477 +--------------------------------------------------------- */
478 static void daemonize(AFB_session *session)
483 // open /dev/console to redirect output messAFBes
484 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
486 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
490 // fork process when running background mode
493 // if fail nothing much to do
495 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
499 // if in father process, just leave
500 if (pid != 0) _exit (0);
502 // son process get all data in standalone mode
503 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
505 // redirect default I/O on console
506 close (2); dup(consoleFD); // redirect stderr
507 close (1); dup(consoleFD); // redirect stdout
508 close (0); // no need for stdin
512 setsid(); // allow father process to fully exit
513 sleep (2); // allow main to leave and release port
516 fprintf (stderr, "----------------------------\n");
517 fprintf (stderr, "INF: main background pid=%d\n", getpid());
521 /*---------------------------------------------------------
523 | Parse option and launch action
524 +--------------------------------------------------------- */
526 int main(int argc, char *argv[]) {
527 AFB_session *session;
529 // open syslog if ever needed
530 openlog("afb-daemon", 0, LOG_DAEMON);
532 // ------------- Build session handler & init config -------
533 session = calloc (1, sizeof (AFB_session));
534 session->config = calloc (1, sizeof (AFB_config));
536 on_exit(closeSession, session);
537 parse_arguments(argc, argv, session);
539 // ------------------ sanity check ----------------------------------------
540 if ((session->background) && (session->foreground)) {
541 fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
544 if (session->config->httpdPort <= 0) {
545 fprintf (stderr, "ERR: no port is defined\n");
549 if (session->config->ldpaths)
550 afb_apis_add_pathset(session->config->ldpaths);
552 ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, afb_apis_count(), session->config->token);
554 install_error_handlers();
556 // ------------------ Some useful default values -------------------------
557 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
559 // ------------------ clean exit on CTR-C signal ------------------------
560 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
561 fprintf (stderr, "ERR: main fail to install Signal handler\n");
566 // let's run this program with a low priority
569 // ------------------ Finaly Process Commands -----------------------------
570 // let's not take the risk to run as ROOT
571 //if (getuid() == 0) goto errorNoRoot;
573 #if defined(ALLOWS_SESSION_FILES)
574 // check session dir and create if it does not exist
575 if (sessionCheckdir (session) != AFB_SUCCESS) {
576 fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");
580 if (verbose) fprintf (stderr, "AFB: notice Init config done\n");
582 // ---- run in foreground mode --------------------
583 if (session->foreground) {
585 if (verbose) fprintf (stderr,"AFB: notice Foreground mode\n");
589 // --------- run in background mode -----------
590 if (session->background) {
592 if (verbose) printf ("AFB: Entering background mode\n");
596 // if everything look OK then look forever
597 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
600 } // end background-foreground
604 if (verbose) printf ("\n---- Application Framework Binder Normal End ------\n");