2 * Copyright (C) 2015 "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.
28 #include <sys/types.h>
35 #include <systemd/sd-event.h>
37 #include "afb-config.h"
38 #include "afb-hswitch.h"
40 #include "afb-api-so.h"
41 #include "afb-api-dbus.h"
43 #include "afb-context.h"
45 #include "afb-sig-handler.h"
48 #include "afb-common.h"
50 #include "afb-plugin.h"
52 #if !defined(PLUGIN_INSTALL_DIR)
53 #error "you should define PLUGIN_INSTALL_DIR"
56 #define AFB_VERSION "0.4"
58 // Define command line option
60 #define SET_BACKGROUND 2
61 #define SET_FORGROUND 3
63 #define SET_TCP_PORT 5
64 #define SET_ROOT_DIR 6
65 #define SET_ROOT_BASE 7
66 #define SET_ROOT_API 8
69 #define SET_CACHE_TIMEOUT 10
70 #define SET_SESSION_DIR 11
72 #define SET_AUTH_TOKEN 12
74 #define SET_APITIMEOUT 14
75 #define SET_CNTXTIMEOUT 15
77 #define DISPLAY_VERSION 16
78 #define DISPLAY_HELP 17
81 #define SET_READYFD 19
83 #define DBUS_CLIENT 20
84 #define DBUS_SERVICE 21
87 // Command line structure hold cli --command + help text
89 int val; // command number within application
90 int has_arg; // command number within application
91 char *name; // command as used in --xxxx cli
92 char *help; // help text
97 static AFB_options cliOptions [] = {
98 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
100 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
101 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
103 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
104 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
105 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
106 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
107 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
109 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
110 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
111 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600s]"},
113 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
115 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
116 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
118 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
119 {DISPLAY_HELP ,0,"help" , "Display this help"},
121 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
122 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
124 {DBUS_CLIENT ,1,"dbus-client" , "bind to an afb service through dbus"},
125 {DBUS_SERVICE ,1,"dbus-server" , "provides an afb service through dbus"},
126 {SO_PLUGIN ,1,"plugin" , "load the plugin of path"},
131 /*----------------------------------------------------------
133 | print version and copyright
134 +--------------------------------------------------------- */
135 static void printVersion (FILE *file)
137 fprintf(file, "\n----------------------------------------- \n");
138 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
139 fprintf(file, " \n");
140 fprintf(file, " Copyright(C) 2016 /IoT.bzh [fulup -at- iot.bzh]\n");
141 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
142 fprintf(file, " Licence Apache 2\n\n");
146 /*----------------------------------------------------------
148 | print information from long option array
149 +--------------------------------------------------------- */
151 static void printHelp(FILE *file, const char *name)
156 fprintf (file, "%s:\nallowed options\n", name);
157 for (ind=0; cliOptions [ind].name != NULL;ind++)
160 if (cliOptions [ind].has_arg == 0 )
162 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
164 sprintf(command, "%s=xxxx", cliOptions [ind].name);
165 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
168 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
171 // load config from disk and merge with CLI option
172 static void config_set_default (struct afb_config * config)
175 if (config->httpdPort == 0)
176 config->httpdPort = 1234;
178 // default Plugin API timeout
179 if (config->apiTimeout == 0)
180 config->apiTimeout = DEFLT_API_TIMEOUT;
182 // default AUTH_TOKEN
183 if (config->token == NULL)
184 config->token = DEFLT_AUTH_TOKEN;
186 // cache timeout default one hour
187 if (config->cacheTimeout == 0)
188 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
190 // cache timeout default one hour
191 if (config->cntxTimeout == 0)
192 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
194 if (config->rootdir == NULL) {
195 config->rootdir = getenv("AFBDIR");
196 if (config->rootdir == NULL) {
197 config->rootdir = malloc (512);
198 strncpy (config->rootdir, getenv("HOME"),512);
199 strncat (config->rootdir, "/.AFB",512);
201 // if directory does not exist createit
202 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
205 // if no Angular/HTML5 rootbase let's try '/' as default
206 if (config->rootbase == NULL)
207 config->rootbase = "/opa";
209 if (config->rootapi == NULL)
210 config->rootapi = "/api";
212 if (config->ldpaths == NULL)
213 config->ldpaths = PLUGIN_INSTALL_DIR;
215 // if no session dir create a default path from rootdir
216 if (config->sessiondir == NULL) {
217 config->sessiondir = malloc (512);
218 strncpy (config->sessiondir, config->rootdir, 512);
219 strncat (config->sessiondir, "/sessions",512);
222 // if no config dir create a default path from sessiondir
223 if (config->console == NULL) {
224 config->console = malloc (512);
225 strncpy (config->console, config->sessiondir, 512);
226 strncat (config->console, "/AFB-console.out",512);
231 /*---------------------------------------------------------
233 | Parse option and launch action
234 +--------------------------------------------------------- */
236 static void add_item(struct afb_config *config, int kind, char *value)
238 struct afb_config_item *item = malloc(sizeof *item);
240 ERROR("out of memory");
245 item->previous = config->items;
246 config->items = item;
249 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
251 char* programName = argv [0];
255 struct option *gnuOptions;
257 // ------------------ Process Command Line -----------------------
259 // if no argument print help and return
261 printHelp(stderr, programName);
265 // build GNU getopt info from cliOptions
266 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
267 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
268 for (ind=0; ind < nbcmd;ind++) {
269 gnuOptions [ind].name = cliOptions[ind].name;
270 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
271 gnuOptions [ind].flag = 0;
272 gnuOptions [ind].val = cliOptions[ind].val;
275 // get all options from command line
276 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
286 if (optarg == 0) goto needValueForOption;
287 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
291 if (optarg == 0) goto needValueForOption;
292 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
295 case SET_CNTXTIMEOUT:
296 if (optarg == 0) goto needValueForOption;
297 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
301 if (optarg == 0) goto needValueForOption;
302 config->rootdir = optarg;
303 INFO("Forcing Rootdir=%s",config->rootdir);
307 if (optarg == 0) goto needValueForOption;
308 config->rootbase = optarg;
309 INFO("Forcing Rootbase=%s",config->rootbase);
313 if (optarg == 0) goto needValueForOption;
314 config->rootapi = optarg;
315 INFO("Forcing Rootapi=%s",config->rootapi);
319 if (optarg == 0) goto needValueForOption;
320 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
321 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
322 if (optarg == NULL) {
323 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
325 config->aliasdir[config->aliascount].path = optarg;
326 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
327 config->aliascount++;
330 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
335 if (optarg == 0) goto needValueForOption;
336 config->token = optarg;
340 if (optarg == 0) goto needValueForOption;
341 config->ldpaths = optarg;
344 case SET_SESSION_DIR:
345 if (optarg == 0) goto needValueForOption;
346 config->sessiondir = optarg;
349 case SET_CACHE_TIMEOUT:
350 if (optarg == 0) goto needValueForOption;
351 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
355 if (optarg != 0) goto noValueForOption;
356 config->background = 0;
360 if (optarg != 0) goto noValueForOption;
361 config->background = 1;
365 if (optarg == 0) goto needValueForOption;
366 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
367 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
368 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
373 if (optarg == 0) goto needValueForOption;
374 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
380 if (optarg == 0) goto needValueForOption;
381 add_item(config, optc, optarg);
384 case DISPLAY_VERSION:
385 if (optarg != 0) goto noValueForOption;
386 printVersion(stdout);
391 printHelp(stdout, programName);
397 config_set_default (config);
402 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
403 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
407 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
408 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
412 ERROR("AFB-daemon option [--%s] don't take value"
413 ,gnuOptions[optionIndex].name);
417 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
418 ,gnuOptions[optionIndex].name);
422 /*----------------------------------------------------------
424 | try to close everything before leaving
425 +--------------------------------------------------------- */
426 static void closeSession (int status, void *data) {
427 /* struct afb_config *config = data; */
430 /*----------------------------------------------------------
432 | set the process in background
433 +--------------------------------------------------------- */
434 static void daemonize(struct afb_config *config)
439 // open /dev/console to redirect output messAFBes
440 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
442 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
446 // fork process when running background mode
449 // if fail nothing much to do
451 ERROR("AFB-daemon Failed to fork son process");
455 // if in father process, just leave
456 if (pid != 0) _exit (0);
458 // son process get all data in standalone mode
459 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
461 // redirect default I/O on console
462 close (2); dup(consoleFD); // redirect stderr
463 close (1); dup(consoleFD); // redirect stdout
464 close (0); // no need for stdin
468 setsid(); // allow father process to fully exit
469 sleep (2); // allow main to leave and release port
473 /*---------------------------------------------------------
475 | Handles the HTTP server
476 +--------------------------------------------------------- */
477 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
481 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
484 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
487 for (idx = 0; idx < config->aliascount; idx++)
488 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0))
491 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10))
494 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
500 static struct afb_hsrv *start_http_server(struct afb_config * config)
503 struct afb_hsrv *hsrv;
505 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
506 ERROR("unable to set the tmp directory");
510 hsrv = afb_hsrv_create();
512 ERROR("memory allocation failure");
516 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
517 || !init_http_server(hsrv, config)) {
518 ERROR("initialisation of httpd failed");
523 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
524 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
526 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
528 ERROR("starting of httpd failed");
536 static void start_items(struct afb_config_item *item)
539 /* keeps the order */
540 start_items(item->previous);
543 if (afb_api_dbus_add_client(item->value) < 0) {
544 ERROR("can't start the afb-dbus client of path %s",item->value);
549 if (afb_api_dbus_add_server(item->value) < 0) {
550 ERROR("can't start the afb-dbus service of path %s",item->value);
555 if (afb_api_so_add_plugin(item->value) < 0) {
556 ERROR("can't start the plugin of path %s",item->value);
561 ERROR("unexpected internal error");
569 /*---------------------------------------------------------
571 | Parse option and launch action
572 +--------------------------------------------------------- */
574 int main(int argc, char *argv[]) {
575 struct afb_hsrv *hsrv;
576 struct afb_config *config;
577 struct sd_event *eventloop;
579 // open syslog if ever needed
580 openlog("afb-daemon", 0, LOG_DAEMON);
582 // ------------- Build session handler & init config -------
583 config = calloc (1, sizeof (struct afb_config));
585 on_exit(closeSession, config);
586 parse_arguments(argc, argv, config);
588 // ------------------ sanity check ----------------------------------------
589 if (config->httpdPort <= 0) {
590 ERROR("no port is defined");
595 afb_api_so_add_pathset(config->ldpaths);
597 start_items(config->items);
598 config->items = NULL;
600 ctxStoreInit(CTX_NBCLIENTS, config->cntxTimeout, config->token, afb_apis_count());
601 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
602 ERROR("initialisation of cookies failed");
606 if (afb_sig_handler_init() < 0) {
607 ERROR("main fail to initialise signal handlers");
611 // let's run this program with a low priority
614 // ------------------ Finaly Process Commands -----------------------------
615 // let's not take the risk to run as ROOT
616 //if (getuid() == 0) goto errorNoRoot;
618 DEBUG("Init config done");
620 // --------- run -----------
621 if (config->background) {
622 // --------- in background mode -----------
623 INFO("entering background mode");
626 // ---- in foreground mode --------------------
627 INFO("entering foreground mode");
630 hsrv = start_http_server(config);
634 if (config->readyfd != 0) {
635 static const char readystr[] = "READY=1";
636 write(config->readyfd, readystr, sizeof(readystr) - 1);
637 close(config->readyfd);
641 eventloop = afb_common_get_event_loop();
643 sd_event_run(eventloop, 30000000);
645 WARNING("hoops returned from infinite loop [report bug]");