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
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 void config_set_default (AFB_session * session)
132 if (session->config->httpdPort == 0)
133 session->config->httpdPort = 1234;
135 // default Plugin API timeout
136 if (session->config->apiTimeout == 0)
137 session->config->apiTimeout = DEFLT_API_TIMEOUT;
139 // default AUTH_TOKEN
140 if (session->config->token == NULL)
141 session->config->token = DEFLT_AUTH_TOKEN;
143 // cache timeout default one hour
144 if (session->config->cacheTimeout == 0)
145 session->config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
147 // cache timeout default one hour
148 if (session->config->cntxTimeout == 0)
149 session->config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
151 if (session->config->rootdir == NULL) {
152 session->config->rootdir = getenv("AFBDIR");
153 if (session->config->rootdir == NULL) {
154 session->config->rootdir = malloc (512);
155 strncpy (session->config->rootdir, getenv("HOME"),512);
156 strncat (session->config->rootdir, "/.AFB",512);
158 // if directory does not exist createit
159 mkdir (session->config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
162 // if no Angular/HTML5 rootbase let's try '/' as default
163 if (session->config->rootbase == NULL)
164 session->config->rootbase = "/opa";
166 if (session->config->rootapi == NULL)
167 session->config->rootapi = "/api";
169 if (session->config->ldpaths == NULL)
170 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);
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 (verbosity) fprintf(stderr, "Forcing Rootdir=%s\n",session->config->rootdir);
279 if (optarg == 0) goto needValueForOption;
280 session->config->rootbase = optarg;
281 if (verbosity) fprintf(stderr, "Forcing Rootbase=%s\n",session->config->rootbase);
285 if (optarg == 0) goto needValueForOption;
286 session->config->rootapi = optarg;
287 if (verbosity) 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 (verbosity) 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->background = 0;
333 if (optarg != 0) goto noValueForOption;
334 session->background = 1;
338 if (optarg == 0) goto needValueForOption;
339 if (!strcmp(optarg, "local")) session->config->mode = AFB_MODE_LOCAL;
340 else if (!strcmp(optarg, "remote")) session->config->mode = AFB_MODE_REMOTE;
341 else if (!strcmp(optarg, "global")) session->config->mode = AFB_MODE_GLOBAL;
346 if (optarg == 0) goto needValueForOption;
347 if (!sscanf (optarg, "%u", &session->readyfd)) goto notAnInteger;
350 case DISPLAY_VERSION:
351 if (optarg != 0) goto noValueForOption;
357 printHelp(programName);
363 config_set_default (session);
368 fprintf (stderr,"\nERR: AFB-daemon option [--%s] need a value i.e. --%s=xxx\n\n"
369 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
373 fprintf (stderr,"\nERR: AFB-daemon option [--%s] requirer an interger i.e. --%s=9\n\n"
374 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
378 fprintf (stderr,"\nERR: AFB-daemon option [--%s] don't take value\n\n"
379 ,gnuOptions[optionIndex].name);
383 fprintf (stderr,"\nERR: AFB-daemon option [--%s] only accepts local, global or remote.\n\n"
384 ,gnuOptions[optionIndex].name);
388 /*----------------------------------------------------------
390 | try to close everything before leaving
391 +--------------------------------------------------------- */
392 static void closeSession (int status, void *data) {
393 /* AFB_session *session = data; */
396 /*----------------------------------------------------------
398 +--------------------------------------------------------- */
399 void signalQuit (int signum)
401 fprintf(stderr, "Terminating signal received %s\n", strsignal(signum));
406 /*----------------------------------------------------------
409 +--------------------------------------------------------- */
410 __thread sigjmp_buf *error_handler;
411 static void signalError(int signum)
415 // unlock signal to allow a new signal to come
416 if (error_handler != NULL) {
417 sigemptyset(&sigset);
418 sigaddset(&sigset, signum);
419 sigprocmask(SIG_UNBLOCK, &sigset, 0);
420 longjmp(*error_handler, signum);
422 if (signum == SIGALRM)
424 fprintf(stderr, "Unmonitored signal received %s\n", strsignal(signum));
428 static void install_error_handlers()
430 int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
432 for (i = 0; signals[i] != 0; i++) {
433 if (signal(signals[i], signalError) == SIG_ERR) {
434 fprintf(stderr, "Signal handler error\n");
440 /*----------------------------------------------------------
442 | set the process in background
443 +--------------------------------------------------------- */
444 static void daemonize(AFB_session *session)
449 // open /dev/console to redirect output messAFBes
450 consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
452 fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
456 // fork process when running background mode
459 // if fail nothing much to do
461 fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
465 // if in father process, just leave
466 if (pid != 0) _exit (0);
468 // son process get all data in standalone mode
469 printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
471 // redirect default I/O on console
472 close (2); dup(consoleFD); // redirect stderr
473 close (1); dup(consoleFD); // redirect stdout
474 close (0); // no need for stdin
478 setsid(); // allow father process to fully exit
479 sleep (2); // allow main to leave and release port
482 fprintf (stderr, "----------------------------\n");
483 fprintf (stderr, "INF: main background pid=%d\n", getpid());
487 /*---------------------------------------------------------
489 | Parse option and launch action
490 +--------------------------------------------------------- */
492 int main(int argc, char *argv[]) {
494 AFB_session *session;
496 // open syslog if ever needed
497 openlog("afb-daemon", 0, LOG_DAEMON);
499 // ------------- Build session handler & init config -------
500 session = calloc (1, sizeof (AFB_session));
501 session->config = calloc (1, sizeof (AFB_config));
503 on_exit(closeSession, session);
504 parse_arguments(argc, argv, session);
506 // ------------------ sanity check ----------------------------------------
507 if (session->config->httpdPort <= 0) {
508 fprintf (stderr, "ERR: no port is defined\n");
512 if (session->config->ldpaths)
513 afb_apis_add_pathset(session->config->ldpaths);
515 ctxStoreInit(CTX_NBCLIENTS, session->config->cntxTimeout, afb_apis_count(), session->config->token);
517 install_error_handlers();
519 // ------------------ clean exit on CTR-C signal ------------------------
520 if (signal (SIGINT, signalQuit) == SIG_ERR || signal (SIGABRT, signalQuit) == SIG_ERR) {
521 fprintf (stderr, "ERR: main fail to install Signal handler\n");
525 // let's run this program with a low priority
528 // ------------------ Finaly Process Commands -----------------------------
529 // let's not take the risk to run as ROOT
530 //if (getuid() == 0) goto errorNoRoot;
532 if (verbosity) fprintf (stderr, "AFB: notice Init config done\n");
534 // --------- run -----------
535 if (session->background) {
536 // --------- in background mode -----------
537 if (verbosity) printf ("AFB: Entering background mode\n");
540 // ---- in foreground mode --------------------
541 if (verbosity) fprintf (stderr,"AFB: notice Foreground mode\n");
545 rc = afb_hsrv_start (session);
549 if (session->readyfd != 0) {
550 static const char readystr[] = "READY=1";
551 write(session->readyfd, readystr, sizeof(readystr) - 1);
552 close(session->readyfd);
560 fprintf (stderr, "hoops returned from infinite loop [report bug]\n");