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.
28 #include <sys/types.h>
30 #include "afb-plugin.h"
32 #include "local-def.h"
37 #if !defined(PLUGIN_INSTALL_DIR)
38 #error "you should define PLUGIN_INSTALL_DIR"
41 #define AFB_VERSION "0.1"
43 // Define command line option
45 #define SET_BACKGROUND 2
46 #define SET_FORGROUND 3
47 #define SET_FAKE_MOD 4
49 #define SET_TCP_PORT 5
50 #define SET_ROOT_DIR 6
51 #define SET_ROOT_BASE 7
52 #define SET_ROOT_API 8
55 #define SET_CACHE_TIMEOUT 10
56 #define SET_SESSION_DIR 11
58 #define SET_AUTH_TOKEN 12
60 #define SET_APITIMEOUT 14
61 #define SET_CNTXTIMEOUT 15
63 #define DISPLAY_VERSION 16
64 #define DISPLAY_HELP 17
67 #define SET_READYFD 19
69 // Command line structure hold cli --command + help text
71 int val; // command number within application
72 int has_arg; // command number within application
73 char *name; // command as used in --xxxx cli
74 char *help; // help text
79 static AFB_options cliOptions [] = {
80 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
82 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
83 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
85 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
86 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
87 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
88 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
89 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
91 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
92 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
93 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
95 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
97 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
98 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
100 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
101 {DISPLAY_HELP ,0,"help" , "Display this help"},
103 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
104 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
108 static AFB_aliasdir aliasdir[MAX_ALIAS];
109 static int aliascount = 0;
112 /*----------------------------------------------------------
114 | print version and copyright
115 +--------------------------------------------------------- */
116 static void printVersion (void)
118 fprintf (stderr,"\n----------------------------------------- \n");
119 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
120 fprintf (stderr,"----------------------------------------- \n");
121 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
122 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
123 fprintf (stderr,"| Licence Apache 2\n\n");
127 // load config from disk and merge with CLI option
128 static AFB_error config_set_default (AFB_session * session)
130 static char cacheTimeout [10];
133 if (session->config->httpdPort == 0) session->config->httpdPort=1234;
135 // default Plugin API timeout
136 if (session->config->apiTimeout == 0) session->config->apiTimeout=DEFLT_API_TIMEOUT;
138 // default AUTH_TOKEN
139 if (session->config->token == NULL) session->config->token= DEFLT_AUTH_TOKEN;
141 // cache timeout default one hour
142 if (session->config->cacheTimeout == 0) session->config->cacheTimeout=DEFLT_CACHE_TIMEOUT;
144 // cache timeout default one hour
145 if (session->config->cntxTimeout == 0) session->config->cntxTimeout=DEFLT_CNTX_TIMEOUT;
147 if (session->config->rootdir == NULL) {
148 session->config->rootdir = getenv("AFBDIR");
149 if (session->config->rootdir == NULL) {
150 session->config->rootdir = malloc (512);
151 strncpy (session->config->rootdir, getenv("HOME"),512);
152 strncat (session->config->rootdir, "/.AFB",512);
154 // if directory does not exist createit
155 mkdir (session->config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
158 // if no Angular/HTML5 rootbase let's try '/' as default
159 if (session->config->rootbase == NULL) {
160 session->config->rootbase = "/opa";
163 if (session->config->rootapi == NULL) {
164 session->config->rootapi = "/api";
167 if (session->config->ldpaths == NULL) {
168 session->config->ldpaths = PLUGIN_INSTALL_DIR;
171 // if no session dir create a default path from rootdir
172 if (session->config->sessiondir == NULL) {
173 session->config->sessiondir = malloc (512);
174 strncpy (session->config->sessiondir, session->config->rootdir, 512);
175 strncat (session->config->sessiondir, "/sessions",512);
178 // if no config dir create a default path from sessiondir
179 if (session->config->console == NULL) {
180 session->config->console = malloc (512);
181 strncpy (session->config->console, session->config->sessiondir, 512);
182 strncat (session->config->console, "/AFB-console.out",512);
185 // cacheTimeout is an integer but HTTPd wants it as a string
186 snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
187 session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
193 /*----------------------------------------------------------
195 | print information from long option array
196 +--------------------------------------------------------- */
198 static void printHelp(char *name) {
202 fprintf (stderr,"%s:\nallowed options\n", name);
203 for (ind=0; cliOptions [ind].name != NULL;ind++)
206 if (cliOptions [ind].has_arg == 0 )
208 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
210 sprintf(command,"%s=xxxx", cliOptions [ind].name);
211 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
214 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
217 /*---------------------------------------------------------
219 | Parse option and launch action
220 +--------------------------------------------------------- */
222 static void parse_arguments(int argc, char *argv[], AFB_session *session)
224 char* programName = argv [0];
228 struct option *gnuOptions;
230 // ------------- Build session handler & init config -------
231 memset(&aliasdir ,0,sizeof(aliasdir));
232 session->config->aliasdir = aliasdir;
234 // ------------------ Process Command Line -----------------------
236 // if no argument print help and return
238 printHelp(programName);
242 // build GNU getopt info from cliOptions
243 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
244 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
245 for (ind=0; ind < nbcmd;ind++) {
246 gnuOptions [ind].name = cliOptions[ind].name;
247 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
248 gnuOptions [ind].flag = 0;
249 gnuOptions [ind].val = cliOptions[ind].val;
252 // get all options from command line
253 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
263 if (optarg == 0) goto needValueForOption;
264 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
268 if (optarg == 0) goto needValueForOption;
269 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
272 case SET_CNTXTIMEOUT:
273 if (optarg == 0) goto needValueForOption;
274 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
278 if (optarg == 0) goto needValueForOption;
279 session->config->rootdir = optarg;
280 if (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
284 if (optarg == 0) goto needValueForOption;
285 session->config->rootbase = optarg;
286 if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
290 if (optarg == 0) goto needValueForOption;
291 session->config->rootapi = optarg;
292 if (verbosity) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
296 if (optarg == 0) goto needValueForOption;
297 if (aliascount < MAX_ALIAS) {
298 aliasdir[aliascount].url = strsep(&optarg,":");
299 if (optarg == NULL) {
300 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
302 aliasdir[aliascount].path = optarg;
303 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
304 if (verbosity) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
308 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
313 if (optarg == 0) goto needValueForOption;
314 session->config->token = optarg;
318 if (optarg == 0) goto needValueForOption;
319 session->config->ldpaths = optarg;
322 case SET_SESSION_DIR:
323 if (optarg == 0) goto needValueForOption;
324 session->config->sessiondir = optarg;
327 case SET_CACHE_TIMEOUT:
328 if (optarg == 0) goto needValueForOption;
329 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
333 if (optarg != 0) goto noValueForOption;
334 session->fakemod = 1;
338 if (optarg != 0) goto noValueForOption;
339 session->foreground = 1;
343 if (optarg != 0) goto noValueForOption;
344 session->background = 1;
348 if (optarg == 0) goto needValueForOption;
349 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
350 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
351 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
356 if (optarg == 0) goto needValueForOption;
357 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
360 case DISPLAY_VERSION:
361 if (optarg != 0) goto noValueForOption;
367 printHelp(programName);
373 config_set_default (session);
378 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
379 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
383 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
384 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
388 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
389 ,gnuOptions[optionIndex].name);
393 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
394 ,gnuOptions[optionIndex].name);
398 /*----------------------------------------------------------
400 | try to close everything before leaving
401 +--------------------------------------------------------- */
402 static void closeSession (int status, void *data) {
403 /* AFB_session *session = data; */
406 /*----------------------------------------------------------
409 +--------------------------------------------------------- */
410 void signalQuit (int signum) {
414 // unlock timeout signal to allow a new signal to come
415 sigemptyset (&sigset);
416 sigaddset (&sigset, SIGABRT);
417 sigprocmask (SIG_UNBLOCK, &sigset, 0);
419 fprintf (stderr, "ERR: Received signal quit\n");
420 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
425 /*----------------------------------------------------------
428 +--------------------------------------------------------- */
429 __thread sigjmp_buf *error_handler;
430 static void signalError(int signum)
434 // unlock signal to allow a new signal to come
435 if (error_handler != NULL) {
436 sigemptyset(&sigset);
437 sigaddset(&sigset, signum);
438 sigprocmask(SIG_UNBLOCK, &sigset, 0);
439 longjmp(*error_handler, signum);
443 static void install_error_handlers()
445 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
447 for (i = 0; signals[i] != 0; i++) {
448 if (signal(signals[i], signalError) == SIG_ERR) {
449 fprintf(stderr, "Signal handler error\n");
455 /*----------------------------------------------------------
457 | Main listening HTTP loop
458 +--------------------------------------------------------- */
459 static void listenLoop (AFB_session *session) {
462 // ------ Start httpd server
464 err = httpdStart (session);
465 if (err != AFB_SUCCESS) return;
467 if (session->readyfd != 0) {
468 static const char readystr[] = "READY=1";
469 write(session->readyfd, readystr, sizeof(readystr) - 1);
470 close(session->readyfd);
476 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
479 /*----------------------------------------------------------
481 | set the process in background
482 +--------------------------------------------------------- */
483 static void daemonize(AFB_session *session)
488 // open /dev/console to redirect output messAFBes
489 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
491 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
495 // fork process when running background mode
498 // if fail nothing much to do
500 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
504 // if in father process, just leave
505 if (pid != 0) _exit (0);
507 // son process get all data in standalone mode
508 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
510 // redirect default I/O on console
511 close (2); dup(consoleFD); // redirect stderr
512 close (1); dup(consoleFD); // redirect stdout
513 close (0); // no need for stdin
517 setsid(); // allow father process to fully exit
518 sleep (2); // allow main to leave and release port
521 fprintf (stderr, "----------------------------\n");
522 fprintf (stderr, "INF: main background pid=%d\n", getpid());
526 /*---------------------------------------------------------
528 | Parse option and launch action
529 +--------------------------------------------------------- */
531 int main(int argc, char *argv[]) {
532 AFB_session *session;
534 // open syslog if ever needed
535 openlog("afb-daemon", 0, LOG_DAEMON);
537 // ------------- Build session handler & init config -------
538 session = calloc (1, sizeof (AFB_session));
539 session->config = calloc (1, sizeof (AFB_config));
541 on_exit(closeSession, session);
542 parse_arguments(argc, argv, session);
544 // ------------------ sanity check ----------------------------------------
545 if ((session->background) && (session->foreground)) {
546 fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
549 if (session->config->httpdPort <= 0) {
550 fprintf (stderr, "ERR: no port is defined\n");
554 if (session->config->ldpaths)
555 afb_apis_add_pathset(session->config->ldpaths);
557 ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, afb_apis_count(), session->config->token);
559 install_error_handlers();
561 // ------------------ Some useful default values -------------------------
562 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
564 // ------------------ clean exit on CTR-C signal ------------------------
565 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
566 fprintf (stderr, "ERR: main fail to install Signal handler\n");
571 // let's run this program with a low priority
574 // ------------------ Finaly Process Commands -----------------------------
575 // let's not take the risk to run as ROOT
576 //if (getuid() == 0) goto errorNoRoot;
578 #if defined(ALLOWS_SESSION_FILES)
579 // check session dir and create if it does not exist
580 if (sessionCheckdir (session) != AFB_SUCCESS) {
581 fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");
585 if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
587 // ---- run in foreground mode --------------------
588 if (session->foreground) {
590 if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
594 // --------- run in background mode -----------
595 if (session->background) {
597 if (verbosity) printf ("AFB: Entering background mode\n");
601 // if everything look OK then look forever
602 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
605 } // end background-foreground
609 if (verbosity) printf ("\n---- Application Framework Binder Normal End ------\n");