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 #include "utils-upoll.h"
39 #if !defined(PLUGIN_INSTALL_DIR)
40 #error "you should define PLUGIN_INSTALL_DIR"
43 #define AFB_VERSION "0.1"
45 // Define command line option
47 #define SET_BACKGROUND 2
48 #define SET_FORGROUND 3
49 #define SET_FAKE_MOD 4
51 #define SET_TCP_PORT 5
52 #define SET_ROOT_DIR 6
53 #define SET_ROOT_BASE 7
54 #define SET_ROOT_API 8
57 #define SET_CACHE_TIMEOUT 10
58 #define SET_SESSION_DIR 11
60 #define SET_AUTH_TOKEN 12
62 #define SET_APITIMEOUT 14
63 #define SET_CNTXTIMEOUT 15
65 #define DISPLAY_VERSION 16
66 #define DISPLAY_HELP 17
69 #define SET_READYFD 19
71 // Command line structure hold cli --command + help text
73 int val; // command number within application
74 int has_arg; // command number within application
75 char *name; // command as used in --xxxx cli
76 char *help; // help text
81 static AFB_options cliOptions [] = {
82 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
84 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
85 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
87 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
88 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
89 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
90 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
91 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
93 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
94 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
95 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
97 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
99 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
100 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
102 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
103 {DISPLAY_HELP ,0,"help" , "Display this help"},
105 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
106 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
110 static AFB_aliasdir aliasdir[MAX_ALIAS];
111 static int aliascount = 0;
114 /*----------------------------------------------------------
116 | print version and copyright
117 +--------------------------------------------------------- */
118 static void printVersion (void)
120 fprintf (stderr,"\n----------------------------------------- \n");
121 fprintf (stderr,"| AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
122 fprintf (stderr,"----------------------------------------- \n");
123 fprintf (stderr,"| Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
124 fprintf (stderr,"| AFB comes with ABSOLUTELY NO WARRANTY.\n");
125 fprintf (stderr,"| Licence Apache 2\n\n");
129 // load config from disk and merge with CLI option
130 static void config_set_default (AFB_session * session)
132 static char cacheTimeout [10];
135 if (session->config->httpdPort == 0)
136 session->config->httpdPort = 1234;
138 // default Plugin API timeout
139 if (session->config->apiTimeout == 0)
140 session->config->apiTimeout = DEFLT_API_TIMEOUT;
142 // default AUTH_TOKEN
143 if (session->config->token == NULL)
144 session->config->token = DEFLT_AUTH_TOKEN;
146 // cache timeout default one hour
147 if (session->config->cacheTimeout == 0)
148 session->config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
150 // cache timeout default one hour
151 if (session->config->cntxTimeout == 0)
152 session->config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
154 if (session->config->rootdir == NULL) {
155 session->config->rootdir = getenv("AFBDIR");
156 if (session->config->rootdir == NULL) {
157 session->config->rootdir = malloc (512);
158 strncpy (session->config->rootdir, getenv("HOME"),512);
159 strncat (session->config->rootdir, "/.AFB",512);
161 // if directory does not exist createit
162 mkdir (session->config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
165 // if no Angular/HTML5 rootbase let's try '/' as default
166 if (session->config->rootbase == NULL)
167 session->config->rootbase = "/opa";
169 if (session->config->rootapi == NULL)
170 session->config->rootapi = "/api";
172 if (session->config->ldpaths == NULL)
173 session->config->ldpaths = PLUGIN_INSTALL_DIR;
175 // if no session dir create a default path from rootdir
176 if (session->config->sessiondir == NULL) {
177 session->config->sessiondir = malloc (512);
178 strncpy (session->config->sessiondir, session->config->rootdir, 512);
179 strncat (session->config->sessiondir, "/sessions",512);
182 // if no config dir create a default path from sessiondir
183 if (session->config->console == NULL) {
184 session->config->console = malloc (512);
185 strncpy (session->config->console, session->config->sessiondir, 512);
186 strncat (session->config->console, "/AFB-console.out",512);
189 // cacheTimeout is an integer but HTTPd wants it as a string
190 snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
191 session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
195 /*----------------------------------------------------------
197 | print information from long option array
198 +--------------------------------------------------------- */
200 static void printHelp(char *name) {
204 fprintf (stderr,"%s:\nallowed options\n", name);
205 for (ind=0; cliOptions [ind].name != NULL;ind++)
208 if (cliOptions [ind].has_arg == 0 )
210 fprintf (stderr," --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
212 sprintf(command,"%s=xxxx", cliOptions [ind].name);
213 fprintf (stderr," --%-15s %s\n", command, cliOptions[ind].help);
216 fprintf (stderr,"Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
219 /*---------------------------------------------------------
221 | Parse option and launch action
222 +--------------------------------------------------------- */
224 static void parse_arguments(int argc, char *argv[], AFB_session *session)
226 char* programName = argv [0];
230 struct option *gnuOptions;
232 // ------------- Build session handler & init config -------
233 memset(&aliasdir ,0,sizeof(aliasdir));
234 session->config->aliasdir = aliasdir;
236 // ------------------ Process Command Line -----------------------
238 // if no argument print help and return
240 printHelp(programName);
244 // build GNU getopt info from cliOptions
245 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
246 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
247 for (ind=0; ind < nbcmd;ind++) {
248 gnuOptions [ind].name = cliOptions[ind].name;
249 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
250 gnuOptions [ind].flag = 0;
251 gnuOptions [ind].val = cliOptions[ind].val;
254 // get all options from command line
255 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
265 if (optarg == 0) goto needValueForOption;
266 if (!sscanf (optarg, "%d", &session->config->httpdPort)) goto notAnInteger;
270 if (optarg == 0) goto needValueForOption;
271 if (!sscanf (optarg, "%d", &session->config->apiTimeout)) goto notAnInteger;
274 case SET_CNTXTIMEOUT:
275 if (optarg == 0) goto needValueForOption;
276 if (!sscanf (optarg, "%d", &session->config->cntxTimeout)) goto notAnInteger;
280 if (optarg == 0) goto needValueForOption;
281 session->config->rootdir = optarg;
282 if (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
286 if (optarg == 0) goto needValueForOption;
287 session->config->rootbase = optarg;
288 if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
292 if (optarg == 0) goto needValueForOption;
293 session->config->rootapi = optarg;
294 if (verbosity) fprintf(stderr, "Forcing Rootapi=%s\n",session->config->rootapi);
298 if (optarg == 0) goto needValueForOption;
299 if (aliascount < MAX_ALIAS) {
300 aliasdir[aliascount].url = strsep(&optarg,":");
301 if (optarg == NULL) {
302 fprintf(stderr, "missing ':' in alias %s, ignored\n", aliasdir[aliascount].url);
304 aliasdir[aliascount].path = optarg;
305 aliasdir[aliascount].len = strlen(aliasdir[aliascount].url);
306 if (verbosity) fprintf(stderr, "Alias url=%s path=%s\n", aliasdir[aliascount].url, aliasdir[aliascount].path);
310 fprintf(stderr, "Too many aliases [max:%d] %s ignored\n", MAX_ALIAS, optarg);
315 if (optarg == 0) goto needValueForOption;
316 session->config->token = optarg;
320 if (optarg == 0) goto needValueForOption;
321 session->config->ldpaths = optarg;
324 case SET_SESSION_DIR:
325 if (optarg == 0) goto needValueForOption;
326 session->config->sessiondir = optarg;
329 case SET_CACHE_TIMEOUT:
330 if (optarg == 0) goto needValueForOption;
331 if (!sscanf (optarg, "%d", &session->config->cacheTimeout)) goto notAnInteger;
335 if (optarg != 0) goto noValueForOption;
336 session->fakemod = 1;
340 if (optarg != 0) goto noValueForOption;
341 session->foreground = 1;
345 if (optarg != 0) goto noValueForOption;
346 session->background = 1;
350 if (optarg == 0) goto needValueForOption;
351 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
352 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
353 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
358 if (optarg == 0) goto needValueForOption;
359 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
362 case DISPLAY_VERSION:
363 if (optarg != 0) goto noValueForOption;
369 printHelp(programName);
375 config_set_default (session);
380 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
381 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
385 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
386 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
390 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
391 ,gnuOptions[optionIndex].name);
395 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
396 ,gnuOptions[optionIndex].name);
400 /*----------------------------------------------------------
402 | try to close everything before leaving
403 +--------------------------------------------------------- */
404 static void closeSession (int status, void *data) {
405 /* AFB_session *session = data; */
408 /*----------------------------------------------------------
410 +--------------------------------------------------------- */
411 void signalQuit (int signum)
413 fprintf(stderr, "Terminating signal received %s\n", strsignal(signum));
418 /*----------------------------------------------------------
421 +--------------------------------------------------------- */
422 __thread sigjmp_buf *error_handler;
423 static void signalError(int signum)
427 // unlock signal to allow a new signal to come
428 if (error_handler != NULL) {
429 sigemptyset(&sigset);
430 sigaddset(&sigset, signum);
431 sigprocmask(SIG_UNBLOCK, &sigset, 0);
432 longjmp(*error_handler, signum);
434 if (signum == SIGALRM)
436 fprintf(stderr, "Unmonitored signal received %s\n", strsignal(signum));
440 static void install_error_handlers()
442 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
444 for (i = 0; signals[i] != 0; i++) {
445 if (signal(signals[i], signalError) == SIG_ERR) {
446 fprintf(stderr, "Signal handler error\n");
452 /*----------------------------------------------------------
454 | set the process in background
455 +--------------------------------------------------------- */
456 static void daemonize(AFB_session *session)
461 // open /dev/console to redirect output messAFBes
462 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
464 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
468 // fork process when running background mode
471 // if fail nothing much to do
473 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
477 // if in father process, just leave
478 if (pid != 0) _exit (0);
480 // son process get all data in standalone mode
481 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
483 // redirect default I/O on console
484 close (2); dup(consoleFD); // redirect stderr
485 close (1); dup(consoleFD); // redirect stdout
486 close (0); // no need for stdin
490 setsid(); // allow father process to fully exit
491 sleep (2); // allow main to leave and release port
494 fprintf (stderr, "----------------------------\n");
495 fprintf (stderr, "INF: main background pid=%d\n", getpid());
499 /*---------------------------------------------------------
501 | Parse option and launch action
502 +--------------------------------------------------------- */
504 int main(int argc, char *argv[]) {
506 AFB_session *session;
508 // open syslog if ever needed
509 openlog("afb-daemon", 0, LOG_DAEMON);
511 // ------------- Build session handler & init config -------
512 session = calloc (1, sizeof (AFB_session));
513 session->config = calloc (1, sizeof (AFB_config));
515 on_exit(closeSession, session);
516 parse_arguments(argc, argv, session);
518 // ------------------ sanity check ----------------------------------------
519 if ((session->background) && (session->foreground)) {
520 fprintf (stderr, "ERR: cannot select foreground & background at the same time\n");
523 if (session->config->httpdPort <= 0) {
524 fprintf (stderr, "ERR: no port is defined\n");
528 if (session->config->ldpaths)
529 afb_apis_add_pathset(session->config->ldpaths);
531 ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, afb_apis_count(), session->config->token);
533 install_error_handlers();
535 // ------------------ Some useful default values -------------------------
536 if ((session->background == 0) && (session->foreground == 0))
537 session->foreground = 1;
539 // ------------------ clean exit on CTR-C signal ------------------------
540 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
541 fprintf (stderr, "ERR: main fail to install Signal handler\n");
545 // let's run this program with a low priority
548 // ------------------ Finaly Process Commands -----------------------------
549 // let's not take the risk to run as ROOT
550 //if (getuid() == 0) goto errorNoRoot;
552 if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
554 // ---- run in foreground mode --------------------
555 if (session->foreground) {
557 if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
561 // --------- run in background mode -----------
562 if (session->background) {
564 if (verbosity) printf ("AFB: Entering background mode\n");
568 // if everything look OK then look forever
569 syslog (LOG_ERR, "AFB: Entering infinite loop in background mode");
572 } // end background-foreground
575 // ------ Start httpd server
577 rc = afb_hsrv_start (session);
581 if (session->readyfd != 0) {
582 static const char readystr[] = "READY=1";
583 write(session->readyfd, readystr, sizeof(readystr) - 1);
584 close(session->readyfd);
592 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");