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"
47 #include <afb/afb-binding.h>
49 #if !defined(BINDING_INSTALL_DIR)
50 #error "you should define BINDING_INSTALL_DIR"
53 #define AFB_VERSION "0.5"
55 // Define command line option
57 #define SET_BACKGROUND 2
58 #define SET_FORGROUND 3
60 #define SET_TCP_PORT 5
61 #define SET_ROOT_DIR 6
62 #define SET_ROOT_BASE 7
63 #define SET_ROOT_API 8
66 #define SET_CACHE_TIMEOUT 10
67 #define SET_SESSION_DIR 11
69 #define SET_AUTH_TOKEN 12
71 #define SET_APITIMEOUT 14
72 #define SET_CNTXTIMEOUT 15
74 #define DISPLAY_VERSION 16
75 #define DISPLAY_HELP 17
78 #define SET_READYFD 19
80 #define DBUS_CLIENT 20
81 #define DBUS_SERVICE 21
84 #define SET_SESSIONMAX 23
89 #define SET_ROOT_HTTP 26
91 // Command line structure hold cli --command + help text
93 int val; // command number within application
94 int has_arg; // command number within application
95 char *name; // command as used in --xxxx cli
96 char *help; // help text
101 static AFB_options cliOptions [] = {
102 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
104 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
105 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
107 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
108 {SET_ROOT_DIR ,1,"rootdir" , "Root Directory [default $HOME/.AFB]"},
109 {SET_ROOT_HTTP ,1,"roothttp" , "HTTP Root Directory [default rootdir]"},
110 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
111 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
112 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
114 {SET_APITIMEOUT ,1,"apitimeout" , "Binding API timeout in seconds [default 10]"},
115 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
116 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600]"},
118 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
120 {SET_LDPATH ,1,"ldpaths" , "Load bindingss from dir1:dir2:... [default = "BINDING_INSTALL_DIR"]"},
121 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
123 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
124 {DISPLAY_HELP ,0,"help" , "Display this help"},
126 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
127 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
129 {DBUS_CLIENT ,1,"dbus-client" , "bind to an afb service through dbus"},
130 {DBUS_SERVICE ,1,"dbus-server" , "provides an afb service through dbus"},
131 {WS_CLIENT ,1,"ws-client" , "bind to an afb service through websocket"},
132 {WS_SERVICE ,1,"ws-server" , "provides an afb service through websockets"},
133 {SO_BINDING ,1,"binding" , "load the binding of path"},
135 {SET_SESSIONMAX ,1,"session-max" , "max count of session simultaneously [default 10]"},
140 /*----------------------------------------------------------
142 | print version and copyright
143 +--------------------------------------------------------- */
144 static void printVersion (FILE *file)
146 fprintf(file, "\n----------------------------------------- \n");
147 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
148 fprintf(file, " \n");
149 fprintf(file, " Copyright (C) 2015, 2016 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
150 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
151 fprintf(file, " Licence Apache 2\n\n");
155 /*----------------------------------------------------------
157 | print information from long option array
158 +--------------------------------------------------------- */
160 static void printHelp(FILE *file, const char *name)
165 fprintf (file, "%s:\nallowed options\n", name);
166 for (ind=0; cliOptions [ind].name != NULL;ind++)
169 if (cliOptions [ind].has_arg == 0 )
171 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
173 sprintf(command, "%s=xxxx", cliOptions [ind].name);
174 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
177 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n", name);
180 // load config from disk and merge with CLI option
181 static void config_set_default (struct afb_config * config)
184 if (config->httpdPort == 0)
185 config->httpdPort = 1234;
187 // default binding API timeout
188 if (config->apiTimeout == 0)
189 config->apiTimeout = DEFLT_API_TIMEOUT;
191 // default AUTH_TOKEN
192 if (config->token == NULL)
193 config->token = DEFLT_AUTH_TOKEN;
195 // cache timeout default one hour
196 if (config->cacheTimeout == 0)
197 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
199 // cache timeout default one hour
200 if (config->cntxTimeout == 0)
201 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
203 // max count of sessions
204 if (config->nbSessionMax == 0)
205 config->nbSessionMax = CTX_NBCLIENTS;
207 if (config->rootdir == NULL) {
208 config->rootdir = getenv("AFBDIR");
209 if (config->rootdir == NULL) {
210 config->rootdir = malloc (512);
211 strncpy (config->rootdir, getenv("HOME"),512);
212 strncat (config->rootdir, "/.AFB",512);
214 // if directory does not exist createit
215 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
218 // if no Angular/HTML5 rootbase let's try '/' as default
219 if (config->roothttp == NULL)
220 config->roothttp = ".";
222 if (config->rootbase == NULL)
223 config->rootbase = "/opa";
225 if (config->rootapi == NULL)
226 config->rootapi = "/api";
228 if (config->ldpaths == NULL)
229 config->ldpaths = BINDING_INSTALL_DIR;
231 // if no session dir create a default path from rootdir
232 if (config->sessiondir == NULL) {
233 config->sessiondir = malloc (512);
234 strncpy (config->sessiondir, config->rootdir, 512);
235 strncat (config->sessiondir, "/sessions",512);
238 // if no config dir create a default path from sessiondir
239 if (config->console == NULL) {
240 config->console = malloc (512);
241 strncpy (config->console, config->sessiondir, 512);
242 strncat (config->console, "/AFB-console.out",512);
247 /*---------------------------------------------------------
249 | Parse option and launch action
250 +--------------------------------------------------------- */
252 static void add_item(struct afb_config *config, int kind, char *value)
254 struct afb_config_item *item = malloc(sizeof *item);
256 ERROR("out of memory");
261 item->previous = config->items;
262 config->items = item;
265 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
267 char* programName = argv [0];
271 struct option *gnuOptions;
273 // ------------------ Process Command Line -----------------------
275 // if no argument print help and return
277 printHelp(stderr, programName);
281 // build GNU getopt info from cliOptions
282 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
283 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
284 for (ind=0; ind < nbcmd;ind++) {
285 gnuOptions [ind].name = cliOptions[ind].name;
286 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
287 gnuOptions [ind].flag = 0;
288 gnuOptions [ind].val = cliOptions[ind].val;
291 // get all options from command line
292 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
302 if (optarg == 0) goto needValueForOption;
303 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
307 if (optarg == 0) goto needValueForOption;
308 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
311 case SET_CNTXTIMEOUT:
312 if (optarg == 0) goto needValueForOption;
313 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
317 if (optarg == 0) goto needValueForOption;
318 config->rootdir = optarg;
319 INFO("Forcing Rootdir=%s",config->rootdir);
323 if (optarg == 0) goto needValueForOption;
324 config->roothttp = optarg;
325 INFO("Forcing Root HTTP=%s",config->roothttp);
329 if (optarg == 0) goto needValueForOption;
330 config->rootbase = optarg;
331 INFO("Forcing Rootbase=%s",config->rootbase);
335 if (optarg == 0) goto needValueForOption;
336 config->rootapi = optarg;
337 INFO("Forcing Rootapi=%s",config->rootapi);
341 if (optarg == 0) goto needValueForOption;
342 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
343 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
344 if (optarg == NULL) {
345 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
347 config->aliasdir[config->aliascount].path = optarg;
348 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
349 config->aliascount++;
352 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
357 if (optarg == 0) goto needValueForOption;
358 config->token = optarg;
362 if (optarg == 0) goto needValueForOption;
363 config->ldpaths = optarg;
366 case SET_SESSION_DIR:
367 if (optarg == 0) goto needValueForOption;
368 config->sessiondir = optarg;
371 case SET_CACHE_TIMEOUT:
372 if (optarg == 0) goto needValueForOption;
373 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
377 if (optarg == 0) goto needValueForOption;
378 if (!sscanf (optarg, "%d", &config->nbSessionMax)) goto notAnInteger;
382 if (optarg != 0) goto noValueForOption;
383 config->background = 0;
387 if (optarg != 0) goto noValueForOption;
388 config->background = 1;
392 if (optarg == 0) goto needValueForOption;
393 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
394 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
395 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
400 if (optarg == 0) goto needValueForOption;
401 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
409 if (optarg == 0) goto needValueForOption;
410 add_item(config, optc, optarg);
413 case DISPLAY_VERSION:
414 if (optarg != 0) goto noValueForOption;
415 printVersion(stdout);
420 printHelp(stdout, programName);
426 config_set_default (config);
431 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
432 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
436 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
437 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
441 ERROR("AFB-daemon option [--%s] don't take value"
442 ,gnuOptions[optionIndex].name);
446 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
447 ,gnuOptions[optionIndex].name);
451 /*----------------------------------------------------------
453 | try to close everything before leaving
454 +--------------------------------------------------------- */
455 static void closeSession (int status, void *data) {
456 /* struct afb_config *config = data; */
459 /*----------------------------------------------------------
461 | set the process in background
462 +--------------------------------------------------------- */
463 static void daemonize(struct afb_config *config)
468 // open /dev/console to redirect output messAFBes
469 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
471 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
475 // fork process when running background mode
478 // if fail nothing much to do
480 ERROR("AFB-daemon Failed to fork son process");
484 // if in father process, just leave
485 if (pid != 0) _exit (0);
487 // son process get all data in standalone mode
488 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
490 // redirect default I/O on console
491 close (2); dup(consoleFD); // redirect stderr
492 close (1); dup(consoleFD); // redirect stdout
493 close (0); // no need for stdin
497 setsid(); // allow father process to fully exit
498 sleep (2); // allow main to leave and release port
502 /*---------------------------------------------------------
504 | Handles the HTTP server
505 +--------------------------------------------------------- */
506 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
510 dfd = afb_common_rootdir_get_fd();
512 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
515 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
518 for (idx = 0; idx < config->aliascount; idx++)
519 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, dfd, config->aliasdir[idx].path, 0, 0))
522 if (!afb_hsrv_add_alias(hsrv, "", dfd, config->roothttp, -10, 1))
525 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
531 static struct afb_hsrv *start_http_server(struct afb_config * config)
534 struct afb_hsrv *hsrv;
536 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
537 ERROR("unable to set the tmp directory");
541 hsrv = afb_hsrv_create();
543 ERROR("memory allocation failure");
547 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
548 || !init_http_server(hsrv, config)) {
549 ERROR("initialisation of httpd failed");
554 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
555 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
557 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
559 ERROR("starting of httpd failed");
567 static void start_items(struct afb_config_item *item)
570 /* keeps the order */
571 start_items(item->previous);
574 if (afb_api_dbus_add_client(item->value) < 0) {
575 ERROR("can't start the afb-dbus client of path %s",item->value);
580 if (afb_api_dbus_add_server(item->value) < 0) {
581 ERROR("can't start the afb-dbus service of path %s",item->value);
586 if (afb_api_ws_add_client(item->value) < 0) {
587 ERROR("can't start the afb-websocket client of path %s",item->value);
592 if (afb_api_ws_add_server(item->value) < 0) {
593 ERROR("can't start the afb-websocket service of path %s",item->value);
598 if (afb_api_so_add_binding(item->value) < 0) {
599 ERROR("can't start the binding of path %s",item->value);
604 ERROR("unexpected internal error");
612 /*---------------------------------------------------------
614 | Parse option and launch action
615 +--------------------------------------------------------- */
617 int main(int argc, char *argv[]) {
618 struct afb_hsrv *hsrv;
619 struct afb_config *config;
620 struct sd_event *eventloop;
622 LOGAUTH("afb-daemon");
624 // ------------- Build session handler & init config -------
625 config = calloc (1, sizeof (struct afb_config));
627 on_exit(closeSession, config);
628 parse_arguments(argc, argv, config);
630 // ------------------ sanity check ----------------------------------------
631 if (config->httpdPort <= 0) {
632 ERROR("no port is defined");
636 afb_api_so_set_timeout(config->apiTimeout);
637 if (config->ldpaths) {
638 if (afb_api_so_add_pathset(config->ldpaths) < 0) {
639 ERROR("initialisation of bindings within %s failed", config->ldpaths);
644 start_items(config->items);
645 config->items = NULL;
647 ctxStoreInit(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
648 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
649 ERROR("initialisation of cookies failed");
653 if (afb_sig_handler_init() < 0) {
654 ERROR("failed to initialise signal handlers");
658 if (afb_common_rootdir_set(config->rootdir) < 0) {
659 ERROR("failed to set common root directory");
663 if (afb_thread_init(3, 1, 20) < 0) {
664 ERROR("failed to initialise threading");
668 // let's run this program with a low priority
671 // ------------------ Finaly Process Commands -----------------------------
672 // let's not take the risk to run as ROOT
673 //if (getuid() == 0) goto errorNoRoot;
675 DEBUG("Init config done");
677 // --------- run -----------
678 if (config->background) {
679 // --------- in background mode -----------
680 INFO("entering background mode");
683 // ---- in foreground mode --------------------
684 INFO("entering foreground mode");
687 /* ignore any SIGPIPE */
688 signal(SIGPIPE, SIG_IGN);
690 /* start the HTTP server */
691 hsrv = start_http_server(config);
695 /* start the services */
696 if (afb_apis_start_all_services(1) < 0)
699 if (config->readyfd != 0) {
700 static const char readystr[] = "READY=1";
701 write(config->readyfd, readystr, sizeof(readystr) - 1);
702 close(config->readyfd);
706 eventloop = afb_common_get_event_loop();
708 sd_event_run(eventloop, 30000000);
710 WARNING("hoops returned from infinite loop [report bug]");