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_PLUGIN_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"
38 #include "afb-context.h"
40 #include "afb-sig-handler.h"
43 #include "afb-common.h"
45 #include <afb/afb-plugin.h>
47 #if !defined(PLUGIN_INSTALL_DIR)
48 #error "you should define PLUGIN_INSTALL_DIR"
51 #define AFB_VERSION "0.5"
53 // Define command line option
55 #define SET_BACKGROUND 2
56 #define SET_FORGROUND 3
58 #define SET_TCP_PORT 5
59 #define SET_ROOT_DIR 6
60 #define SET_ROOT_BASE 7
61 #define SET_ROOT_API 8
64 #define SET_CACHE_TIMEOUT 10
65 #define SET_SESSION_DIR 11
67 #define SET_AUTH_TOKEN 12
69 #define SET_APITIMEOUT 14
70 #define SET_CNTXTIMEOUT 15
72 #define DISPLAY_VERSION 16
73 #define DISPLAY_HELP 17
76 #define SET_READYFD 19
78 #define DBUS_CLIENT 20
79 #define DBUS_SERVICE 21
82 // Command line structure hold cli --command + help text
84 int val; // command number within application
85 int has_arg; // command number within application
86 char *name; // command as used in --xxxx cli
87 char *help; // help text
92 static AFB_options cliOptions [] = {
93 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
95 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
96 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
98 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
99 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
100 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
101 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
102 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
104 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
105 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
106 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
108 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
110 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
111 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
113 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
114 {DISPLAY_HELP ,0,"help" , "Display this help"},
116 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
117 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
119 {DBUS_CLIENT ,1,"dbus-client" , "bind to an afb service through dbus"},
120 {DBUS_SERVICE ,1,"dbus-server" , "provides an afb service through dbus"},
121 {SO_PLUGIN ,1,"plugin" , "load the plugin of path"},
126 /*----------------------------------------------------------
128 | print version and copyright
129 +--------------------------------------------------------- */
130 static void printVersion (FILE *file)
132 fprintf(file, "\n----------------------------------------- \n");
133 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
134 fprintf(file, " \n");
135 fprintf(file, " Copyright (C) 2015, 2016 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
136 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
137 fprintf(file, " Licence Apache 2\n\n");
141 /*----------------------------------------------------------
143 | print information from long option array
144 +--------------------------------------------------------- */
146 static void printHelp(FILE *file, const char *name)
151 fprintf (file, "%s:\nallowed options\n", name);
152 for (ind=0; cliOptions [ind].name != NULL;ind++)
155 if (cliOptions [ind].has_arg == 0 )
157 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
159 sprintf(command, "%s=xxxx", cliOptions [ind].name);
160 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
163 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
166 // load config from disk and merge with CLI option
167 static void config_set_default (struct afb_config * config)
170 if (config->httpdPort == 0)
171 config->httpdPort = 1234;
173 // default Plugin API timeout
174 if (config->apiTimeout == 0)
175 config->apiTimeout = DEFLT_API_TIMEOUT;
177 // default AUTH_TOKEN
178 if (config->token == NULL)
179 config->token = DEFLT_AUTH_TOKEN;
181 // cache timeout default one hour
182 if (config->cacheTimeout == 0)
183 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
185 // cache timeout default one hour
186 if (config->cntxTimeout == 0)
187 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
189 if (config->rootdir == NULL) {
190 config->rootdir = getenv("AFBDIR");
191 if (config->rootdir == NULL) {
192 config->rootdir = malloc (512);
193 strncpy (config->rootdir, getenv("HOME"),512);
194 strncat (config->rootdir, "/.AFB",512);
196 // if directory does not exist createit
197 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
200 // if no Angular/HTML5 rootbase let's try '/' as default
201 if (config->rootbase == NULL)
202 config->rootbase = "/opa";
204 if (config->rootapi == NULL)
205 config->rootapi = "/api";
207 if (config->ldpaths == NULL)
208 config->ldpaths = PLUGIN_INSTALL_DIR;
210 // if no session dir create a default path from rootdir
211 if (config->sessiondir == NULL) {
212 config->sessiondir = malloc (512);
213 strncpy (config->sessiondir, config->rootdir, 512);
214 strncat (config->sessiondir, "/sessions",512);
217 // if no config dir create a default path from sessiondir
218 if (config->console == NULL) {
219 config->console = malloc (512);
220 strncpy (config->console, config->sessiondir, 512);
221 strncat (config->console, "/AFB-console.out",512);
226 /*---------------------------------------------------------
228 | Parse option and launch action
229 +--------------------------------------------------------- */
231 static void add_item(struct afb_config *config, int kind, char *value)
233 struct afb_config_item *item = malloc(sizeof *item);
235 ERROR("out of memory");
240 item->previous = config->items;
241 config->items = item;
244 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
246 char* programName = argv [0];
250 struct option *gnuOptions;
252 // ------------------ Process Command Line -----------------------
254 // if no argument print help and return
256 printHelp(stderr, programName);
260 // build GNU getopt info from cliOptions
261 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
262 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
263 for (ind=0; ind < nbcmd;ind++) {
264 gnuOptions [ind].name = cliOptions[ind].name;
265 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
266 gnuOptions [ind].flag = 0;
267 gnuOptions [ind].val = cliOptions[ind].val;
270 // get all options from command line
271 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
281 if (optarg == 0) goto needValueForOption;
282 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
286 if (optarg == 0) goto needValueForOption;
287 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
290 case SET_CNTXTIMEOUT:
291 if (optarg == 0) goto needValueForOption;
292 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
296 if (optarg == 0) goto needValueForOption;
297 config->rootdir = optarg;
298 INFO("Forcing Rootdir=%s",config->rootdir);
302 if (optarg == 0) goto needValueForOption;
303 config->rootbase = optarg;
304 INFO("Forcing Rootbase=%s",config->rootbase);
308 if (optarg == 0) goto needValueForOption;
309 config->rootapi = optarg;
310 INFO("Forcing Rootapi=%s",config->rootapi);
314 if (optarg == 0) goto needValueForOption;
315 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
316 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
317 if (optarg == NULL) {
318 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
320 config->aliasdir[config->aliascount].path = optarg;
321 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
322 config->aliascount++;
325 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
330 if (optarg == 0) goto needValueForOption;
331 config->token = optarg;
335 if (optarg == 0) goto needValueForOption;
336 config->ldpaths = optarg;
339 case SET_SESSION_DIR:
340 if (optarg == 0) goto needValueForOption;
341 config->sessiondir = optarg;
344 case SET_CACHE_TIMEOUT:
345 if (optarg == 0) goto needValueForOption;
346 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
350 if (optarg != 0) goto noValueForOption;
351 config->background = 0;
355 if (optarg != 0) goto noValueForOption;
356 config->background = 1;
360 if (optarg == 0) goto needValueForOption;
361 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
362 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
363 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
368 if (optarg == 0) goto needValueForOption;
369 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
375 if (optarg == 0) goto needValueForOption;
376 add_item(config, optc, optarg);
379 case DISPLAY_VERSION:
380 if (optarg != 0) goto noValueForOption;
381 printVersion(stdout);
386 printHelp(stdout, programName);
392 config_set_default (config);
397 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
398 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
402 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
403 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
407 ERROR("AFB-daemon option [--%s] don't take value"
408 ,gnuOptions[optionIndex].name);
412 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
413 ,gnuOptions[optionIndex].name);
417 /*----------------------------------------------------------
419 | try to close everything before leaving
420 +--------------------------------------------------------- */
421 static void closeSession (int status, void *data) {
422 /* struct afb_config *config = data; */
425 /*----------------------------------------------------------
427 | set the process in background
428 +--------------------------------------------------------- */
429 static void daemonize(struct afb_config *config)
434 // open /dev/console to redirect output messAFBes
435 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
437 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
441 // fork process when running background mode
444 // if fail nothing much to do
446 ERROR("AFB-daemon Failed to fork son process");
450 // if in father process, just leave
451 if (pid != 0) _exit (0);
453 // son process get all data in standalone mode
454 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
456 // redirect default I/O on console
457 close (2); dup(consoleFD); // redirect stderr
458 close (1); dup(consoleFD); // redirect stdout
459 close (0); // no need for stdin
463 setsid(); // allow father process to fully exit
464 sleep (2); // allow main to leave and release port
468 /*---------------------------------------------------------
470 | Handles the HTTP server
471 +--------------------------------------------------------- */
472 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
476 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
479 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
482 for (idx = 0; idx < config->aliascount; idx++)
483 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0, 0))
486 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10, 1))
489 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
495 static struct afb_hsrv *start_http_server(struct afb_config * config)
498 struct afb_hsrv *hsrv;
500 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
501 ERROR("unable to set the tmp directory");
505 hsrv = afb_hsrv_create();
507 ERROR("memory allocation failure");
511 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
512 || !init_http_server(hsrv, config)) {
513 ERROR("initialisation of httpd failed");
518 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
519 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
521 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
523 ERROR("starting of httpd failed");
531 static void start_items(struct afb_config_item *item)
534 /* keeps the order */
535 start_items(item->previous);
538 if (afb_api_dbus_add_client(item->value) < 0) {
539 ERROR("can't start the afb-dbus client of path %s",item->value);
544 if (afb_api_dbus_add_server(item->value) < 0) {
545 ERROR("can't start the afb-dbus service of path %s",item->value);
550 if (afb_api_so_add_plugin(item->value) < 0) {
551 ERROR("can't start the plugin of path %s",item->value);
556 ERROR("unexpected internal error");
564 /*---------------------------------------------------------
566 | Parse option and launch action
567 +--------------------------------------------------------- */
569 int main(int argc, char *argv[]) {
570 struct afb_hsrv *hsrv;
571 struct afb_config *config;
572 struct sd_event *eventloop;
574 LOGAUTH("afb-daemon");
576 // ------------- Build session handler & init config -------
577 config = calloc (1, sizeof (struct afb_config));
579 on_exit(closeSession, config);
580 parse_arguments(argc, argv, config);
582 // ------------------ sanity check ----------------------------------------
583 if (config->httpdPort <= 0) {
584 ERROR("no port is defined");
588 if (config->ldpaths) {
589 if (afb_api_so_add_pathset(config->ldpaths) < 0) {
590 ERROR("initialisation of plugins within %s failed", config->ldpaths);
595 start_items(config->items);
596 config->items = NULL;
598 ctxStoreInit(CTX_NBCLIENTS, config->cntxTimeout, config->token, afb_apis_count());
599 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
600 ERROR("initialisation of cookies failed");
604 if (afb_sig_handler_init() < 0) {
605 ERROR("main fail to initialise signal handlers");
609 // let's run this program with a low priority
612 // ------------------ Finaly Process Commands -----------------------------
613 // let's not take the risk to run as ROOT
614 //if (getuid() == 0) goto errorNoRoot;
616 DEBUG("Init config done");
618 // --------- run -----------
619 if (config->background) {
620 // --------- in background mode -----------
621 INFO("entering background mode");
624 // ---- in foreground mode --------------------
625 INFO("entering foreground mode");
628 hsrv = start_http_server(config);
632 if (config->readyfd != 0) {
633 static const char readystr[] = "READY=1";
634 write(config->readyfd, readystr, sizeof(readystr) - 1);
635 close(config->readyfd);
639 eventloop = afb_common_get_event_loop();
641 sd_event_run(eventloop, 30000000);
643 WARNING("hoops returned from infinite loop [report bug]");