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 #define SET_SESSIONMAX 23
84 // Command line structure hold cli --command + help text
86 int val; // command number within application
87 int has_arg; // command number within application
88 char *name; // command as used in --xxxx cli
89 char *help; // help text
94 static AFB_options cliOptions [] = {
95 {SET_VERBOSE ,0,"verbose" , "Verbose Mode"},
97 {SET_FORGROUND ,0,"foreground" , "Get all in foreground mode"},
98 {SET_BACKGROUND ,0,"daemon" , "Get all in background mode"},
100 {SET_TCP_PORT ,1,"port" , "HTTP listening TCP port [default 1234]"},
101 {SET_ROOT_DIR ,1,"rootdir" , "HTTP Root Directory [default $HOME/.AFB]"},
102 {SET_ROOT_BASE ,1,"rootbase" , "Angular Base Root URL [default /opa]"},
103 {SET_ROOT_API ,1,"rootapi" , "HTML Root API URL [default /api]"},
104 {SET_ALIAS ,1,"alias" , "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
106 {SET_APITIMEOUT ,1,"apitimeout" , "Plugin API timeout in seconds [default 10]"},
107 {SET_CNTXTIMEOUT ,1,"cntxtimeout" , "Client Session Context Timeout [default 900]"},
108 {SET_CACHE_TIMEOUT,1,"cache-eol" , "Client cache end of live [default 3600]"},
110 {SET_SESSION_DIR ,1,"sessiondir" , "Sessions file path [default rootdir/sessions]"},
112 {SET_LDPATH ,1,"ldpaths" , "Load Plugins from dir1:dir2:... [default = PLUGIN_INSTALL_DIR"},
113 {SET_AUTH_TOKEN ,1,"token" , "Initial Secret [default=no-session, --token="" for session without authentication]"},
115 {DISPLAY_VERSION ,0,"version" , "Display version and copyright"},
116 {DISPLAY_HELP ,0,"help" , "Display this help"},
118 {SET_MODE ,1,"mode" , "set the mode: either local, remote or global"},
119 {SET_READYFD ,1,"readyfd" , "set the #fd to signal when ready"},
121 {DBUS_CLIENT ,1,"dbus-client" , "bind to an afb service through dbus"},
122 {DBUS_SERVICE ,1,"dbus-server" , "provides an afb service through dbus"},
123 {SO_PLUGIN ,1,"plugin" , "load the plugin of path"},
125 {SET_SESSIONMAX ,1,"session-max" , "max count of session simultaneously [default 10]"},
130 /*----------------------------------------------------------
132 | print version and copyright
133 +--------------------------------------------------------- */
134 static void printVersion (FILE *file)
136 fprintf(file, "\n----------------------------------------- \n");
137 fprintf(file, " AFB [Application Framework Binder] version=%s |\n", AFB_VERSION);
138 fprintf(file, " \n");
139 fprintf(file, " Copyright (C) 2015, 2016 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
140 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
141 fprintf(file, " Licence Apache 2\n\n");
145 /*----------------------------------------------------------
147 | print information from long option array
148 +--------------------------------------------------------- */
150 static void printHelp(FILE *file, const char *name)
155 fprintf (file, "%s:\nallowed options\n", name);
156 for (ind=0; cliOptions [ind].name != NULL;ind++)
159 if (cliOptions [ind].has_arg == 0 )
161 fprintf (file, " --%-15s %s\n", cliOptions [ind].name, cliOptions[ind].help);
163 sprintf(command, "%s=xxxx", cliOptions [ind].name);
164 fprintf (file, " --%-15s %s\n", command, cliOptions[ind].help);
167 fprintf (file, "Example:\n %s\\\n --verbose --port=1234 --token='azerty' --ldpaths=build/plugins:/usr/lib64/agl/plugins\n", name);
170 // load config from disk and merge with CLI option
171 static void config_set_default (struct afb_config * config)
174 if (config->httpdPort == 0)
175 config->httpdPort = 1234;
177 // default Plugin API timeout
178 if (config->apiTimeout == 0)
179 config->apiTimeout = DEFLT_API_TIMEOUT;
181 // default AUTH_TOKEN
182 if (config->token == NULL)
183 config->token = DEFLT_AUTH_TOKEN;
185 // cache timeout default one hour
186 if (config->cacheTimeout == 0)
187 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
189 // cache timeout default one hour
190 if (config->cntxTimeout == 0)
191 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
193 // max count of sessions
194 if (config->nbSessionMax == 0)
195 config->nbSessionMax = CTX_NBCLIENTS;
197 if (config->rootdir == NULL) {
198 config->rootdir = getenv("AFBDIR");
199 if (config->rootdir == NULL) {
200 config->rootdir = malloc (512);
201 strncpy (config->rootdir, getenv("HOME"),512);
202 strncat (config->rootdir, "/.AFB",512);
204 // if directory does not exist createit
205 mkdir (config->rootdir, O_RDWR | S_IRWXU | S_IRGRP);
208 // if no Angular/HTML5 rootbase let's try '/' as default
209 if (config->rootbase == NULL)
210 config->rootbase = "/opa";
212 if (config->rootapi == NULL)
213 config->rootapi = "/api";
215 if (config->ldpaths == NULL)
216 config->ldpaths = PLUGIN_INSTALL_DIR;
218 // if no session dir create a default path from rootdir
219 if (config->sessiondir == NULL) {
220 config->sessiondir = malloc (512);
221 strncpy (config->sessiondir, config->rootdir, 512);
222 strncat (config->sessiondir, "/sessions",512);
225 // if no config dir create a default path from sessiondir
226 if (config->console == NULL) {
227 config->console = malloc (512);
228 strncpy (config->console, config->sessiondir, 512);
229 strncat (config->console, "/AFB-console.out",512);
234 /*---------------------------------------------------------
236 | Parse option and launch action
237 +--------------------------------------------------------- */
239 static void add_item(struct afb_config *config, int kind, char *value)
241 struct afb_config_item *item = malloc(sizeof *item);
243 ERROR("out of memory");
248 item->previous = config->items;
249 config->items = item;
252 static void parse_arguments(int argc, char *argv[], struct afb_config *config)
254 char* programName = argv [0];
258 struct option *gnuOptions;
260 // ------------------ Process Command Line -----------------------
262 // if no argument print help and return
264 printHelp(stderr, programName);
268 // build GNU getopt info from cliOptions
269 nbcmd = sizeof (cliOptions) / sizeof (AFB_options);
270 gnuOptions = malloc (sizeof (*gnuOptions) * (unsigned)nbcmd);
271 for (ind=0; ind < nbcmd;ind++) {
272 gnuOptions [ind].name = cliOptions[ind].name;
273 gnuOptions [ind].has_arg = cliOptions[ind].has_arg;
274 gnuOptions [ind].flag = 0;
275 gnuOptions [ind].val = cliOptions[ind].val;
278 // get all options from command line
279 while ((optc = getopt_long (argc, argv, "vsp?", gnuOptions, &optionIndex))
289 if (optarg == 0) goto needValueForOption;
290 if (!sscanf (optarg, "%d", &config->httpdPort)) goto notAnInteger;
294 if (optarg == 0) goto needValueForOption;
295 if (!sscanf (optarg, "%d", &config->apiTimeout)) goto notAnInteger;
298 case SET_CNTXTIMEOUT:
299 if (optarg == 0) goto needValueForOption;
300 if (!sscanf (optarg, "%d", &config->cntxTimeout)) goto notAnInteger;
304 if (optarg == 0) goto needValueForOption;
305 config->rootdir = optarg;
306 INFO("Forcing Rootdir=%s",config->rootdir);
310 if (optarg == 0) goto needValueForOption;
311 config->rootbase = optarg;
312 INFO("Forcing Rootbase=%s",config->rootbase);
316 if (optarg == 0) goto needValueForOption;
317 config->rootapi = optarg;
318 INFO("Forcing Rootapi=%s",config->rootapi);
322 if (optarg == 0) goto needValueForOption;
323 if ((unsigned)config->aliascount < sizeof (config->aliasdir) / sizeof (config->aliasdir[0])) {
324 config->aliasdir[config->aliascount].url = strsep(&optarg,":");
325 if (optarg == NULL) {
326 ERROR("missing ':' in alias %s, ignored", config->aliasdir[config->aliascount].url);
328 config->aliasdir[config->aliascount].path = optarg;
329 INFO("Alias url=%s path=%s", config->aliasdir[config->aliascount].url, config->aliasdir[config->aliascount].path);
330 config->aliascount++;
333 ERROR("Too many aliases [max:%d] %s ignored", MAX_ALIAS, optarg);
338 if (optarg == 0) goto needValueForOption;
339 config->token = optarg;
343 if (optarg == 0) goto needValueForOption;
344 config->ldpaths = optarg;
347 case SET_SESSION_DIR:
348 if (optarg == 0) goto needValueForOption;
349 config->sessiondir = optarg;
352 case SET_CACHE_TIMEOUT:
353 if (optarg == 0) goto needValueForOption;
354 if (!sscanf (optarg, "%d", &config->cacheTimeout)) goto notAnInteger;
358 if (optarg == 0) goto needValueForOption;
359 if (!sscanf (optarg, "%d", &config->nbSessionMax)) goto notAnInteger;
363 if (optarg != 0) goto noValueForOption;
364 config->background = 0;
368 if (optarg != 0) goto noValueForOption;
369 config->background = 1;
373 if (optarg == 0) goto needValueForOption;
374 if (!strcmp(optarg, "local")) config->mode = AFB_MODE_LOCAL;
375 else if (!strcmp(optarg, "remote")) config->mode = AFB_MODE_REMOTE;
376 else if (!strcmp(optarg, "global")) config->mode = AFB_MODE_GLOBAL;
381 if (optarg == 0) goto needValueForOption;
382 if (!sscanf (optarg, "%u", &config->readyfd)) goto notAnInteger;
388 if (optarg == 0) goto needValueForOption;
389 add_item(config, optc, optarg);
392 case DISPLAY_VERSION:
393 if (optarg != 0) goto noValueForOption;
394 printVersion(stdout);
399 printHelp(stdout, programName);
405 config_set_default (config);
410 ERROR("AFB-daemon option [--%s] need a value i.e. --%s=xxx"
411 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
415 ERROR("AFB-daemon option [--%s] requirer an interger i.e. --%s=9"
416 ,gnuOptions[optionIndex].name, gnuOptions[optionIndex].name);
420 ERROR("AFB-daemon option [--%s] don't take value"
421 ,gnuOptions[optionIndex].name);
425 ERROR("AFB-daemon option [--%s] only accepts local, global or remote."
426 ,gnuOptions[optionIndex].name);
430 /*----------------------------------------------------------
432 | try to close everything before leaving
433 +--------------------------------------------------------- */
434 static void closeSession (int status, void *data) {
435 /* struct afb_config *config = data; */
438 /*----------------------------------------------------------
440 | set the process in background
441 +--------------------------------------------------------- */
442 static void daemonize(struct afb_config *config)
447 // open /dev/console to redirect output messAFBes
448 consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
450 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
454 // fork process when running background mode
457 // if fail nothing much to do
459 ERROR("AFB-daemon Failed to fork son process");
463 // if in father process, just leave
464 if (pid != 0) _exit (0);
466 // son process get all data in standalone mode
467 NOTICE("background mode [pid:%d console:%s]", getpid(),config->console);
469 // redirect default I/O on console
470 close (2); dup(consoleFD); // redirect stderr
471 close (1); dup(consoleFD); // redirect stdout
472 close (0); // no need for stdin
476 setsid(); // allow father process to fully exit
477 sleep (2); // allow main to leave and release port
481 /*---------------------------------------------------------
483 | Handles the HTTP server
484 +--------------------------------------------------------- */
485 static int init_http_server(struct afb_hsrv *hsrv, struct afb_config * config)
489 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
492 if (!afb_hsrv_add_handler(hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
495 for (idx = 0; idx < config->aliascount; idx++)
496 if (!afb_hsrv_add_alias (hsrv, config->aliasdir[idx].url, config->aliasdir[idx].path, 0, 0))
499 if (!afb_hsrv_add_alias(hsrv, "", config->rootdir, -10, 1))
502 if (!afb_hsrv_add_handler(hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL, -20))
508 static struct afb_hsrv *start_http_server(struct afb_config * config)
511 struct afb_hsrv *hsrv;
513 if (afb_hreq_init_download_path("/tmp")) { /* TODO: sessiondir? */
514 ERROR("unable to set the tmp directory");
518 hsrv = afb_hsrv_create();
520 ERROR("memory allocation failure");
524 if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
525 || !init_http_server(hsrv, config)) {
526 ERROR("initialisation of httpd failed");
531 NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
532 NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
534 rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
536 ERROR("starting of httpd failed");
544 static void start_items(struct afb_config_item *item)
547 /* keeps the order */
548 start_items(item->previous);
551 if (afb_api_dbus_add_client(item->value) < 0) {
552 ERROR("can't start the afb-dbus client of path %s",item->value);
557 if (afb_api_dbus_add_server(item->value) < 0) {
558 ERROR("can't start the afb-dbus service of path %s",item->value);
563 if (afb_api_so_add_plugin(item->value) < 0) {
564 ERROR("can't start the plugin of path %s",item->value);
569 ERROR("unexpected internal error");
577 /*---------------------------------------------------------
579 | Parse option and launch action
580 +--------------------------------------------------------- */
582 int main(int argc, char *argv[]) {
583 struct afb_hsrv *hsrv;
584 struct afb_config *config;
585 struct sd_event *eventloop;
587 LOGAUTH("afb-daemon");
589 // ------------- Build session handler & init config -------
590 config = calloc (1, sizeof (struct afb_config));
592 on_exit(closeSession, config);
593 parse_arguments(argc, argv, config);
595 // ------------------ sanity check ----------------------------------------
596 if (config->httpdPort <= 0) {
597 ERROR("no port is defined");
601 afb_api_so_set_timeout(config->apiTimeout);
602 if (config->ldpaths) {
603 if (afb_api_so_add_pathset(config->ldpaths) < 0) {
604 ERROR("initialisation of plugins within %s failed", config->ldpaths);
609 start_items(config->items);
610 config->items = NULL;
612 ctxStoreInit(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
613 if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, DEFLT_CNTX_TIMEOUT)) {
614 ERROR("initialisation of cookies failed");
618 if (afb_sig_handler_init() < 0) {
619 ERROR("main fail to initialise signal handlers");
623 // let's run this program with a low priority
626 // ------------------ Finaly Process Commands -----------------------------
627 // let's not take the risk to run as ROOT
628 //if (getuid() == 0) goto errorNoRoot;
630 DEBUG("Init config done");
632 // --------- run -----------
633 if (config->background) {
634 // --------- in background mode -----------
635 INFO("entering background mode");
638 // ---- in foreground mode --------------------
639 INFO("entering foreground mode");
642 hsrv = start_http_server(config);
646 if (config->readyfd != 0) {
647 static const char readystr[] = "READY=1";
648 write(config->readyfd, readystr, sizeof(readystr) - 1);
649 close(config->readyfd);
653 eventloop = afb_common_get_event_loop();
655 sd_event_run(eventloop, 30000000);
657 WARNING("hoops returned from infinite loop [report bug]");