2 * Copyright (C) 2015, 2016, 2017 "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, 2017 \"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->rootbase == NULL)
230 config->rootbase = "/opa";
232 if (config->rootapi == NULL)
233 config->rootapi = "/api";
235 if (config->ldpaths == NULL)
236 config->ldpaths = BINDING_INSTALL_DIR;
238 // if no session dir create a default path from rootdir
239 if (config->sessiondir == NULL) {
240 config->sessiondir = malloc (512);
241 strncpy (config->sessiondir, config->rootdir, 512);
242 strncat (config->sessiondir, "/sessions",512);
245 // if no config dir create a default path from sessiondir
246 if (config->console == NULL) {
247 config->console = malloc (512);
248 strncpy (config->console, config->sessiondir, 512);
249 strncat (config->console, "/AFB-console.out",512);
254 /*---------------------------------------------------------
256 | Parse option and launch action
257 +--------------------------------------------------------- */
259 static void add_item(struct afb_config *config, int kind, char *value)
261 struct afb_config_item *item = malloc(sizeof *item);
263 ERROR("out of memory");
268 item->previous = config->items;
269 config->items = item;
272 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
274 char* programName = argv [0];
278 struct option *gnuOptions;
280 // ------------------ Process Command Line -----------------------
282 // if no argument print help and return
284 printHelp(stderr, programName);
288 // build GNU getopt info from cliOptions
289 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
290 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
291 for (ind=0; ind < nbcmd;ind++) {
292 gnuOptions [ind].name = cliOptions[ind].name;
293 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
294 gnuOptions [ind].flag = 0;
295 gnuOptions [ind].val = cliOptions[ind].val;
298 // get all options from command line
299 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
309 if (optarg == 0) goto needValueForOption;
310 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
314 if (optarg == 0) goto needValueForOption;
315 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
318 case SET_CNTXTIMEOUT:
319 if (optarg == 0) goto needValueForOption;
320 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
324 if (optarg == 0) goto needValueForOption;
325 config->rootdir = optarg;
326 INFO("Forcing Rootdir=%s",config->rootdir);
330 if (optarg == 0) goto needValueForOption;
331 config->roothttp = optarg;
332 INFO("Forcing Root HTTP=%s",config->roothttp);
336 if (optarg == 0) goto needValueForOption;
337 config->rootbase = optarg;
338 INFO("Forcing Rootbase=%s",config->rootbase);
342 if (optarg == 0) goto needValueForOption;
343 config->rootapi = optarg;
344 INFO("Forcing Rootapi=%s",config->rootapi);
348 if (optarg == 0) goto needValueForOption;
349 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
350 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
351 if (optarg == NULL) {
352 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
354 config->aliasdir[config->aliascount].path = optarg;
355 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
356 config->aliascount++;
359 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
364 if (optarg == 0) goto needValueForOption;
365 config->token = optarg;
369 if (optarg == 0) goto needValueForOption;
370 config->ldpaths = optarg;
373 case SET_SESSION_DIR:
374 if (optarg == 0) goto needValueForOption;
375 config->sessiondir = optarg;
378 case SET_CACHE_TIMEOUT:
379 if (optarg == 0) goto needValueForOption;
380 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
384 if (optarg == 0) goto needValueForOption;
385 if (!sscanf (optarg, "%d", &config->nbSessionMax)) goto notAnInteger;
389 if (optarg != 0) goto noValueForOption;
390 config->background = 0;
394 if (optarg != 0) goto noValueForOption;
395 config->background = 1;
399 if (optarg == 0) goto needValueForOption;
400 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
401 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
402 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
407 if (optarg == 0) goto needValueForOption;
408 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
416 if (optarg == 0) goto needValueForOption;
417 add_item(config, optc, optarg);
421 if (optarg == 0) goto needValueForOption;
422 if (!strcmp(optarg, "no")) config->tracereq = TRACEREQ_NO;
423 else if (!strcmp(optarg, "common")) config->tracereq = TRACEREQ_COMMON;
424 else if (!strcmp(optarg, "extra")) config->tracereq = TRACEREQ_EXTRA;
425 else if (!strcmp(optarg, "all")) config->tracereq = TRACEREQ_ALL;
429 case DISPLAY_VERSION:
430 if (optarg != 0) goto noValueForOption;
431 printVersion(stdout);
436 printHelp(stdout, programName);
442 config_set_default (config);
447 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
448 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
452 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
453 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
457 ERROR("AFB-daemon option [--%s] don't take value"
458 ,gnuOptions[optionIndex].name);
462 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
463 ,gnuOptions[optionIndex].name);
467 /*----------------------------------------------------------
469 | try to close everything before leaving
470 +--------------------------------------------------------- */
471 static void closeSession (int status, void *data) {
472 /* struct afb_config *config = data; */
475 /*----------------------------------------------------------
477 | set the process in background
478 +--------------------------------------------------------- */
479 static void daemonize(struct afb_config *config)
484 // open /dev/console to redirect output messAFBes
485 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
487 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
491 // fork process when running background mode
494 // if fail nothing much to do
496 ERROR("AFB-daemon Failed to fork son process");
500 // if in father process, just leave
501 if (pid != 0) _exit (0);
503 // son process get all data in standalone mode
504 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
506 // redirect default I/O on console
507 close (2); dup(consoleFD); // redirect stderr
508 close (1); dup(consoleFD); // redirect stdout
509 close (0); // no need for stdin
513 setsid(); // allow father process to fully exit
514 sleep (2); // allow main to leave and release port
518 /*---------------------------------------------------------
520 | Handles the HTTP server
521 +--------------------------------------------------------- */
522 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
526 dfd = afb_common_rootdir_get_fd();
528 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
531 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
534 for (idx = 0; idx < config->aliascount; idx++)
535 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, dfd, config->aliasdir[idx].path, 0, 0))
538 if (config->roothttp != NULL) {
539 if (!afb_hsrv_add_alias(hsrv, "", dfd, config->roothttp, -10, 1))
543 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
549 static struct afb_hsrv *start_http_server(struct afb_config * config)
552 struct afb_hsrv *hsrv;
554 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
555 ERROR("unable to set the tmp directory");
559 hsrv = afb_hsrv_create();
561 ERROR("memory allocation failure");
565 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
566 || !init_http_server(hsrv, config)) {
567 ERROR("initialisation of httpd failed");
572 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
573 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
575 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
577 ERROR("starting of httpd failed");
585 static void start_items(struct afb_config_item *item)
588 /* keeps the order */
589 start_items(item->previous);
592 if (afb_api_dbus_add_client(item->value) < 0) {
593 ERROR("can't start the afb-dbus client of path %s",item->value);
598 if (afb_api_dbus_add_server(item->value) < 0) {
599 ERROR("can't start the afb-dbus service of path %s",item->value);
604 if (afb_api_ws_add_client(item->value) < 0) {
605 ERROR("can't start the afb-websocket client of path %s",item->value);
610 if (afb_api_ws_add_server(item->value) < 0) {
611 ERROR("can't start the afb-websocket service of path %s",item->value);
616 if (afb_api_so_add_binding(item->value) < 0) {
617 ERROR("can't start the binding of path %s",item->value);
622 ERROR("unexpected internal error");
630 /*---------------------------------------------------------
632 | Parse option and launch action
633 +--------------------------------------------------------- */
635 int main(int argc, char *argv[]) {
636 struct afb_hsrv *hsrv;
637 struct afb_config *config;
638 struct sd_event *eventloop;
640 LOGAUTH("afb-daemon");
642 // ------------- Build session handler & init config -------
643 config = calloc (1, sizeof (struct afb_config));
645 on_exit(closeSession, config);
646 parse_arguments(argc, argv, config);
648 // ------------------ sanity check ----------------------------------------
649 if (config->httpdPort <= 0) {
650 ERROR("no port is defined");
654 afb_api_so_set_timeout(config->apiTimeout);
655 if (config->ldpaths) {
656 if (afb_api_so_add_pathset(config->ldpaths) < 0) {
657 ERROR("initialisation of bindings within %s failed", config->ldpaths);
662 start_items(config->items);
663 config->items = NULL;
665 ctxStoreInit(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
666 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
667 ERROR("initialisation of cookies failed");
671 if (afb_sig_handler_init() < 0) {
672 ERROR("failed to initialise signal handlers");
676 if (afb_common_rootdir_set(config->rootdir) < 0) {
677 ERROR("failed to set common root directory");
681 if (afb_thread_init(3, 1, 20) < 0) {
682 ERROR("failed to initialise threading");
686 // let's run this program with a low priority
689 // ------------------ Finaly Process Commands -----------------------------
690 // let's not take the risk to run as ROOT
691 //if (getuid() == 0) goto errorNoRoot;
693 DEBUG("Init config done");
695 // --------- run -----------
696 if (config->background) {
697 // --------- in background mode -----------
698 INFO("entering background mode");
701 // ---- in foreground mode --------------------
702 INFO("entering foreground mode");
705 /* ignore any SIGPIPE */
706 signal(SIGPIPE, SIG_IGN);
708 /* install trace of requests */
709 switch(config->tracereq) {
713 case TRACEREQ_COMMON:
714 afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_common, NULL, NULL);
717 afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_extra, NULL, NULL);
720 afb_hook_req_create(NULL, NULL, NULL, afb_hook_flags_req_all, NULL, NULL);
724 /* start the HTTP server */
725 hsrv = start_http_server(config);
729 /* start the services */
730 if (afb_apis_start_all_services(1) < 0)
733 if (config->readyfd != 0) {
734 static const char readystr[] = "READY=1";
735 write(config->readyfd, readystr, sizeof(readystr) - 1);
736 close(config->readyfd);
740 eventloop = afb_common_get_event_loop();
742 sd_event_run(eventloop, 30000000);
744 WARNING("hoops returned from infinite loop [report bug]");