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"
42 #include "afb-thread.h"
45 #include "afb-common.h"
48 #include <afb/afb-binding.h>
50 #if !defined(BINDING_INSTALL_DIR)
51 #error "you should define BINDING_INSTALL_DIR"
55 #define TRACEREQ_COMMON 1
56 #define TRACEREQ_EXTRA 2
57 #define TRACEREQ_ALL 3
59 #define AFB_VERSION "0.5"
61 // Define command line option
63 #define SET_BACKGROUND 2
64 #define SET_FORGROUND 3
66 #define SET_TCP_PORT 5
67 #define SET_ROOT_DIR 6
68 #define SET_ROOT_BASE 7
69 #define SET_ROOT_API 8
72 #define SET_CACHE_TIMEOUT 10
73 #define SET_SESSION_DIR 11
75 #define SET_AUTH_TOKEN 12
77 #define SET_APITIMEOUT 14
78 #define SET_CNTXTIMEOUT 15
80 #define DISPLAY_VERSION 16
81 #define DISPLAY_HELP 17
84 #define SET_READYFD 19
86 #define DBUS_CLIENT 20
87 #define DBUS_SERVICE 21
90 #define SET_SESSIONMAX 23
95 #define SET_ROOT_HTTP 26
97 #define SET_TRACEREQ 27
99 // Command line structure hold cli --command + help text
101 int val; // command number within application
102 int has_arg; // command number within application
103 char *name; // command as used in --xxxx cli
104 char *help; // help text
109 static AFB_options cliOptions [] = {
110 {SET_VERBOSE ,0,"verbose" , "Verbose Mode, repeat to increase verbosity"},
112 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
113 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
115 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
116 {SET_ROOT_DIR ,1,"rootdir" , "Root Directory [default $HOME/.AFB]"},
117 {SET_ROOT_HTTP ,1,"roothttp" , "HTTP Root Directory [default rootdir]"},
118 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
119 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
120 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
122 {SET_APITIMEOUT ,1,"apitimeout" , "Binding API timeout in seconds [default 10]"},
123 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
124 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600]"},
126 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
128 {SET_LDPATH ,1,"ldpaths" , "Load bindingss from dir1:dir2:... [default = "BINDING_INSTALL_DIR"]"},
129 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
131 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
132 {DISPLAY_HELP ,0,"help" , "Display this help"},
134 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
135 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
137 {DBUS_CLIENT ,1,"dbus-client" , "bind to an afb service through dbus"},
138 {DBUS_SERVICE ,1,"dbus-server" , "provides an afb service through dbus"},
139 {WS_CLIENT ,1,"ws-client" , "bind to an afb service through websocket"},
140 {WS_SERVICE ,1,"ws-server" , "provides an afb service through websockets"},
141 {SO_BINDING ,1,"binding" , "load the binding of path"},
143 {SET_SESSIONMAX ,1,"session-max" , "max count of session simultaneously [default 10]"},
145 {SET_TRACEREQ ,1,"tracereq" , "log the requests: no, common, extra, all"},
150 /*----------------------------------------------------------
152 | print version and copyright
153 +--------------------------------------------------------- */
154 static void printVersion (FILE *file)
156 fprintf(file, "\n----------------------------------------- \n");
157 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
158 fprintf(file, " \n");
159 fprintf(file, " Copyright (C) 2015, 2016 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
160 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
161 fprintf(file, " Licence Apache 2\n\n");
165 /*----------------------------------------------------------
167 | print information from long option array
168 +--------------------------------------------------------- */
170 static void printHelp(FILE *file, const char *name)
175 fprintf (file, "%s:\nallowed options\n", name);
176 for (ind=0; cliOptions [ind].name != NULL;ind++)
179 if (cliOptions [ind].has_arg == 0 )
181 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
183 sprintf(command, "%s=xxxx", cliOptions [ind].name);
184 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
187 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n", name);
190 // load config from disk and merge with CLI option
191 static void config_set_default (struct afb_config * config)
194 if (config->httpdPort == 0)
195 config->httpdPort = 1234;
197 // default binding API timeout
198 if (config->apiTimeout == 0)
199 config->apiTimeout = DEFLT_API_TIMEOUT;
201 // default AUTH_TOKEN
202 if (config->token == NULL)
203 config->token = DEFLT_AUTH_TOKEN;
205 // cache timeout default one hour
206 if (config->cacheTimeout == 0)
207 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
209 // cache timeout default one hour
210 if (config->cntxTimeout == 0)
211 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
213 // max count of sessions
214 if (config->nbSessionMax == 0)
215 config->nbSessionMax = CTX_NBCLIENTS;
217 if (config->rootdir == NULL) {
218 config->rootdir = getenv("AFBDIR");
219 if (config->rootdir == NULL) {
220 config->rootdir = malloc (512);
221 strncpy (config->rootdir, getenv("HOME"),512);
222 strncat (config->rootdir, "/.AFB",512);
224 // if directory does not exist createit
225 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
228 // if no Angular/HTML5 rootbase let's try '/' as default
229 if (config->roothttp == NULL)
230 config->roothttp = ".";
232 if (config->rootbase == NULL)
233 config->rootbase = "/opa";
235 if (config->rootapi == NULL)
236 config->rootapi = "/api";
238 if (config->ldpaths == NULL)
239 config->ldpaths = BINDING_INSTALL_DIR;
241 // if no session dir create a default path from rootdir
242 if (config->sessiondir == NULL) {
243 config->sessiondir = malloc (512);
244 strncpy (config->sessiondir, config->rootdir, 512);
245 strncat (config->sessiondir, "/sessions",512);
248 // if no config dir create a default path from sessiondir
249 if (config->console == NULL) {
250 config->console = malloc (512);
251 strncpy (config->console, config->sessiondir, 512);
252 strncat (config->console, "/AFB-console.out",512);
257 /*---------------------------------------------------------
259 | Parse option and launch action
260 +--------------------------------------------------------- */
262 static void add_item(struct afb_config *config, int kind, char *value)
264 struct afb_config_item *item = malloc(sizeof *item);
266 ERROR("out of memory");
271 item->previous = config->items;
272 config->items = item;
275 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
277 char* programName = argv [0];
281 struct option *gnuOptions;
283 // ------------------ Process Command Line -----------------------
285 // if no argument print help and return
287 printHelp(stderr, programName);
291 // build GNU getopt info from cliOptions
292 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
293 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
294 for (ind=0; ind < nbcmd;ind++) {
295 gnuOptions [ind].name = cliOptions[ind].name;
296 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
297 gnuOptions [ind].flag = 0;
298 gnuOptions [ind].val = cliOptions[ind].val;
301 // get all options from command line
302 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
312 if (optarg == 0) goto needValueForOption;
313 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
317 if (optarg == 0) goto needValueForOption;
318 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
321 case SET_CNTXTIMEOUT:
322 if (optarg == 0) goto needValueForOption;
323 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
327 if (optarg == 0) goto needValueForOption;
328 config->rootdir = optarg;
329 INFO("Forcing Rootdir=%s",config->rootdir);
333 if (optarg == 0) goto needValueForOption;
334 config->roothttp = optarg;
335 INFO("Forcing Root HTTP=%s",config->roothttp);
339 if (optarg == 0) goto needValueForOption;
340 config->rootbase = optarg;
341 INFO("Forcing Rootbase=%s",config->rootbase);
345 if (optarg == 0) goto needValueForOption;
346 config->rootapi = optarg;
347 INFO("Forcing Rootapi=%s",config->rootapi);
351 if (optarg == 0) goto needValueForOption;
352 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
353 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
354 if (optarg == NULL) {
355 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
357 config->aliasdir[config->aliascount].path = optarg;
358 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
359 config->aliascount++;
362 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
367 if (optarg == 0) goto needValueForOption;
368 config->token = optarg;
372 if (optarg == 0) goto needValueForOption;
373 config->ldpaths = optarg;
376 case SET_SESSION_DIR:
377 if (optarg == 0) goto needValueForOption;
378 config->sessiondir = optarg;
381 case SET_CACHE_TIMEOUT:
382 if (optarg == 0) goto needValueForOption;
383 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
387 if (optarg == 0) goto needValueForOption;
388 if (!sscanf (optarg, "%d", &config->nbSessionMax)) goto notAnInteger;
392 if (optarg != 0) goto noValueForOption;
393 config->background = 0;
397 if (optarg != 0) goto noValueForOption;
398 config->background = 1;
402 if (optarg == 0) goto needValueForOption;
403 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
404 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
405 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
410 if (optarg == 0) goto needValueForOption;
411 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
419 if (optarg == 0) goto needValueForOption;
420 add_item(config, optc, optarg);
424 if (optarg == 0) goto needValueForOption;
425 if (!strcmp(optarg, "no")) config->tracereq = TRACEREQ_NO;
426 else if (!strcmp(optarg, "common")) config->tracereq = TRACEREQ_COMMON;
427 else if (!strcmp(optarg, "extra")) config->tracereq = TRACEREQ_EXTRA;
428 else if (!strcmp(optarg, "all")) config->tracereq = TRACEREQ_ALL;
432 case DISPLAY_VERSION:
433 if (optarg != 0) goto noValueForOption;
434 printVersion(stdout);
439 printHelp(stdout, programName);
445 config_set_default (config);
450 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
451 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
455 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
456 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
460 ERROR("AFB-daemon option [--%s] don't take value"
461 ,gnuOptions[optionIndex].name);
465 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
466 ,gnuOptions[optionIndex].name);
470 /*----------------------------------------------------------
472 | try to close everything before leaving
473 +--------------------------------------------------------- */
474 static void closeSession (int status, void *data) {
475 /* struct afb_config *config = data; */
478 /*----------------------------------------------------------
480 | set the process in background
481 +--------------------------------------------------------- */
482 static void daemonize(struct afb_config *config)
487 // open /dev/console to redirect output messAFBes
488 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
490 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
494 // fork process when running background mode
497 // if fail nothing much to do
499 ERROR("AFB-daemon Failed to fork son process");
503 // if in father process, just leave
504 if (pid != 0) _exit (0);
506 // son process get all data in standalone mode
507 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
509 // redirect default I/O on console
510 close (2); dup(consoleFD); // redirect stderr
511 close (1); dup(consoleFD); // redirect stdout
512 close (0); // no need for stdin
516 setsid(); // allow father process to fully exit
517 sleep (2); // allow main to leave and release port
521 /*---------------------------------------------------------
523 | Handles the HTTP server
524 +--------------------------------------------------------- */
525 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
529 dfd = afb_common_rootdir_get_fd();
531 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
534 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
537 for (idx = 0; idx < config->aliascount; idx++)
538 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, dfd, config->aliasdir[idx].path, 0, 0))
541 if (!afb_hsrv_add_alias(hsrv, "", dfd, config->roothttp, -10, 1))
544 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
550 static struct afb_hsrv *start_http_server(struct afb_config * config)
553 struct afb_hsrv *hsrv;
555 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
556 ERROR("unable to set the tmp directory");
560 hsrv = afb_hsrv_create();
562 ERROR("memory allocation failure");
566 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
567 || !init_http_server(hsrv, config)) {
568 ERROR("initialisation of httpd failed");
573 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
574 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
576 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
578 ERROR("starting of httpd failed");
586 static void start_items(struct afb_config_item *item)
589 /* keeps the order */
590 start_items(item->previous);
593 if (afb_api_dbus_add_client(item->value) < 0) {
594 ERROR("can't start the afb-dbus client of path %s",item->value);
599 if (afb_api_dbus_add_server(item->value) < 0) {
600 ERROR("can't start the afb-dbus service of path %s",item->value);
605 if (afb_api_ws_add_client(item->value) < 0) {
606 ERROR("can't start the afb-websocket client of path %s",item->value);
611 if (afb_api_ws_add_server(item->value) < 0) {
612 ERROR("can't start the afb-websocket service of path %s",item->value);
617 if (afb_api_so_add_binding(item->value) < 0) {
618 ERROR("can't start the binding of path %s",item->value);
623 ERROR("unexpected internal error");
631 /*---------------------------------------------------------
633 | Parse option and launch action
634 +--------------------------------------------------------- */
636 int main(int argc, char *argv[]) {
637 struct afb_hsrv *hsrv;
638 struct afb_config *config;
639 struct sd_event *eventloop;
641 LOGAUTH("afb-daemon");
643 // ------------- Build session handler & init config -------
644 config = calloc (1, sizeof (struct afb_config));
646 on_exit(closeSession, config);
647 parse_arguments(argc, argv, config);
649 // ------------------ sanity check ----------------------------------------
650 if (config->httpdPort <= 0) {
651 ERROR("no port is defined");
655 afb_api_so_set_timeout(config->apiTimeout);
656 if (config->ldpaths) {
657 if (afb_api_so_add_pathset(config->ldpaths) < 0) {
658 ERROR("initialisation of bindings within %s failed", config->ldpaths);
663 start_items(config->items);
664 config->items = NULL;
666 ctxStoreInit(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
667 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
668 ERROR("initialisation of cookies failed");
672 if (afb_sig_handler_init() < 0) {
673 ERROR("failed to initialise signal handlers");
677 if (afb_common_rootdir_set(config->rootdir) < 0) {
678 ERROR("failed to set common root directory");
682 if (afb_thread_init(3, 1, 20) < 0) {
683 ERROR("failed to initialise threading");
687 // let's run this program with a low priority
690 // ------------------ Finaly Process Commands -----------------------------
691 // let's not take the risk to run as ROOT
692 //if (getuid() == 0) goto errorNoRoot;
694 DEBUG("Init config done");
696 // --------- run -----------
697 if (config->background) {
698 // --------- in background mode -----------
699 INFO("entering background mode");
702 // ---- in foreground mode --------------------
703 INFO("entering foreground mode");
706 /* ignore any SIGPIPE */
707 signal(SIGPIPE, SIG_IGN);
709 /* install trace of requests */
710 switch(config->tracereq) {
714 case TRACEREQ_COMMON:
715 afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_common, NULL, NULL);
718 afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_extra, NULL, NULL);
721 afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_all, NULL, NULL);
725 /* start the HTTP server */
726 hsrv = start_http_server(config);
730 /* start the services */
731 if (afb_apis_start_all_services(1) < 0)
734 if (config->readyfd != 0) {
735 static const char readystr[] = "READY=1";
736 write(config->readyfd, readystr, sizeof(readystr) - 1);
737 close(config->readyfd);
741 eventloop = afb_common_get_event_loop();
743 sd_event_run(eventloop, 30000000);
745 WARNING("hoops returned from infinite loop [report bug]");