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 #define SET_ROOT_HTTP 26
90 // Command line structure hold cli --command + help text
92 int val; // command number within application
93 int has_arg; // command number within application
94 char *name; // command as used in --xxxx cli
95 char *help; // help text
100 static AFB_options cliOptions [] = {
101 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
103 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
104 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
106 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
107 {SET_ROOT_DIR ,1,"rootdir" , "Root Directory [default $HOME/.AFB]"},
108 {SET_ROOT_HTTP ,1,"roothttp" , "HTTP Root Directory [default rootdir]"},
109 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
110 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
111 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
113 {SET_APITIMEOUT ,1,"apitimeout" , "Binding API timeout in seconds [default 10]"},
114 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
115 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600]"},
117 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
119 {SET_LDPATH ,1,"ldpaths" , "Load bindingss from dir1:dir2:... [default = "BINDING_INSTALL_DIR"]"},
120 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
122 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
123 {DISPLAY_HELP ,0,"help" , "Display this help"},
125 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
126 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
128 {DBUS_CLIENT ,1,"dbus-client" , "bind to an afb service through dbus"},
129 {DBUS_SERVICE ,1,"dbus-server" , "provides an afb service through dbus"},
130 {WS_CLIENT ,1,"ws-client" , "bind to an afb service through websocket"},
131 {WS_SERVICE ,1,"ws-server" , "provides an afb service through websockets"},
132 {SO_BINDING ,1,"binding" , "load the binding of path"},
134 {SET_SESSIONMAX ,1,"session-max" , "max count of session simultaneously [default 10]"},
139 /*----------------------------------------------------------
141 | print version and copyright
142 +--------------------------------------------------------- */
143 static void printVersion (FILE *file)
145 fprintf(file, "\n----------------------------------------- \n");
146 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
147 fprintf(file, " \n");
148 fprintf(file, " Copyright (C) 2015, 2016 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
149 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
150 fprintf(file, " Licence Apache 2\n\n");
154 /*----------------------------------------------------------
156 | print information from long option array
157 +--------------------------------------------------------- */
159 static void printHelp(FILE *file, const char *name)
164 fprintf (file, "%s:\nallowed options\n", name);
165 for (ind=0; cliOptions [ind].name != NULL;ind++)
168 if (cliOptions [ind].has_arg == 0 )
170 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
172 sprintf(command, "%s=xxxx", cliOptions [ind].name);
173 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
176 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n", name);
179 // load config from disk and merge with CLI option
180 static void config_set_default (struct afb_config * config)
183 if (config->httpdPort == 0)
184 config->httpdPort = 1234;
186 // default binding API timeout
187 if (config->apiTimeout == 0)
188 config->apiTimeout = DEFLT_API_TIMEOUT;
190 // default AUTH_TOKEN
191 if (config->token == NULL)
192 config->token = DEFLT_AUTH_TOKEN;
194 // cache timeout default one hour
195 if (config->cacheTimeout == 0)
196 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
198 // cache timeout default one hour
199 if (config->cntxTimeout == 0)
200 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
202 // max count of sessions
203 if (config->nbSessionMax == 0)
204 config->nbSessionMax = CTX_NBCLIENTS;
206 if (config->rootdir == NULL) {
207 config->rootdir = getenv("AFBDIR");
208 if (config->rootdir == NULL) {
209 config->rootdir = malloc (512);
210 strncpy (config->rootdir, getenv("HOME"),512);
211 strncat (config->rootdir, "/.AFB",512);
213 // if directory does not exist createit
214 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
217 // if no Angular/HTML5 rootbase let's try '/' as default
218 if (config->roothttp == NULL)
219 config->roothttp = ".";
221 if (config->rootbase == NULL)
222 config->rootbase = "/opa";
224 if (config->rootapi == NULL)
225 config->rootapi = "/api";
227 if (config->ldpaths == NULL)
228 config->ldpaths = BINDING_INSTALL_DIR;
230 // if no session dir create a default path from rootdir
231 if (config->sessiondir == NULL) {
232 config->sessiondir = malloc (512);
233 strncpy (config->sessiondir, config->rootdir, 512);
234 strncat (config->sessiondir, "/sessions",512);
237 // if no config dir create a default path from sessiondir
238 if (config->console == NULL) {
239 config->console = malloc (512);
240 strncpy (config->console, config->sessiondir, 512);
241 strncat (config->console, "/AFB-console.out",512);
246 /*---------------------------------------------------------
248 | Parse option and launch action
249 +--------------------------------------------------------- */
251 static void add_item(struct afb_config *config, int kind, char *value)
253 struct afb_config_item *item = malloc(sizeof *item);
255 ERROR("out of memory");
260 item->previous = config->items;
261 config->items = item;
264 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
266 char* programName = argv [0];
270 struct option *gnuOptions;
272 // ------------------ Process Command Line -----------------------
274 // if no argument print help and return
276 printHelp(stderr, programName);
280 // build GNU getopt info from cliOptions
281 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
282 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
283 for (ind=0; ind < nbcmd;ind++) {
284 gnuOptions [ind].name = cliOptions[ind].name;
285 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
286 gnuOptions [ind].flag = 0;
287 gnuOptions [ind].val = cliOptions[ind].val;
290 // get all options from command line
291 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
301 if (optarg == 0) goto needValueForOption;
302 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
306 if (optarg == 0) goto needValueForOption;
307 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
310 case SET_CNTXTIMEOUT:
311 if (optarg == 0) goto needValueForOption;
312 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
316 if (optarg == 0) goto needValueForOption;
317 config->rootdir = optarg;
318 INFO("Forcing Rootdir=%s",config->rootdir);
322 if (optarg == 0) goto needValueForOption;
323 config->roothttp = optarg;
324 INFO("Forcing Root HTTP=%s",config->roothttp);
328 if (optarg == 0) goto needValueForOption;
329 config->rootbase = optarg;
330 INFO("Forcing Rootbase=%s",config->rootbase);
334 if (optarg == 0) goto needValueForOption;
335 config->rootapi = optarg;
336 INFO("Forcing Rootapi=%s",config->rootapi);
340 if (optarg == 0) goto needValueForOption;
341 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
342 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
343 if (optarg == NULL) {
344 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
346 config->aliasdir[config->aliascount].path = optarg;
347 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
348 config->aliascount++;
351 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
356 if (optarg == 0) goto needValueForOption;
357 config->token = optarg;
361 if (optarg == 0) goto needValueForOption;
362 config->ldpaths = optarg;
365 case SET_SESSION_DIR:
366 if (optarg == 0) goto needValueForOption;
367 config->sessiondir = optarg;
370 case SET_CACHE_TIMEOUT:
371 if (optarg == 0) goto needValueForOption;
372 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
376 if (optarg == 0) goto needValueForOption;
377 if (!sscanf (optarg, "%d", &config->nbSessionMax)) goto notAnInteger;
381 if (optarg != 0) goto noValueForOption;
382 config->background = 0;
386 if (optarg != 0) goto noValueForOption;
387 config->background = 1;
391 if (optarg == 0) goto needValueForOption;
392 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
393 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
394 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
399 if (optarg == 0) goto needValueForOption;
400 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
408 if (optarg == 0) goto needValueForOption;
409 add_item(config, optc, optarg);
412 case DISPLAY_VERSION:
413 if (optarg != 0) goto noValueForOption;
414 printVersion(stdout);
419 printHelp(stdout, programName);
425 config_set_default (config);
430 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
431 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
435 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
436 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
440 ERROR("AFB-daemon option [--%s] don't take value"
441 ,gnuOptions[optionIndex].name);
445 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
446 ,gnuOptions[optionIndex].name);
450 /*----------------------------------------------------------
452 | try to close everything before leaving
453 +--------------------------------------------------------- */
454 static void closeSession (int status, void *data) {
455 /* struct afb_config *config = data; */
458 /*----------------------------------------------------------
460 | set the process in background
461 +--------------------------------------------------------- */
462 static void daemonize(struct afb_config *config)
467 // open /dev/console to redirect output messAFBes
468 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
470 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
474 // fork process when running background mode
477 // if fail nothing much to do
479 ERROR("AFB-daemon Failed to fork son process");
483 // if in father process, just leave
484 if (pid != 0) _exit (0);
486 // son process get all data in standalone mode
487 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
489 // redirect default I/O on console
490 close (2); dup(consoleFD); // redirect stderr
491 close (1); dup(consoleFD); // redirect stdout
492 close (0); // no need for stdin
496 setsid(); // allow father process to fully exit
497 sleep (2); // allow main to leave and release port
501 /*---------------------------------------------------------
503 | Handles the HTTP server
504 +--------------------------------------------------------- */
505 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
509 dfd = afb_common_rootdir_get_fd();
511 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
514 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
517 for (idx = 0; idx < config->aliascount; idx++)
518 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, dfd, config->aliasdir[idx].path, 0, 0))
521 if (!afb_hsrv_add_alias(hsrv, "", dfd, config->roothttp, -10, 1))
524 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
530 static struct afb_hsrv *start_http_server(struct afb_config * config)
533 struct afb_hsrv *hsrv;
535 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
536 ERROR("unable to set the tmp directory");
540 hsrv = afb_hsrv_create();
542 ERROR("memory allocation failure");
546 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
547 || !init_http_server(hsrv, config)) {
548 ERROR("initialisation of httpd failed");
553 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
554 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
556 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
558 ERROR("starting of httpd failed");
566 static void start_items(struct afb_config_item *item)
569 /* keeps the order */
570 start_items(item->previous);
573 if (afb_api_dbus_add_client(item->value) < 0) {
574 ERROR("can't start the afb-dbus client of path %s",item->value);
579 if (afb_api_dbus_add_server(item->value) < 0) {
580 ERROR("can't start the afb-dbus service of path %s",item->value);
585 if (afb_api_ws_add_client(item->value) < 0) {
586 ERROR("can't start the afb-websocket client of path %s",item->value);
591 if (afb_api_ws_add_server(item->value) < 0) {
592 ERROR("can't start the afb-websocket service of path %s",item->value);
597 if (afb_api_so_add_binding(item->value) < 0) {
598 ERROR("can't start the binding of path %s",item->value);
603 ERROR("unexpected internal error");
611 /*---------------------------------------------------------
613 | Parse option and launch action
614 +--------------------------------------------------------- */
616 int main(int argc, char *argv[]) {
617 struct afb_hsrv *hsrv;
618 struct afb_config *config;
619 struct sd_event *eventloop;
621 LOGAUTH("afb-daemon");
623 // ------------- Build session handler & init config -------
624 config = calloc (1, sizeof (struct afb_config));
626 on_exit(closeSession, config);
627 parse_arguments(argc, argv, config);
629 // ------------------ sanity check ----------------------------------------
630 if (config->httpdPort <= 0) {
631 ERROR("no port is defined");
635 afb_api_so_set_timeout(config->apiTimeout);
636 if (config->ldpaths) {
637 if (afb_api_so_add_pathset(config->ldpaths) < 0) {
638 ERROR("initialisation of bindings within %s failed", config->ldpaths);
643 start_items(config->items);
644 config->items = NULL;
646 ctxStoreInit(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
647 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
648 ERROR("initialisation of cookies failed");
652 if (afb_sig_handler_init() < 0) {
653 ERROR("main fail to initialise signal handlers");
657 if (afb_common_rootdir_set(config->rootdir) < 0) {
658 ERROR("main fail to set common root directory");
662 // let's run this program with a low priority
665 // ------------------ Finaly Process Commands -----------------------------
666 // let's not take the risk to run as ROOT
667 //if (getuid() == 0) goto errorNoRoot;
669 DEBUG("Init config done");
671 // --------- run -----------
672 if (config->background) {
673 // --------- in background mode -----------
674 INFO("entering background mode");
677 // ---- in foreground mode --------------------
678 INFO("entering foreground mode");
681 /* start the HTTP server */
682 hsrv = start_http_server(config);
686 /* start the services */
687 if (afb_apis_start_all_services(1) < 0)
690 if (config->readyfd != 0) {
691 static const char readystr[] = "READY=1";
692 write(config->readyfd, readystr, sizeof(readystr) - 1);
693 close(config->readyfd);
697 eventloop = afb_common_get_event_loop();
699 sd_event_run(eventloop, 30000000);
701 WARNING("hoops returned from infinite loop [report bug]");