2 * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3 * Author José Bollo <jose.bollo@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
28 #include "afb-config.h"
31 #include <afb/afb-binding-v1.h>
33 #if !defined(BINDING_INSTALL_DIR)
34 #error "you should define BINDING_INSTALL_DIR"
36 #if !defined(AFB_VERSION)
37 #error "you should define AFB_VERSION"
41 #define DEFLT_CNTX_TIMEOUT 3600 // default Client Connection
43 #define DEFLT_API_TIMEOUT 20 // default Plugin API Timeout [0=NoLimit
45 #define DEFLT_CACHE_TIMEOUT 100000 // default Static File Chache
48 #define CTX_NBCLIENTS 10 // allow a default of 10 authenticated
52 // Define command line option
53 #define SET_BACKGROUND 2
54 #define SET_FORGROUND 3
56 #define SET_ROOT_DIR 6
57 #define SET_ROOT_BASE 7
58 #define SET_ROOT_API 8
61 #define SET_CACHE_TIMEOUT 10
62 #define SET_SESSION_DIR 11
65 #define SET_APITIMEOUT 14
66 #define SET_CNTXTIMEOUT 15
67 #define SET_WEAK_LDPATH 16
72 #define DBUS_CLIENT 20
73 #define DBUS_SERVICE 21
76 #define SET_SESSIONMAX 23
81 #define SET_ROOT_HTTP 26
83 #define SET_NO_HTTPD 28
86 #define SET_TRACEDITF 'D'
87 #define SET_TRACEEVT 'E'
89 #define DISPLAY_HELP 'h'
90 #if defined(WITH_MONITORING_OPTION)
91 #define SET_MONITORING 'M'
94 #define SET_TCP_PORT 'p'
96 #define SET_RNDTOKEN 'r'
97 #define SET_TRACESVC 'S'
98 #define SET_TRACEREQ 'T'
99 #define SET_AUTH_TOKEN 't'
100 #define SET_UPLOAD_DIR 'u'
101 #define DISPLAY_VERSION 'V'
102 #define SET_VERBOSE 'v'
103 #define SET_WORK_DIR 'w'
105 const char shortopts[] =
106 "c:D:E:ehn:p:qrT:t:u:Vvw:"
107 #if defined(WITH_MONITORING_OPTION)
112 // Command line structure hold cli --command + help text
114 int val; // command number within application
115 int has_arg; // command number within application
116 char *name; // command as used in --xxxx cli
117 char *help; // help text
121 static AFB_options cliOptions[] = {
123 {SET_VERBOSE, 0, "verbose", "Verbose Mode, repeat to increase verbosity"},
124 {SET_QUIET, 0, "quiet", "Quiet Mode, repeat to decrease verbosity"},
126 {SET_FORGROUND, 0, "foreground", "Get all in foreground mode"},
127 {SET_BACKGROUND, 0, "daemon", "Get all in background mode"},
129 {SET_NAME, 1, "name", "Set the visible name"},
131 {SET_TCP_PORT, 1, "port", "HTTP listening TCP port [default 1234]"},
132 {SET_ROOT_HTTP, 1, "roothttp", "HTTP Root Directory [default no root http (files not served but apis still available)]"},
133 {SET_ROOT_BASE, 1, "rootbase", "Angular Base Root URL [default /opa]"},
134 {SET_ROOT_API, 1, "rootapi", "HTML Root API URL [default /api]"},
135 {SET_ALIAS, 1, "alias", "Multiple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
137 {SET_APITIMEOUT, 1, "apitimeout", "Binding API timeout in seconds [default 10]"},
138 {SET_CNTXTIMEOUT, 1, "cntxtimeout", "Client Session Context Timeout [default 900]"},
139 {SET_CACHE_TIMEOUT, 1, "cache-eol", "Client cache end of live [default 3600]"},
141 {SET_WORK_DIR, 1, "workdir", "Set the working directory [default: $PWD or current working directory]"},
142 {SET_UPLOAD_DIR, 1, "uploaddir", "Directory for uploading files [default: workdir]"},
143 {SET_ROOT_DIR, 1, "rootdir", "Root Directory of the application [default: workdir]"},
144 {SET_SESSION_DIR, 1, "sessiondir", "OBSOLETE (was: Sessions file path)"},
146 {SET_LDPATH, 1, "ldpaths", "Load bindings from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
147 {SO_BINDING, 1, "binding", "Load the binding of path"},
148 {SET_WEAK_LDPATH, 1, "weak-ldpaths","Same as --ldpaths but ignore errors"},
149 {NO_LDPATH, 0, "no-ldpaths", "Discard default ldpaths loading"},
151 {SET_AUTH_TOKEN, 1, "token", "Initial Secret [default=no-session, --token= for session without authentication]"},
152 {SET_RNDTOKEN, 0, "random-token","Enforce a random token"},
154 {DISPLAY_VERSION, 0, "version", "Display version and copyright"},
155 {DISPLAY_HELP, 0, "help", "Display this help"},
157 {SET_MODE, 1, "mode", "Set the mode: either local, remote or global"},
159 {DBUS_CLIENT, 1, "dbus-client", "Bind to an afb service through dbus"},
160 {DBUS_SERVICE, 1, "dbus-server", "Provides an afb service through dbus"},
161 {WS_CLIENT, 1, "ws-client", "Bind to an afb service through websocket"},
162 {WS_SERVICE, 1, "ws-server", "Provides an afb service through websockets"},
164 {SET_SESSIONMAX, 1, "session-max", "Max count of session simultaneously [default 10]"},
166 {SET_TRACEREQ, 1, "tracereq", "Log the requests: no, common, extra, all"},
167 {SET_TRACEDITF, 1, "traceditf", "Log the requests: no, common, extra, all"},
168 {SET_TRACESVC, 1, "tracesvc", "Log the requests: no, all"},
169 {SET_TRACEEVT, 1, "traceevt", "Log the requests: no, common, extra, all"},
171 {ADD_CALL, 1, "call", "call at start format of val: API/VERB:json-args"},
173 {SET_NO_HTTPD, 0, "no-httpd", "Forbids HTTP service"},
174 {SET_EXEC, 0, "exec", "Execute the remaining arguments"},
176 #if defined(WITH_MONITORING_OPTION)
177 {SET_MONITORING, 0, "monitoring", "enable HTTP monitoring at <ROOT>/monitoring/"},
190 static struct enumdesc tracereq_desc[] = {
192 { "common", afb_hook_flags_req_common },
193 { "extra", afb_hook_flags_req_extra },
194 { "all", afb_hook_flags_req_all },
198 static struct enumdesc traceditf_desc[] = {
200 { "common", afb_hook_flags_ditf_common },
201 { "extra", afb_hook_flags_ditf_extra },
202 { "all", afb_hook_flags_ditf_all },
206 static struct enumdesc tracesvc_desc[] = {
208 { "all", afb_hook_flags_svc_all },
212 static struct enumdesc traceevt_desc[] = {
214 { "common", afb_hook_flags_evt_common },
215 { "extra", afb_hook_flags_evt_extra },
216 { "all", afb_hook_flags_evt_all },
220 static struct enumdesc mode_desc[] = {
221 { "local", AFB_MODE_LOCAL },
222 { "remote", AFB_MODE_REMOTE },
223 { "global", AFB_MODE_GLOBAL },
227 /*----------------------------------------------------------
229 | print version and copyright
230 +--------------------------------------------------------- */
231 static void printVersion(FILE * file)
233 static const char version[] =
235 " AFB [Application Framework Binder] version="AFB_VERSION"\n"
237 " Copyright (C) 2015, 2016, 2017 \"IoT.bzh\"\n"
238 " AFB comes with ABSOLUTELY NO WARRANTY.\n"
239 " Licence Apache 2\n"
242 fprintf(file, "%s", version);
245 /*----------------------------------------------------------
247 | print information from long option array
248 +--------------------------------------------------------- */
250 static void printHelp(FILE * file, const char *name)
255 fprintf(file, "%s:\nallowed options\n", name);
256 for (ind = 0; cliOptions[ind].name != NULL; ind++) {
257 strcpy(command, cliOptions[ind].name);
258 if (cliOptions[ind].has_arg)
259 strcat(command, "=xxxx");
260 fprintf(file, " --%-15s %s\n", command, cliOptions[ind].help);
263 "Example:\n %s --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
268 /*----------------------------------------------------------
269 | adds a string to the list
270 +--------------------------------------------------------- */
271 static void list_add(struct afb_config_list **head, char *value)
273 struct afb_config_list *item;
279 while (item != NULL) {
287 item = malloc(sizeof *item);
289 ERROR("out of memory");
301 /*---------------------------------------------------------
302 | helpers for argument scanning
303 +--------------------------------------------------------- */
305 static const char *name_of_option(int optc)
307 AFB_options *o = cliOptions;
308 while (o->name && o->val != optc)
310 return o->name ? : "<unknown-option-name>";
313 static const char *current_argument(int optc)
316 ERROR("option [--%s] needs a value i.e. --%s=xxx",
317 name_of_option(optc), name_of_option(optc));
323 static char *argvalstr(int optc)
325 char *result = strdup(current_argument(optc));
326 if (result == NULL) {
327 ERROR("can't alloc memory");
333 static int argvalenum(int optc, struct enumdesc *desc)
338 const char *name = current_argument(optc);
341 while(desc[i].name && strcmp(desc[i].name, name))
347 len += strlen(desc[i++].name);
348 list = malloc(len + i + i);
350 ERROR("option [--%s] bad value (found %s)",
351 name_of_option(optc), name);
354 strcpy(list, desc[i].name ? : "");
355 while(desc[++i].name)
356 strcat(strcat(list, ", "), desc[i].name);
357 ERROR("option [--%s] bad value, only accepts values %s (found %s)",
358 name_of_option(optc), list, name);
363 return desc[i].value;
366 static int argvalint(int optc, int mini, int maxi, int base)
368 const char *beg, *end;
370 beg = current_argument(optc);
371 val = strtol(beg, (char**)&end, base);
372 if (*end || end == beg) {
373 ERROR("option [--%s] requires a valid integer (found %s)",
374 name_of_option(optc), beg);
377 if (val < (long int)mini || val > (long int)maxi) {
378 ERROR("option [--%s] value out of bounds (not %d<=%ld<=%d)",
379 name_of_option(optc), mini, val, maxi);
385 static int argvalintdec(int optc, int mini, int maxi)
387 return argvalint(optc, mini, maxi, 10);
390 static void noarg(int optc)
393 ERROR("option [--%s] need no value (found %s)", name_of_option(optc), optarg);
398 static char **make_exec(char **argv)
400 char **result, *iter;
405 for (i = 0 ; argv[i] ; i++)
406 length += strlen(argv[i]) + 1;
408 result = malloc(length + ((unsigned)(i + 1)) * sizeof *result);
409 if (result == NULL) {
410 ERROR("can't alloc memory");
414 iter = (char*)&result[i+1];
415 for (i = 0 ; argv[i] ; i++) {
417 iter = stpcpy(iter, argv[i]) + 1;
423 /*---------------------------------------------------------
424 | Parse option and launch action
425 +--------------------------------------------------------- */
427 static void parse_arguments(int argc, char **argv, struct afb_config *config)
429 char *programName = argv[0];
432 struct option *gnuOptions;
434 // ------------------ Process Command Line -----------------------
436 // build GNU getopt info from cliOptions
437 nbcmd = sizeof(cliOptions) / sizeof(AFB_options);
438 gnuOptions = malloc(sizeof(*gnuOptions) * (unsigned)nbcmd);
439 for (ind = 0; ind < nbcmd; ind++) {
440 gnuOptions[ind].name = cliOptions[ind].name;
441 gnuOptions[ind].has_arg = cliOptions[ind].has_arg;
442 gnuOptions[ind].flag = 0;
443 gnuOptions[ind].val = cliOptions[ind].val;
446 // get all options from command line
447 while ((optc = getopt_long(argc, argv, shortopts, gnuOptions, NULL)) != EOF) {
458 config->httpdPort = argvalintdec(optc, 1024, 32767);
462 config->apiTimeout = argvalintdec(optc, 0, INT_MAX);
465 case SET_CNTXTIMEOUT:
466 config->cntxTimeout = argvalintdec(optc, 0, INT_MAX);
470 config->rootdir = argvalstr(optc);
471 INFO("Forcing Rootdir=%s", config->rootdir);
475 config->roothttp = argvalstr(optc);
476 INFO("Forcing Root HTTP=%s", config->roothttp);
480 config->rootbase = argvalstr(optc);
481 INFO("Forcing Rootbase=%s", config->rootbase);
485 config->rootapi = argvalstr(optc);
486 INFO("Forcing Rootapi=%s", config->rootapi);
490 list_add(&config->aliases, argvalstr(optc));
494 config->token = argvalstr(optc);
498 list_add(&config->ldpaths, argvalstr(optc));
501 case SET_WEAK_LDPATH:
502 list_add(&config->weak_ldpaths, argvalstr(optc));
507 config->no_ldpaths = 1;
511 list_add(&config->calls, argvalstr(optc));
514 case SET_SESSION_DIR:
515 /* config->sessiondir = argvalstr(optc); */
516 WARNING("Obsolete option %s ignored", name_of_option(optc));
520 config->uploaddir = argvalstr(optc);
524 config->workdir = argvalstr(optc);
527 case SET_CACHE_TIMEOUT:
528 config->cacheTimeout = argvalintdec(optc, 0, INT_MAX);
532 config->nbSessionMax = argvalintdec(optc, 1, INT_MAX);
537 config->background = 0;
542 config->background = 1;
546 config->name = argvalstr(optc);
550 config->mode = argvalenum(optc, mode_desc);
554 list_add(&config->dbus_clients, argvalstr(optc));
558 list_add(&config->dbus_servers, argvalstr(optc));
562 list_add(&config->ws_clients, argvalstr(optc));
566 list_add(&config->ws_servers, argvalstr(optc));
570 list_add(&config->so_bindings, argvalstr(optc));
574 config->tracereq = argvalenum(optc, tracereq_desc);
578 config->traceditf = argvalenum(optc, traceditf_desc);
582 config->tracesvc = argvalenum(optc, tracesvc_desc);
586 config->traceevt = argvalenum(optc, traceevt_desc);
595 config->exec = make_exec(&argv[optind]);
596 optind = argc; /* stop option scanning */
600 config->random_token = 1;
603 #if defined(WITH_MONITORING_OPTION)
605 config->monitoring = 1;
609 case DISPLAY_VERSION:
611 printVersion(stdout);
615 printHelp(stdout, programName);
625 static void fulfill_config(struct afb_config *config)
628 if (config->httpdPort == 0)
629 config->httpdPort = 1234;
631 // default binding API timeout
632 if (config->apiTimeout == 0)
633 config->apiTimeout = DEFLT_API_TIMEOUT;
635 // default AUTH_TOKEN
636 if (config->random_token)
637 config->token = NULL;
639 // cache timeout default one hour
640 if (config->cacheTimeout == 0)
641 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
643 // cache timeout default one hour
644 if (config->cntxTimeout == 0)
645 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
647 // max count of sessions
648 if (config->nbSessionMax == 0)
649 config->nbSessionMax = CTX_NBCLIENTS;
651 /* set directories */
652 if (config->workdir == NULL)
653 config->workdir = ".";
655 if (config->rootdir == NULL)
656 config->rootdir = ".";
658 if (config->uploaddir == NULL)
659 config->uploaddir = ".";
661 // if no Angular/HTML5 rootbase let's try '/' as default
662 if (config->rootbase == NULL)
663 config->rootbase = "/opa";
665 if (config->rootapi == NULL)
666 config->rootapi = "/api";
668 if (config->ldpaths == NULL && config->weak_ldpaths == NULL && !config->no_ldpaths)
669 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
671 #if defined(WITH_MONITORING_OPTION)
672 if (config->monitoring)
673 list_add(&config->aliases, strdup("/monitoring:"BINDING_INSTALL_DIR"/monitoring"));
676 // if no config dir create a default path from uploaddir
677 if (config->console == NULL) {
678 config->console = malloc(512);
679 strncpy(config->console, config->uploaddir, 512);
680 strncat(config->console, "/AFB-console.out", 512);
684 void afb_config_dump(struct afb_config *config)
686 struct afb_config_list *l;
690 #define NN(x) (x)?:""
691 #define P(...) fprintf(stderr, __VA_ARGS__)
692 #define PF(x) P("-- %15s: ", #x)
694 #define S(x) PF(x);P("%s",NN(config->x));PE;
695 #define D(x) PF(x);P("%d",config->x);PE;
696 #define H(x) PF(x);P("%x",config->x);PE;
697 #define B(x) PF(x);P("%s",config->x?"yes":"no");PE;
698 #define L(x) PF(x);l=config->x;if(l){P("%s\n",NN(l->value));for(l=l->next;l;l=l->next)P("-- %15s %s\n","",NN(l->value));}else PE;
699 #define E(x,d) for(e=d;e->name&&e->value!=config->x;e++);if(e->name){PF(x);P("%s",e->name);PE;}else{D(x);}
700 #define V(x) P("-- %15s:", #x);for(v=config->x;v&&*v;v++)P(" %s",*v); PE;
702 P("---BEGIN-OF-CONFIG---\n");
732 E(tracereq,tracereq_desc)
733 E(traceditf,traceditf_desc)
734 E(tracesvc,tracesvc_desc)
735 E(traceevt,traceevt_desc)
742 P("---END-OF-CONFIG---\n");
757 static void on_environment_list(struct afb_config_list **to, const char *name)
759 char *value = getenv(name);
765 static void on_environment_enum(int *to, const char *name, struct enumdesc *desc)
767 char *value = getenv(name);
771 if (strcmp(desc->name, value))
778 WARNING("Unknown value %s for environment variable %s, ignored", value, name);
782 static void parse_environment(struct afb_config *config)
784 on_environment_enum(&config->tracereq, "AFB_TRACEREQ", tracereq_desc);
785 on_environment_enum(&config->traceditf, "AFB_TRACEDITF", traceditf_desc);
786 on_environment_enum(&config->tracesvc, "AFB_TRACESVC", tracesvc_desc);
787 on_environment_enum(&config->traceevt, "AFB_TRACEEVT", traceevt_desc);
788 on_environment_list(&config->ldpaths, "AFB_LDPATHS");
791 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
793 struct afb_config *result;
795 result = calloc(1, sizeof *result);
797 parse_environment(result);
798 parse_arguments(argc, argv, result);
799 fulfill_config(result);
801 afb_config_dump(result);