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.
20 #define NO_BINDING_VERBOSE_MACRO
30 #include <systemd/sd-event.h>
32 #include "afb-config.h"
33 #include "afb-hswitch.h"
35 #include "afb-api-so.h"
36 #include "afb-api-dbus.h"
37 #include "afb-api-ws.h"
39 #include "afb-context.h"
41 #include "afb-sig-handler.h"
44 #include "afb-common.h"
46 #include <afb/afb-binding.h>
48 #if !defined(BINDING_INSTALL_DIR)
49 #error "you should define BINDING_INSTALL_DIR"
52 #define AFB_VERSION "0.5"
54 // Define command line option
56 #define SET_BACKGROUND 2
57 #define SET_FORGROUND 3
59 #define SET_TCP_PORT 5
60 #define SET_ROOT_DIR 6
61 #define SET_ROOT_BASE 7
62 #define SET_ROOT_API 8
65 #define SET_CACHE_TIMEOUT 10
66 #define SET_SESSION_DIR 11
68 #define SET_AUTH_TOKEN 12
70 #define SET_APITIMEOUT 14
71 #define SET_CNTXTIMEOUT 15
73 #define DISPLAY_VERSION 16
74 #define DISPLAY_HELP 17
77 #define SET_READYFD 19
79 #define DBUS_CLIENT 20
80 #define DBUS_SERVICE 21
83 #define SET_SESSIONMAX 23
88 // Command line structure hold cli --command + help text
90 int val; // command number within application
91 int has_arg; // command number within application
92 char *name; // command as used in --xxxx cli
93 char *help; // help text
98 static AFB_options cliOptions [] = {
99 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
101 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
102 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
104 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
105 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
106 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
107 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
108 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
110 {SET_APITIMEOUT ,1,"apitimeout" , "Binding API timeout in seconds [default 10]"},
111 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
112 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600]"},
114 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
116 {SET_LDPATH ,1,"ldpaths" , "Load bindingss from dir1:dir2:... [default = "BINDING_INSTALL_DIR"]"},
117 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
119 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
120 {DISPLAY_HELP ,0,"help" , "Display this help"},
122 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
123 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
125 {DBUS_CLIENT ,1,"dbus-client" , "bind to an afb service through dbus"},
126 {DBUS_SERVICE ,1,"dbus-server" , "provides an afb service through dbus"},
127 {WS_CLIENT ,1,"ws-client" , "bind to an afb service through websocket"},
128 {WS_SERVICE ,1,"ws-server" , "provides an afb service through websockets"},
129 {SO_BINDING ,1,"binding" , "load the binding of path"},
131 {SET_SESSIONMAX ,1,"session-max" , "max count of session simultaneously [default 10]"},
136 /*----------------------------------------------------------
138 | print version and copyright
139 +--------------------------------------------------------- */
140 static void printVersion (FILE *file)
142 fprintf(file, "\n----------------------------------------- \n");
143 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
144 fprintf(file, " \n");
145 fprintf(file, " Copyright (C) 2015, 2016 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
146 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
147 fprintf(file, " Licence Apache 2\n\n");
151 /*----------------------------------------------------------
153 | print information from long option array
154 +--------------------------------------------------------- */
156 static void printHelp(FILE *file, const char *name)
161 fprintf (file, "%s:\nallowed options\n", name);
162 for (ind=0; cliOptions [ind].name != NULL;ind++)
165 if (cliOptions [ind].has_arg == 0 )
167 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
169 sprintf(command, "%s=xxxx", cliOptions [ind].name);
170 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
173 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n", name);
176 // load config from disk and merge with CLI option
177 static void config_set_default (struct afb_config * config)
180 if (config->httpdPort == 0)
181 config->httpdPort = 1234;
183 // default binding API timeout
184 if (config->apiTimeout == 0)
185 config->apiTimeout = DEFLT_API_TIMEOUT;
187 // default AUTH_TOKEN
188 if (config->token == NULL)
189 config->token = DEFLT_AUTH_TOKEN;
191 // cache timeout default one hour
192 if (config->cacheTimeout == 0)
193 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
195 // cache timeout default one hour
196 if (config->cntxTimeout == 0)
197 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
199 // max count of sessions
200 if (config->nbSessionMax == 0)
201 config->nbSessionMax = CTX_NBCLIENTS;
203 if (config->rootdir == NULL) {
204 config->rootdir = getenv("AFBDIR");
205 if (config->rootdir == NULL) {
206 config->rootdir = malloc (512);
207 strncpy (config->rootdir, getenv("HOME"),512);
208 strncat (config->rootdir, "/.AFB",512);
210 // if directory does not exist createit
211 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
214 // if no Angular/HTML5 rootbase let's try '/' as default
215 if (config->rootbase == NULL)
216 config->rootbase = "/opa";
218 if (config->rootapi == NULL)
219 config->rootapi = "/api";
221 if (config->ldpaths == NULL)
222 config->ldpaths = BINDING_INSTALL_DIR;
224 // if no session dir create a default path from rootdir
225 if (config->sessiondir == NULL) {
226 config->sessiondir = malloc (512);
227 strncpy (config->sessiondir, config->rootdir, 512);
228 strncat (config->sessiondir, "/sessions",512);
231 // if no config dir create a default path from sessiondir
232 if (config->console == NULL) {
233 config->console = malloc (512);
234 strncpy (config->console, config->sessiondir, 512);
235 strncat (config->console, "/AFB-console.out",512);
240 /*---------------------------------------------------------
242 | Parse option and launch action
243 +--------------------------------------------------------- */
245 static void add_item(struct afb_config *config, int kind, char *value)
247 struct afb_config_item *item = malloc(sizeof *item);
249 ERROR("out of memory");
254 item->previous = config->items;
255 config->items = item;
258 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
260 char* programName = argv [0];
264 struct option *gnuOptions;
266 // ------------------ Process Command Line -----------------------
268 // if no argument print help and return
270 printHelp(stderr, programName);
274 // build GNU getopt info from cliOptions
275 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
276 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
277 for (ind=0; ind < nbcmd;ind++) {
278 gnuOptions [ind].name = cliOptions[ind].name;
279 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
280 gnuOptions [ind].flag = 0;
281 gnuOptions [ind].val = cliOptions[ind].val;
284 // get all options from command line
285 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
295 if (optarg == 0) goto needValueForOption;
296 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
300 if (optarg == 0) goto needValueForOption;
301 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
304 case SET_CNTXTIMEOUT:
305 if (optarg == 0) goto needValueForOption;
306 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
310 if (optarg == 0) goto needValueForOption;
311 config->rootdir = optarg;
312 INFO("Forcing Rootdir=%s",config->rootdir);
316 if (optarg == 0) goto needValueForOption;
317 config->rootbase = optarg;
318 INFO("Forcing Rootbase=%s",config->rootbase);
322 if (optarg == 0) goto needValueForOption;
323 config->rootapi = optarg;
324 INFO("Forcing Rootapi=%s",config->rootapi);
328 if (optarg == 0) goto needValueForOption;
329 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
330 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
331 if (optarg == NULL) {
332 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
334 config->aliasdir[config->aliascount].path = optarg;
335 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
336 config->aliascount++;
339 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
344 if (optarg == 0) goto needValueForOption;
345 config->token = optarg;
349 if (optarg == 0) goto needValueForOption;
350 config->ldpaths = optarg;
353 case SET_SESSION_DIR:
354 if (optarg == 0) goto needValueForOption;
355 config->sessiondir = optarg;
358 case SET_CACHE_TIMEOUT:
359 if (optarg == 0) goto needValueForOption;
360 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
364 if (optarg == 0) goto needValueForOption;
365 if (!sscanf (optarg, "%d", &config->nbSessionMax)) goto notAnInteger;
369 if (optarg != 0) goto noValueForOption;
370 config->background = 0;
374 if (optarg != 0) goto noValueForOption;
375 config->background = 1;
379 if (optarg == 0) goto needValueForOption;
380 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
381 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
382 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
387 if (optarg == 0) goto needValueForOption;
388 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
396 if (optarg == 0) goto needValueForOption;
397 add_item(config, optc, optarg);
400 case DISPLAY_VERSION:
401 if (optarg != 0) goto noValueForOption;
402 printVersion(stdout);
407 printHelp(stdout, programName);
413 config_set_default (config);
418 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
419 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
423 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
424 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
428 ERROR("AFB-daemon option [--%s] don't take value"
429 ,gnuOptions[optionIndex].name);
433 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
434 ,gnuOptions[optionIndex].name);
438 /*----------------------------------------------------------
440 | try to close everything before leaving
441 +--------------------------------------------------------- */
442 static void closeSession (int status, void *data) {
443 /* struct afb_config *config = data; */
446 /*----------------------------------------------------------
448 | set the process in background
449 +--------------------------------------------------------- */
450 static void daemonize(struct afb_config *config)
455 // open /dev/console to redirect output messAFBes
456 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
458 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
462 // fork process when running background mode
465 // if fail nothing much to do
467 ERROR("AFB-daemon Failed to fork son process");
471 // if in father process, just leave
472 if (pid != 0) _exit (0);
474 // son process get all data in standalone mode
475 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
477 // redirect default I/O on console
478 close (2); dup(consoleFD); // redirect stderr
479 close (1); dup(consoleFD); // redirect stdout
480 close (0); // no need for stdin
484 setsid(); // allow father process to fully exit
485 sleep (2); // allow main to leave and release port
489 /*---------------------------------------------------------
491 | Handles the HTTP server
492 +--------------------------------------------------------- */
493 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
497 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
500 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
503 for (idx = 0; idx < config->aliascount; idx++)
504 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0, 0))
507 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10, 1))
510 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
516 static struct afb_hsrv *start_http_server(struct afb_config * config)
519 struct afb_hsrv *hsrv;
521 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
522 ERROR("unable to set the tmp directory");
526 hsrv = afb_hsrv_create();
528 ERROR("memory allocation failure");
532 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
533 || !init_http_server(hsrv, config)) {
534 ERROR("initialisation of httpd failed");
539 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
540 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
542 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
544 ERROR("starting of httpd failed");
552 static void start_items(struct afb_config_item *item)
555 /* keeps the order */
556 start_items(item->previous);
559 if (afb_api_dbus_add_client(item->value) < 0) {
560 ERROR("can't start the afb-dbus client of path %s",item->value);
565 if (afb_api_dbus_add_server(item->value) < 0) {
566 ERROR("can't start the afb-dbus service of path %s",item->value);
571 if (afb_api_ws_add_client(item->value) < 0) {
572 ERROR("can't start the afb-websocket client of path %s",item->value);
577 if (afb_api_ws_add_server(item->value) < 0) {
578 ERROR("can't start the afb-websocket service of path %s",item->value);
583 if (afb_api_so_add_binding(item->value) < 0) {
584 ERROR("can't start the binding of path %s",item->value);
589 ERROR("unexpected internal error");
597 /*---------------------------------------------------------
599 | Parse option and launch action
600 +--------------------------------------------------------- */
602 int main(int argc, char *argv[]) {
603 struct afb_hsrv *hsrv;
604 struct afb_config *config;
605 struct sd_event *eventloop;
607 LOGAUTH("afb-daemon");
609 // ------------- Build session handler & init config -------
610 config = calloc (1, sizeof (struct afb_config));
612 on_exit(closeSession, config);
613 parse_arguments(argc, argv, config);
615 // ------------------ sanity check ----------------------------------------
616 if (config->httpdPort <= 0) {
617 ERROR("no port is defined");
621 afb_api_so_set_timeout(config->apiTimeout);
622 if (config->ldpaths) {
623 if (afb_api_so_add_pathset(config->ldpaths) < 0) {
624 ERROR("initialisation of bindings within %s failed", config->ldpaths);
629 start_items(config->items);
630 config->items = NULL;
632 ctxStoreInit(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
633 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
634 ERROR("initialisation of cookies failed");
638 if (afb_sig_handler_init() < 0) {
639 ERROR("main fail to initialise signal handlers");
643 // let's run this program with a low priority
646 // ------------------ Finaly Process Commands -----------------------------
647 // let's not take the risk to run as ROOT
648 //if (getuid() == 0) goto errorNoRoot;
650 DEBUG("Init config done");
652 // --------- run -----------
653 if (config->background) {
654 // --------- in background mode -----------
655 INFO("entering background mode");
658 // ---- in foreground mode --------------------
659 INFO("entering foreground mode");
662 hsrv = start_http_server(config);
666 /* start the services */
667 if (afb_apis_start_all_services(1) < 0)
670 if (config->readyfd != 0) {
671 static const char readystr[] = "READY=1";
672 write(config->readyfd, readystr, sizeof(readystr) - 1);
673 close(config->readyfd);
677 eventloop = afb_common_get_event_loop();
679 sd_event_run(eventloop, 30000000);
681 WARNING("hoops returned from infinite loop [report bug]");