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>
31 #include "afb-plugin.h"
33 #include "local-def.h"
38 #if !defined(PLUGIN_INSTALL_DIR)
39 #error "you should define PLUGIN_INSTALL_DIR"
42 #define AFB_VERSION "0.1"
44 // Define command line option
46 #define SET_BACKGROUND 2
47 #define SET_FORGROUND 3
48 #define SET_FAKE_MOD 4
50 #define SET_TCP_PORT 5
51 #define SET_ROOT_DIR 6
52 #define SET_ROOT_BASE 7
53 #define SET_ROOT_API 8
56 #define SET_CACHE_TIMEOUT 10
57 #define SET_SESSION_DIR 11
59 #define SET_AUTH_TOKEN 12
61 #define SET_APITIMEOUT 14
62 #define SET_CNTXTIMEOUT 15
64 #define DISPLAY_VERSION 16
65 #define DISPLAY_HELP 17
68 #define SET_READYFD 19
70 // Command line structure hold cli --command + help text
72 int val; // command number within application
73 int has_arg; // command number within application
74 char *name; // command as used in --xxxx cli
75 char *help; // help text
80 static AFB_options cliOptions [] = {
81 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
83 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
84 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
86 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
87 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
88 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
89 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
90 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
92 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
93 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
94 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
96 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
98 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
99 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
101 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
102 {DISPLAY_HELP ,0,"help" , "Display this help"},
104 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
105 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
109 static AFB_aliasdir aliasdir[MAX_ALIAS];
110 static int aliascount = 0;
113 /*----------------------------------------------------------
115 | print version and copyright
116 +--------------------------------------------------------- */
117 static void printVersion (void)
119 fprintf (stderr,"\n----------------------------------------- \n");
120 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
121 fprintf (stderr,"----------------------------------------- \n");
122 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
123 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
124 fprintf (stderr,"| Licence Apache 2\n\n");
128 // load config from disk and merge with CLI option
129 static AFB_error config_set_default (AFB_session * session)
131 static char cacheTimeout [10];
134 if (session->config->httpdPort == 0) session->config->httpdPort=1234;
136 // default Plugin API timeout
137 if (session->config->apiTimeout == 0) session->config->apiTimeout=DEFLT_API_TIMEOUT;
139 // default AUTH_TOKEN
140 if (session->config->token == NULL) session->config->token= DEFLT_AUTH_TOKEN;
142 // cache timeout default one hour
143 if (session->config->cacheTimeout == 0) session->config->cacheTimeout=DEFLT_CACHE_TIMEOUT;
145 // cache timeout default one hour
146 if (session->config->cntxTimeout == 0) session->config->cntxTimeout=DEFLT_CNTX_TIMEOUT;
148 if (session->config->rootdir == NULL) {
149 session->config->rootdir = getenv("AFBDIR");
150 if (session->config->rootdir == NULL) {
151 session->config->rootdir = malloc (512);
152 strncpy (session->config->rootdir, getenv("HOME"),512);
153 strncat (session->config->rootdir, "/.AFB",512);
155 // if directory does not exist createit
156 mkdir (session->config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
159 // if no Angular/HTML5 rootbase let's try '/' as default
160 if (session->config->rootbase == NULL) {
161 session->config->rootbase = "/opa";
164 if (session->config->rootapi == NULL) {
165 session->config->rootapi = "/api";
168 if (session->config->ldpaths == NULL) {
169 session->config->ldpaths = PLUGIN_INSTALL_DIR;
172 // if no session dir create a default path from rootdir
173 if (session->config->sessiondir == NULL) {
174 session->config->sessiondir = malloc (512);
175 strncpy (session->config->sessiondir, session->config->rootdir, 512);
176 strncat (session->config->sessiondir, "/sessions",512);
179 // if no config dir create a default path from sessiondir
180 if (session->config->console == NULL) {
181 session->config->console = malloc (512);
182 strncpy (session->config->console, session->config->sessiondir, 512);
183 strncat (session->config->console, "/AFB-console.out",512);
186 // cacheTimeout is an integer but HTTPd wants it as a string
187 snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
188 session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
194 /*----------------------------------------------------------
196 | print information from long option array
197 +--------------------------------------------------------- */
199 static void printHelp(char *name) {
203 fprintf (stderr,"%s:\nallowed options\n", name);
204 for (ind=0; cliOptions [ind].name != NULL;ind++)
207 if (cliOptions [ind].has_arg == 0 )
209 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
211 sprintf(command,"%s=xxxx", cliOptions [ind].name);
212 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
215 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
218 /*---------------------------------------------------------
220 | Parse option and launch action
221 +--------------------------------------------------------- */
223 static void parse_arguments(int argc, char *argv[], AFB_session *session)
225 char* programName = argv [0];
229 struct option *gnuOptions;
231 // ------------- Build session handler & init config -------
232 memset(&aliasdir ,0,sizeof(aliasdir));
233 session->config->aliasdir = aliasdir;
235 // ------------------ Process Command Line -----------------------
237 // if no argument print help and return
239 printHelp(programName);
243 // build GNU getopt info from cliOptions
244 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
245 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
246 for (ind=0; ind < nbcmd;ind++) {
247 gnuOptions [ind].name = cliOptions[ind].name;
248 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
249 gnuOptions [ind].flag = 0;
250 gnuOptions [ind].val = cliOptions[ind].val;
253 // get all options from command line
254 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
264 if (optarg == 0) goto needValueForOption;
265 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
269 if (optarg == 0) goto needValueForOption;
270 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
273 case SET_CNTXTIMEOUT:
274 if (optarg == 0) goto needValueForOption;
275 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
279 if (optarg == 0) goto needValueForOption;
280 session->config->rootdir = optarg;
281 if (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
285 if (optarg == 0) goto needValueForOption;
286 session->config->rootbase = optarg;
287 if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
291 if (optarg == 0) goto needValueForOption;
292 session->config->rootapi = optarg;
293 if (verbosity) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
297 if (optarg == 0) goto needValueForOption;
298 if (aliascount < MAX_ALIAS) {
299 aliasdir[aliascount].url = strsep(&optarg,":");
300 if (optarg == NULL) {
301 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
303 aliasdir[aliascount].path = optarg;
304 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
305 if (verbosity) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
309 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
314 if (optarg == 0) goto needValueForOption;
315 session->config->token = optarg;
319 if (optarg == 0) goto needValueForOption;
320 session->config->ldpaths = optarg;
323 case SET_SESSION_DIR:
324 if (optarg == 0) goto needValueForOption;
325 session->config->sessiondir = optarg;
328 case SET_CACHE_TIMEOUT:
329 if (optarg == 0) goto needValueForOption;
330 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
334 if (optarg != 0) goto noValueForOption;
335 session->fakemod = 1;
339 if (optarg != 0) goto noValueForOption;
340 session->foreground = 1;
344 if (optarg != 0) goto noValueForOption;
345 session->background = 1;
349 if (optarg == 0) goto needValueForOption;
350 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
351 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
352 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
357 if (optarg == 0) goto needValueForOption;
358 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
361 case DISPLAY_VERSION:
362 if (optarg != 0) goto noValueForOption;
368 printHelp(programName);
374 config_set_default (session);
379 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
380 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
384 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
385 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
389 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
390 ,gnuOptions[optionIndex].name);
394 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
395 ,gnuOptions[optionIndex].name);
399 /*----------------------------------------------------------
401 | try to close everything before leaving
402 +--------------------------------------------------------- */
403 static void closeSession (int status, void *data) {
404 /* AFB_session *session = data; */
407 /*----------------------------------------------------------
410 +--------------------------------------------------------- */
411 void signalQuit (int signum) {
415 // unlock timeout signal to allow a new signal to come
416 sigemptyset (&sigset);
417 sigaddset (&sigset, SIGABRT);
418 sigprocmask (SIG_UNBLOCK, &sigset, 0);
420 fprintf (stderr, "ERR: Received signal quit\n");
421 syslog (LOG_ERR, "Daemon got kill3 & quit [please report bug]");
426 /*----------------------------------------------------------
429 +--------------------------------------------------------- */
430 __thread sigjmp_buf *error_handler;
431 static void signalError(int signum)
435 // unlock signal to allow a new signal to come
436 if (error_handler != NULL) {
437 sigemptyset(&sigset);
438 sigaddset(&sigset, signum);
439 sigprocmask(SIG_UNBLOCK, &sigset, 0);
440 longjmp(*error_handler, signum);
444 static void install_error_handlers()
446 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
448 for (i = 0; signals[i] != 0; i++) {
449 if (signal(signals[i], signalError) == SIG_ERR) {
450 fprintf(stderr, "Signal handler error\n");
456 /*----------------------------------------------------------
458 | Main listening HTTP loop
459 +--------------------------------------------------------- */
460 static void listenLoop (AFB_session *session) {
463 // ------ Start httpd server
465 err = httpdStart (session);
466 if (err != AFB_SUCCESS) return;
468 if (session->readyfd != 0) {
469 static const char readystr[] = "READY=1";
470 write(session->readyfd, readystr, sizeof(readystr) - 1);
471 close(session->readyfd);
477 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");
480 /*----------------------------------------------------------
482 | set the process in background
483 +--------------------------------------------------------- */
484 static void daemonize(AFB_session *session)
489 // open /dev/console to redirect output messAFBes
490 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
492 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
496 // fork process when running background mode
499 // if fail nothing much to do
501 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
505 // if in father process, just leave
506 if (pid != 0) _exit (0);
508 // son process get all data in standalone mode
509 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
511 // redirect default I/O on console
512 close (2); dup(consoleFD); // redirect stderr
513 close (1); dup(consoleFD); // redirect stdout
514 close (0); // no need for stdin
518 setsid(); // allow father process to fully exit
519 sleep (2); // allow main to leave and release port
522 fprintf (stderr, "----------------------------\n");
523 fprintf (stderr, "INF: main background pid=%d\n", getpid());
527 /*---------------------------------------------------------
529 | Parse option and launch action
530 +--------------------------------------------------------- */
532 int main(int argc, char *argv[]) {
533 AFB_session *session;
535 // open syslog if ever needed
536 openlog("afb-daemon", 0, LOG_DAEMON);
538 // ------------- Build session handler & init config -------
539 session = calloc (1, sizeof (AFB_session));
540 session->config = calloc (1, sizeof (AFB_config));
542 on_exit(closeSession, session);
543 parse_arguments(argc, argv, session);
545 // ------------------ sanity check ----------------------------------------
546 if ((session->background) && (session->foreground)) {
547 fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
550 if (session->config->httpdPort <= 0) {
551 fprintf (stderr, "ERR: no port is defined\n");
555 if (session->config->ldpaths)
556 afb_apis_add_pathset(session->config->ldpaths);
558 ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, afb_apis_count(), session->config->token);
560 install_error_handlers();
562 // ------------------ Some useful default values -------------------------
563 if ((session->background == 0) && (session->foreground == 0)) session->foreground=1;
565 // ------------------ clean exit on CTR-C signal ------------------------
566 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
567 fprintf (stderr, "ERR: main fail to install Signal handler\n");
572 // let's run this program with a low priority
575 // ------------------ Finaly Process Commands -----------------------------
576 // let's not take the risk to run as ROOT
577 //if (getuid() == 0) goto errorNoRoot;
579 #if defined(ALLOWS_SESSION_FILES)
580 // check session dir and create if it does not exist
581 if (sessionCheckdir (session) != AFB_SUCCESS) {
582 fprintf (stderr,"\nERR: AFB-daemon cannot read/write session dir\n\n");
586 if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
588 // ---- run in foreground mode --------------------
589 if (session->foreground) {
591 if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
595 // --------- run in background mode -----------
596 if (session->background) {
598 if (verbosity) printf ("AFB: Entering background mode\n");
602 // if everything look OK then look forever
603 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
606 } // end background-foreground
610 if (verbosity) printf ("\n---- Application Framework Binder Normal End ------\n");