2 * Copyright (C) 2015-2018 "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 <json-c/json.h>
31 #include "afb-config.h"
35 #define d2s(x) _d2s_(x)
37 #if !defined(BINDING_INSTALL_DIR)
38 #error "you should define BINDING_INSTALL_DIR"
40 #if !defined(AFB_VERSION)
41 #error "you should define AFB_VERSION"
44 /* set the HAS_ options */
45 #if defined(WITH_MONITORING_OPTION)
46 # define HAS_MONITORING 1
48 # define HAS_MONITORING 0
50 #if defined(WITH_DBUS_TRANSPARENCY)
57 * The default timeout of sessions in seconds
59 #define DEFAULT_SESSION_TIMEOUT 32000000
62 * The default timeout of api calls in seconds
64 #define DEFAULT_API_TIMEOUT 20
67 * The default timeout of cache in seconds
69 #define DEFAULT_CACHE_TIMEOUT 100000
72 * The default maximum count of sessions
74 #define DEFAULT_MAX_SESSION_COUNT 200
77 * The default HTTP port to serve
79 #define DEFAULT_HTTP_PORT 1234
85 // Define command line option
86 #define SET_BACKGROUND 1
87 #define SET_FORGROUND 2
88 #define SET_ROOT_DIR 3
89 #define SET_ROOT_BASE 4
90 #define SET_ROOT_API 5
93 #define SET_CACHE_TIMEOUT 7
99 #define SET_APITIMEOUT 11
100 #define SET_CNTXTIMEOUT 12
101 #define SET_WEAK_LDPATH 13
104 #define SET_SESSIONMAX 15
107 #define WS_SERVICE 17
109 #define SET_ROOT_HTTP 18
111 #define SET_NO_HTTPD 19
113 #define SET_TRACEEVT 20
114 #define SET_TRACESES 21
115 #define SET_TRACEREQ 22
116 #define SET_TRACEAPI 23
117 #if !defined(REMOVE_LEGACY_TRACE)
118 #define SET_TRACEDITF 24
119 #define SET_TRACESVC 25
123 # define DBUS_CLIENT 30
124 # define DBUS_SERVICE 31
129 #define SO_BINDING 'b'
132 #define DISPLAY_HELP 'h'
135 #define SET_MONITORING 'M'
138 #define SET_TCP_PORT 'p'
139 #define SET_QUIET 'q'
140 #define SET_RNDTOKEN 'r'
141 #define SET_AUTH_TOKEN 't'
142 #define SET_UPLOAD_DIR 'u'
143 #define DISPLAY_VERSION 'V'
144 #define SET_VERBOSE 'v'
145 #define SET_WORK_DIR 'w'
147 const char shortopts[] =
168 // Command line structure hold cli --command + help text
170 int val; // command number within application
171 int has_arg; // command number within application
172 char *name; // command as used in --xxxx cli
173 char *help; // help text
177 static AFB_options cliOptions[] = {
179 {SET_VERBOSE, 0, "verbose", "Verbose Mode, repeat to increase verbosity"},
180 {SET_QUIET, 0, "quiet", "Quiet Mode, repeat to decrease verbosity"},
181 {SET_LOG, 1, "log", "Tune log level"},
183 {SET_FORGROUND, 0, "foreground", "Get all in foreground mode"},
184 {SET_BACKGROUND, 0, "daemon", "Get all in background mode"},
186 {SET_NAME, 1, "name", "Set the visible name"},
188 {SET_TCP_PORT, 1, "port", "HTTP listening TCP port [default " d2s(DEFAULT_HTTP_PORT) "]"},
189 {SET_ROOT_HTTP, 1, "roothttp", "HTTP Root Directory [default no root http (files not served but apis still available)]"},
190 {SET_ROOT_BASE, 1, "rootbase", "Angular Base Root URL [default /opa]"},
191 {SET_ROOT_API, 1, "rootapi", "HTML Root API URL [default /api]"},
192 {SET_ALIAS, 1, "alias", "Multiple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
194 {SET_APITIMEOUT, 1, "apitimeout", "Binding API timeout in seconds [default " d2s(DEFAULT_API_TIMEOUT) "]"},
195 {SET_CNTXTIMEOUT, 1, "cntxtimeout", "Client Session Context Timeout [default " d2s(DEFAULT_SESSION_TIMEOUT) "]"},
196 {SET_CACHE_TIMEOUT, 1, "cache-eol", "Client cache end of live [default " d2s(DEFAULT_CACHE_TIMEOUT) "]"},
198 {SET_WORK_DIR, 1, "workdir", "Set the working directory [default: $PWD or current working directory]"},
199 {SET_UPLOAD_DIR, 1, "uploaddir", "Directory for uploading files [default: workdir]"},
200 {SET_ROOT_DIR, 1, "rootdir", "Root Directory of the application [default: workdir]"},
202 {SET_LDPATH, 1, "ldpaths", "Load bindings from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
203 {SO_BINDING, 1, "binding", "Load the binding of path"},
204 {SET_WEAK_LDPATH, 1, "weak-ldpaths","Same as --ldpaths but ignore errors"},
205 {NO_LDPATH, 0, "no-ldpaths", "Discard default ldpaths loading"},
207 {SET_AUTH_TOKEN, 1, "token", "Initial Secret [default=random, use --token="" to allow any token]"},
208 {SET_RNDTOKEN, 0, "random-token","Enforce a random token"},
210 {DISPLAY_VERSION, 0, "version", "Display version and copyright"},
211 {DISPLAY_HELP, 0, "help", "Display this help"},
214 {DBUS_CLIENT, 1, "dbus-client", "Bind to an afb service through dbus"},
215 {DBUS_SERVICE, 1, "dbus-server", "Provide an afb service through dbus"},
217 {WS_CLIENT, 1, "ws-client", "Bind to an afb service through websocket"},
218 {WS_SERVICE, 1, "ws-server", "Provide an afb service through websockets"},
220 {AUTO_API, 1, "auto-api", "Automatic load of api of the given directory"},
222 {SET_SESSIONMAX, 1, "session-max", "Max count of session simultaneously [default " d2s(DEFAULT_MAX_SESSION_COUNT) "]"},
224 {SET_TRACEREQ, 1, "tracereq", "Log the requests: no, common, extra, all"},
225 #if !defined(REMOVE_LEGACY_TRACE)
226 {SET_TRACEDITF, 1, "traceditf", "Log the daemons: no, common, all"},
227 {SET_TRACESVC, 1, "tracesvc", "Log the services: no, all"},
229 {SET_TRACEEVT, 1, "traceevt", "Log the events: no, common, extra, all"},
230 {SET_TRACESES, 1, "traceses", "Log the sessions: no, all"},
231 {SET_TRACEAPI, 1, "traceapi", "Log the apis: no, common, api, event, all"},
233 {ADD_CALL, 1, "call", "call at start format of val: API/VERB:json-args"},
235 {SET_NO_HTTPD, 0, "no-httpd", "Forbid HTTP service"},
236 {SET_EXEC, 0, "exec", "Execute the remaining arguments"},
239 {SET_MONITORING, 0, "monitoring", "Enable HTTP monitoring at <ROOT>/monitoring/"},
252 static struct enumdesc tracereq_desc[] = {
254 { "common", afb_hook_flags_req_common },
255 { "extra", afb_hook_flags_req_extra },
256 { "all", afb_hook_flags_req_all },
260 #if !defined(REMOVE_LEGACY_TRACE)
261 static struct enumdesc traceditf_desc[] = {
263 { "common", afb_hook_flags_api_ditf_common },
264 { "all", afb_hook_flags_api_ditf_all },
268 static struct enumdesc tracesvc_desc[] = {
270 { "all", afb_hook_flags_api_svc_all },
275 static struct enumdesc traceevt_desc[] = {
277 { "common", afb_hook_flags_evt_common },
278 { "extra", afb_hook_flags_evt_extra },
279 { "all", afb_hook_flags_evt_all },
283 static struct enumdesc traceses_desc[] = {
285 { "common", afb_hook_flags_session_common },
286 { "all", afb_hook_flags_session_all },
290 static struct enumdesc traceapi_desc[] = {
292 { "common", afb_hook_flags_api_common },
293 { "api", afb_hook_flags_api_api|afb_hook_flag_api_start },
294 { "event", afb_hook_flags_api_event|afb_hook_flag_api_start },
295 { "all", afb_hook_flags_api_all },
299 /*----------------------------------------------------------
301 | print version and copyright
302 +--------------------------------------------------------- */
303 static void printVersion(FILE * file)
305 static char pm[2] = { '-', '+' };
308 " AGL Framework Binder [AFB %s] %cDBUS %cMONITOR\n"
315 " Copyright (C) 2015-2018 \"IoT.bzh\"\n"
316 " AFB comes with ABSOLUTELY NO WARRANTY.\n"
317 " Licence Apache 2\n"
321 /*----------------------------------------------------------
323 | print information from long option array
324 +--------------------------------------------------------- */
326 static void printHelp(FILE * file, const char *name)
329 char command[50], sht[4];
332 fprintf(file, "%s:\nallowed options\n", name);
333 for (ind = 0; cliOptions[ind].name != NULL; ind++) {
334 if (((cliOptions[ind].val >= 'a' && cliOptions[ind].val <= 'z')
335 || (cliOptions[ind].val >= 'A' && cliOptions[ind].val <= 'Z')
336 || (cliOptions[ind].val >= '0' && cliOptions[ind].val <= '9'))
337 && strchr(shortopts, (char)cliOptions[ind].val)) {
339 sht[1] = (char)cliOptions[ind].val;
342 sht[0] = sht[1] = sht[2] = ' ';
344 strcpy(command, cliOptions[ind].name);
345 if (cliOptions[ind].has_arg)
346 strcat(command, "=xxxx");
347 fprintf(file, " %s --%-17s %s\n", sht, command, cliOptions[ind].help);
350 "Example:\n %s --verbose --port=" d2s(DEFAULT_HTTP_PORT) " --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
355 /*----------------------------------------------------------
356 | adds a string to the list
357 +--------------------------------------------------------- */
358 static void list_add(struct afb_config_list **head, char *value)
360 struct afb_config_list *item;
366 while (item != NULL) {
374 item = malloc(sizeof *item);
376 ERROR("out of memory");
388 /*---------------------------------------------------------
389 | helpers for argument scanning
390 +--------------------------------------------------------- */
392 static const char *name_of_option(int optc)
394 AFB_options *o = cliOptions;
395 while (o->name && o->val != optc)
397 return o->name ? : "<unknown-option-name>";
400 static const char *current_argument(int optc)
403 ERROR("option [--%s] needs a value i.e. --%s=xxx",
404 name_of_option(optc), name_of_option(optc));
410 static char *argvalstr(int optc)
412 char *result = strdup(current_argument(optc));
413 if (result == NULL) {
414 ERROR("can't alloc memory");
420 static int argvalenum(int optc, struct enumdesc *desc)
425 const char *name = current_argument(optc);
428 while(desc[i].name && strcmp(desc[i].name, name))
434 len += strlen(desc[i++].name);
435 list = malloc(len + i + i);
437 ERROR("option [--%s] bad value (found %s)",
438 name_of_option(optc), name);
441 strcpy(list, desc[i].name ? : "");
442 while(desc[++i].name)
443 strcat(strcat(list, ", "), desc[i].name);
444 ERROR("option [--%s] bad value, only accepts values %s (found %s)",
445 name_of_option(optc), list, name);
450 return desc[i].value;
453 static int argvalint(int optc, int mini, int maxi, int base)
455 const char *beg, *end;
457 beg = current_argument(optc);
458 val = strtol(beg, (char**)&end, base);
459 if (*end || end == beg) {
460 ERROR("option [--%s] requires a valid integer (found %s)",
461 name_of_option(optc), beg);
464 if (val < (long int)mini || val > (long int)maxi) {
465 ERROR("option [--%s] value out of bounds (not %d<=%ld<=%d)",
466 name_of_option(optc), mini, val, maxi);
472 static int argvalintdec(int optc, int mini, int maxi)
474 return argvalint(optc, mini, maxi, 10);
477 static void noarg(int optc)
480 ERROR("option [--%s] need no value (found %s)", name_of_option(optc), optarg);
485 static char **make_exec(char **argv)
487 char **result, *iter;
492 for (i = 0 ; argv[i] ; i++)
493 length += strlen(argv[i]) + 1;
495 result = malloc(length + ((unsigned)(i + 1)) * sizeof *result);
496 if (result == NULL) {
497 ERROR("can't alloc memory");
501 iter = (char*)&result[i+1];
502 for (i = 0 ; argv[i] ; i++) {
504 iter = stpcpy(iter, argv[i]) + 1;
510 /*---------------------------------------------------------
512 +--------------------------------------------------------- */
514 static void set_log(char *args)
516 char o = 0, s, *p, *i = args;
519 for(;;) switch (*i) {
532 while (isalpha(*p)) p++;
535 lvl = verbose_level_of_name(i);
539 ERROR("Bad log name '%s' in %s", i, args);
557 /*---------------------------------------------------------
558 | Parse option and launch action
559 +--------------------------------------------------------- */
561 static void parse_arguments(int argc, char **argv, struct afb_config *config)
563 char *programName = argv[0];
566 struct option *gnuOptions;
568 // ------------------ Process Command Line -----------------------
570 // build GNU getopt info from cliOptions
571 nbcmd = sizeof(cliOptions) / sizeof(AFB_options);
572 gnuOptions = malloc(sizeof(*gnuOptions) * (unsigned)nbcmd);
573 for (ind = 0; ind < nbcmd; ind++) {
574 gnuOptions[ind].name = cliOptions[ind].name;
575 gnuOptions[ind].has_arg = cliOptions[ind].has_arg;
576 gnuOptions[ind].flag = 0;
577 gnuOptions[ind].val = cliOptions[ind].val;
580 // get all options from command line
581 while ((optc = getopt_long(argc, argv, shortopts, gnuOptions, NULL)) != EOF) {
592 set_log(argvalstr(optc));
596 config->http_port = argvalintdec(optc, 1024, 32767);
600 config->api_timeout = argvalintdec(optc, 0, INT_MAX);
603 case SET_CNTXTIMEOUT:
604 config->session_timeout = argvalintdec(optc, 0, INT_MAX);
608 config->rootdir = argvalstr(optc);
609 INFO("Forcing Rootdir=%s", config->rootdir);
613 config->roothttp = argvalstr(optc);
614 INFO("Forcing Root HTTP=%s", config->roothttp);
618 config->rootbase = argvalstr(optc);
619 INFO("Forcing Rootbase=%s", config->rootbase);
623 config->rootapi = argvalstr(optc);
624 INFO("Forcing Rootapi=%s", config->rootapi);
628 list_add(&config->aliases, argvalstr(optc));
632 config->token = argvalstr(optc);
636 list_add(&config->ldpaths, argvalstr(optc));
639 case SET_WEAK_LDPATH:
640 list_add(&config->weak_ldpaths, argvalstr(optc));
645 config->no_ldpaths = 1;
649 list_add(&config->calls, argvalstr(optc));
653 config->uploaddir = argvalstr(optc);
657 config->workdir = argvalstr(optc);
660 case SET_CACHE_TIMEOUT:
661 config->cache_timeout = argvalintdec(optc, 0, INT_MAX);
665 config->max_session_count = argvalintdec(optc, 1, INT_MAX);
670 config->background = 0;
675 config->background = 1;
679 config->name = argvalstr(optc);
684 list_add(&config->dbus_clients, argvalstr(optc));
688 list_add(&config->dbus_servers, argvalstr(optc));
693 list_add(&config->ws_clients, argvalstr(optc));
697 list_add(&config->ws_servers, argvalstr(optc));
701 list_add(&config->so_bindings, argvalstr(optc));
705 list_add(&config->auto_api, argvalstr(optc));
709 config->tracereq = argvalenum(optc, tracereq_desc);
712 #if !defined(REMOVE_LEGACY_TRACE)
714 config->traceditf = argvalenum(optc, traceditf_desc);
718 config->tracesvc = argvalenum(optc, tracesvc_desc);
723 config->traceevt = argvalenum(optc, traceevt_desc);
727 config->traceses = argvalenum(optc, traceses_desc);
731 config->traceapi = argvalenum(optc, traceapi_desc);
736 config->no_httpd = 1;
740 config->exec = make_exec(&argv[optind]);
741 optind = argc; /* stop option scanning */
745 config->random_token = 1;
750 config->monitoring = 1;
754 case DISPLAY_VERSION:
756 printVersion(stdout);
760 printHelp(stdout, programName);
770 static void fulfill_config(struct afb_config *config)
773 if (config->http_port == 0)
774 config->http_port = DEFAULT_HTTP_PORT;
776 // default binding API timeout
777 if (config->api_timeout == 0)
778 config->api_timeout = DEFAULT_API_TIMEOUT;
780 // default AUTH_TOKEN
781 if (config->random_token)
782 config->token = NULL;
784 // cache timeout default one hour
785 if (config->cache_timeout == 0)
786 config->cache_timeout = DEFAULT_CACHE_TIMEOUT;
788 // cache timeout default one hour
789 if (config->session_timeout == 0)
790 config->session_timeout = DEFAULT_SESSION_TIMEOUT;
792 // max count of sessions
793 if (config->max_session_count == 0)
794 config->max_session_count = DEFAULT_MAX_SESSION_COUNT;
796 /* set directories */
797 if (config->workdir == NULL)
798 config->workdir = ".";
800 if (config->rootdir == NULL)
801 config->rootdir = ".";
803 if (config->uploaddir == NULL)
804 config->uploaddir = ".";
806 // if no Angular/HTML5 rootbase let's try '/' as default
807 if (config->rootbase == NULL)
808 config->rootbase = "/opa";
810 if (config->rootapi == NULL)
811 config->rootapi = "/api";
813 if (config->ldpaths == NULL && config->weak_ldpaths == NULL && !config->no_ldpaths)
814 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
817 if (config->monitoring)
818 list_add(&config->aliases, strdup("/monitoring:"BINDING_INSTALL_DIR"/monitoring"));
821 // if no config dir create a default path from uploaddir
822 if (config->console == NULL) {
823 config->console = malloc(512);
824 strncpy(config->console, config->uploaddir, 512);
825 strncat(config->console, "/AFB-console.out", 512);
828 #if !defined(REMOVE_LEGACY_TRACE)
829 config->traceapi |= config->traceditf | config->tracesvc;
833 void afb_config_dump(struct afb_config *config)
835 struct afb_config_list *l;
839 #define NN(x) (x)?:""
840 #define P(...) fprintf(stderr, __VA_ARGS__)
841 #define PF(x) P("-- %15s: ", #x)
843 #define S(x) PF(x);P("%s",NN(config->x));PE;
844 #define D(x) PF(x);P("%d",config->x);PE;
845 #define B(x) PF(x);P("%s",config->x?"yes":"no");PE;
846 #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;
847 #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);}
848 #define V(x) P("-- %15s:", #x);for(v=config->x;v&&*v;v++)P(" %s",*v); PE;
850 P("---BEGIN-OF-CONFIG---\n");
882 E(tracereq,tracereq_desc)
883 #if !defined(REMOVE_LEGACY_TRACE)
884 E(traceditf,traceditf_desc)
885 E(tracesvc,tracesvc_desc)
887 E(traceevt,traceevt_desc)
888 E(traceses,traceses_desc)
889 E(traceapi,traceapi_desc)
898 P("---END-OF-CONFIG---\n");
912 static void on_environment_list(struct afb_config_list **to, const char *name)
914 char *value = getenv(name);
920 static void on_environment_enum(int *to, const char *name, struct enumdesc *desc)
922 char *value = getenv(name);
926 if (strcmp(desc->name, value))
933 WARNING("Unknown value %s for environment variable %s, ignored", value, name);
937 static void parse_environment(struct afb_config *config)
939 on_environment_enum(&config->tracereq, "AFB_TRACEREQ", tracereq_desc);
940 #if !defined(REMOVE_LEGACY_TRACE)
941 on_environment_enum(&config->traceditf, "AFB_TRACEDITF", traceditf_desc);
942 on_environment_enum(&config->tracesvc, "AFB_TRACESVC", tracesvc_desc);
944 on_environment_enum(&config->traceevt, "AFB_TRACEEVT", traceevt_desc);
945 on_environment_enum(&config->traceses, "AFB_TRACESES", traceses_desc);
946 on_environment_enum(&config->traceapi, "AFB_TRACEAPI", traceapi_desc);
947 on_environment_list(&config->ldpaths, "AFB_LDPATHS");
950 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
952 struct afb_config *result;
954 result = calloc(1, sizeof *result);
956 parse_environment(result);
957 parse_arguments(argc, argv, result);
958 fulfill_config(result);
959 if (verbose_wants(Log_Level_Info))
960 afb_config_dump(result);
964 struct json_object *afb_config_json(struct afb_config *config)
966 struct json_object *r, *a;
967 struct afb_config_list *l;
971 #define XA(t,o) json_object_array_add(t,o);
972 #define XO(t,x,o) json_object_object_add(t,x,o);
973 #define YS(s) ((s)?json_object_new_string(s):NULL)
975 #define AO(o) XA(a,o)
976 #define AS(s) AO(YS(s))
977 #define RO(x,o) XO(r,x,o)
978 #define RS(x,s) RO(x,YS(s))
979 #define RA(x) RO(x,(a=json_object_new_array()))
980 #define RI(x,i) RO(x,json_object_new_int(i))
981 #define RB(x,b) RO(x,json_object_new_boolean(b))
983 #define S(x) RS(#x,config->x)
984 #define V(x) RA(#x);for(v=config->x;v&&*v;v++)AS(*v);
985 #define L(x) RA(#x);for(l=config->x;l;l=l->next)AS(l->value);
986 #define D(x) RI(#x,config->x)
987 #define B(x) RB(#x,config->x)
988 #define E(x,d) for(e=d;e->name&&e->value!=config->x;e++);if(e->name){RS(#x,e->name);}else{D(x);}
990 r = json_object_new_object();
1020 D(max_session_count)
1022 E(tracereq,tracereq_desc)
1023 #if !defined(REMOVE_LEGACY_TRACE)
1024 E(traceditf,traceditf_desc)
1025 E(tracesvc,tracesvc_desc)
1027 E(traceevt,traceevt_desc)
1028 E(traceses,traceses_desc)
1029 E(traceapi,traceapi_desc)