2 * Copyright (C) 2015, 2016 "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.
29 #include <systemd/sd-event.h>
31 #include "afb-config.h"
32 #include "afb-hswitch.h"
34 #include "afb-api-so.h"
35 #include "afb-api-dbus.h"
37 #include "afb-context.h"
39 #include "afb-sig-handler.h"
42 #include "afb-common.h"
44 #include <afb/afb-plugin.h>
46 #if !defined(PLUGIN_INSTALL_DIR)
47 #error "you should define PLUGIN_INSTALL_DIR"
50 #define AFB_VERSION "0.4"
52 // Define command line option
54 #define SET_BACKGROUND 2
55 #define SET_FORGROUND 3
57 #define SET_TCP_PORT 5
58 #define SET_ROOT_DIR 6
59 #define SET_ROOT_BASE 7
60 #define SET_ROOT_API 8
63 #define SET_CACHE_TIMEOUT 10
64 #define SET_SESSION_DIR 11
66 #define SET_AUTH_TOKEN 12
68 #define SET_APITIMEOUT 14
69 #define SET_CNTXTIMEOUT 15
71 #define DISPLAY_VERSION 16
72 #define DISPLAY_HELP 17
75 #define SET_READYFD 19
77 #define DBUS_CLIENT 20
78 #define DBUS_SERVICE 21
81 // Command line structure hold cli --command + help text
83 int val; // command number within application
84 int has_arg; // command number within application
85 char *name; // command as used in --xxxx cli
86 char *help; // help text
91 static AFB_options cliOptions [] = {
92 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
94 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
95 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
97 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
98 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
99 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
100 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
101 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
103 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
104 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
105 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
107 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
109 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
110 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
112 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
113 {DISPLAY_HELP ,0,"help" , "Display this help"},
115 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
116 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
118 {DBUS_CLIENT ,1,"dbus-client" , "bind to an afb service through dbus"},
119 {DBUS_SERVICE ,1,"dbus-server" , "provides an afb service through dbus"},
120 {SO_PLUGIN ,1,"plugin" , "load the plugin of path"},
125 /*----------------------------------------------------------
127 | print version and copyright
128 +--------------------------------------------------------- */
129 static void printVersion (FILE *file)
131 fprintf(file, "\n----------------------------------------- \n");
132 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
133 fprintf(file, " \n");
134 fprintf(file, " Copyright (C) 2015, 2016 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
135 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
136 fprintf(file, " Licence Apache 2\n\n");
140 /*----------------------------------------------------------
142 | print information from long option array
143 +--------------------------------------------------------- */
145 static void printHelp(FILE *file, const char *name)
150 fprintf (file, "%s:\nallowed options\n", name);
151 for (ind=0; cliOptions [ind].name != NULL;ind++)
154 if (cliOptions [ind].has_arg == 0 )
156 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
158 sprintf(command, "%s=xxxx", cliOptions [ind].name);
159 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
162 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
165 // load config from disk and merge with CLI option
166 static void config_set_default (struct afb_config * config)
169 if (config->httpdPort == 0)
170 config->httpdPort = 1234;
172 // default Plugin API timeout
173 if (config->apiTimeout == 0)
174 config->apiTimeout = DEFLT_API_TIMEOUT;
176 // default AUTH_TOKEN
177 if (config->token == NULL)
178 config->token = DEFLT_AUTH_TOKEN;
180 // cache timeout default one hour
181 if (config->cacheTimeout == 0)
182 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
184 // cache timeout default one hour
185 if (config->cntxTimeout == 0)
186 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
188 if (config->rootdir == NULL) {
189 config->rootdir = getenv("AFBDIR");
190 if (config->rootdir == NULL) {
191 config->rootdir = malloc (512);
192 strncpy (config->rootdir, getenv("HOME"),512);
193 strncat (config->rootdir, "/.AFB",512);
195 // if directory does not exist createit
196 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
199 // if no Angular/HTML5 rootbase let's try '/' as default
200 if (config->rootbase == NULL)
201 config->rootbase = "/opa";
203 if (config->rootapi == NULL)
204 config->rootapi = "/api";
206 if (config->ldpaths == NULL)
207 config->ldpaths = PLUGIN_INSTALL_DIR;
209 // if no session dir create a default path from rootdir
210 if (config->sessiondir == NULL) {
211 config->sessiondir = malloc (512);
212 strncpy (config->sessiondir, config->rootdir, 512);
213 strncat (config->sessiondir, "/sessions",512);
216 // if no config dir create a default path from sessiondir
217 if (config->console == NULL) {
218 config->console = malloc (512);
219 strncpy (config->console, config->sessiondir, 512);
220 strncat (config->console, "/AFB-console.out",512);
225 /*---------------------------------------------------------
227 | Parse option and launch action
228 +--------------------------------------------------------- */
230 static void add_item(struct afb_config *config, int kind, char *value)
232 struct afb_config_item *item = malloc(sizeof *item);
234 ERROR("out of memory");
239 item->previous = config->items;
240 config->items = item;
243 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
245 char* programName = argv [0];
249 struct option *gnuOptions;
251 // ------------------ Process Command Line -----------------------
253 // if no argument print help and return
255 printHelp(stderr, programName);
259 // build GNU getopt info from cliOptions
260 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
261 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
262 for (ind=0; ind < nbcmd;ind++) {
263 gnuOptions [ind].name = cliOptions[ind].name;
264 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
265 gnuOptions [ind].flag = 0;
266 gnuOptions [ind].val = cliOptions[ind].val;
269 // get all options from command line
270 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
280 if (optarg == 0) goto needValueForOption;
281 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
285 if (optarg == 0) goto needValueForOption;
286 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
289 case SET_CNTXTIMEOUT:
290 if (optarg == 0) goto needValueForOption;
291 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
295 if (optarg == 0) goto needValueForOption;
296 config->rootdir = optarg;
297 INFO("Forcing Rootdir=%s",config->rootdir);
301 if (optarg == 0) goto needValueForOption;
302 config->rootbase = optarg;
303 INFO("Forcing Rootbase=%s",config->rootbase);
307 if (optarg == 0) goto needValueForOption;
308 config->rootapi = optarg;
309 INFO("Forcing Rootapi=%s",config->rootapi);
313 if (optarg == 0) goto needValueForOption;
314 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
315 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
316 if (optarg == NULL) {
317 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
319 config->aliasdir[config->aliascount].path = optarg;
320 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
321 config->aliascount++;
324 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
329 if (optarg == 0) goto needValueForOption;
330 config->token = optarg;
334 if (optarg == 0) goto needValueForOption;
335 config->ldpaths = optarg;
338 case SET_SESSION_DIR:
339 if (optarg == 0) goto needValueForOption;
340 config->sessiondir = optarg;
343 case SET_CACHE_TIMEOUT:
344 if (optarg == 0) goto needValueForOption;
345 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
349 if (optarg != 0) goto noValueForOption;
350 config->background = 0;
354 if (optarg != 0) goto noValueForOption;
355 config->background = 1;
359 if (optarg == 0) goto needValueForOption;
360 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
361 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
362 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
367 if (optarg == 0) goto needValueForOption;
368 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
374 if (optarg == 0) goto needValueForOption;
375 add_item(config, optc, optarg);
378 case DISPLAY_VERSION:
379 if (optarg != 0) goto noValueForOption;
380 printVersion(stdout);
385 printHelp(stdout, programName);
391 config_set_default (config);
396 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
397 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
401 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
402 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
406 ERROR("AFB-daemon option [--%s] don't take value"
407 ,gnuOptions[optionIndex].name);
411 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
412 ,gnuOptions[optionIndex].name);
416 /*----------------------------------------------------------
418 | try to close everything before leaving
419 +--------------------------------------------------------- */
420 static void closeSession (int status, void *data) {
421 /* struct afb_config *config = data; */
424 /*----------------------------------------------------------
426 | set the process in background
427 +--------------------------------------------------------- */
428 static void daemonize(struct afb_config *config)
433 // open /dev/console to redirect output messAFBes
434 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
436 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
440 // fork process when running background mode
443 // if fail nothing much to do
445 ERROR("AFB-daemon Failed to fork son process");
449 // if in father process, just leave
450 if (pid != 0) _exit (0);
452 // son process get all data in standalone mode
453 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
455 // redirect default I/O on console
456 close (2); dup(consoleFD); // redirect stderr
457 close (1); dup(consoleFD); // redirect stdout
458 close (0); // no need for stdin
462 setsid(); // allow father process to fully exit
463 sleep (2); // allow main to leave and release port
467 /*---------------------------------------------------------
469 | Handles the HTTP server
470 +--------------------------------------------------------- */
471 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
475 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
478 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
481 for (idx = 0; idx < config->aliascount; idx++)
482 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0))
485 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10))
488 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
494 static struct afb_hsrv *start_http_server(struct afb_config * config)
497 struct afb_hsrv *hsrv;
499 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
500 ERROR("unable to set the tmp directory");
504 hsrv = afb_hsrv_create();
506 ERROR("memory allocation failure");
510 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
511 || !init_http_server(hsrv, config)) {
512 ERROR("initialisation of httpd failed");
517 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
518 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
520 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
522 ERROR("starting of httpd failed");
530 static void start_items(struct afb_config_item *item)
533 /* keeps the order */
534 start_items(item->previous);
537 if (afb_api_dbus_add_client(item->value) < 0) {
538 ERROR("can't start the afb-dbus client of path %s",item->value);
543 if (afb_api_dbus_add_server(item->value) < 0) {
544 ERROR("can't start the afb-dbus service of path %s",item->value);
549 if (afb_api_so_add_plugin(item->value) < 0) {
550 ERROR("can't start the plugin of path %s",item->value);
555 ERROR("unexpected internal error");
563 /*---------------------------------------------------------
565 | Parse option and launch action
566 +--------------------------------------------------------- */
568 int main(int argc, char *argv[]) {
569 struct afb_hsrv *hsrv;
570 struct afb_config *config;
571 struct sd_event *eventloop;
573 LOGAUTH("afb-daemon");
575 // ------------- Build session handler & init config -------
576 config = calloc (1, sizeof (struct afb_config));
578 on_exit(closeSession, config);
579 parse_arguments(argc, argv, config);
581 // ------------------ sanity check ----------------------------------------
582 if (config->httpdPort <= 0) {
583 ERROR("no port is defined");
588 afb_api_so_add_pathset(config->ldpaths);
590 start_items(config->items);
591 config->items = NULL;
593 ctxStoreInit(CTX_NBCLIENTS, config->cntxTimeout, config->token, afb_apis_count());
594 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
595 ERROR("initialisation of cookies failed");
599 if (afb_sig_handler_init() < 0) {
600 ERROR("main fail to initialise signal handlers");
604 // let's run this program with a low priority
607 // ------------------ Finaly Process Commands -----------------------------
608 // let's not take the risk to run as ROOT
609 //if (getuid() == 0) goto errorNoRoot;
611 DEBUG("Init config done");
613 // --------- run -----------
614 if (config->background) {
615 // --------- in background mode -----------
616 INFO("entering background mode");
619 // ---- in foreground mode --------------------
620 INFO("entering foreground mode");
623 hsrv = start_http_server(config);
627 if (config->readyfd != 0) {
628 static const char readystr[] = "READY=1";
629 write(config->readyfd, readystr, sizeof(readystr) - 1);
630 close(config->readyfd);
634 eventloop = afb_common_get_event_loop();
636 sd_event_run(eventloop, 30000000);
638 WARNING("hoops returned from infinite loop [report bug]");