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.
27 #include <json-c/json.h>
30 #include "afb-config.h"
33 #include <afb/afb-binding-v1.h>
35 #if !defined(BINDING_INSTALL_DIR)
36 #error "you should define BINDING_INSTALL_DIR"
38 #if !defined(AFB_VERSION)
39 #error "you should define AFB_VERSION"
43 #define DEFLT_CNTX_TIMEOUT 32000000 // default Client Connection
44 // Timeout: few more than one year
45 #define DEFLT_API_TIMEOUT 20 // default Plugin API Timeout [0=NoLimit
47 #define DEFLT_CACHE_TIMEOUT 100000 // default Static File Chache
50 #define CTX_NBCLIENTS 10 // allow a default of 10 authenticated
54 // Define command line option
55 #define SET_BACKGROUND 2
56 #define SET_FORGROUND 3
58 #define SET_ROOT_DIR 6
59 #define SET_ROOT_BASE 7
60 #define SET_ROOT_API 8
63 #define SET_CACHE_TIMEOUT 10
64 #define SET_SESSION_DIR 11
67 #define SET_APITIMEOUT 14
68 #define SET_CNTXTIMEOUT 15
69 #define SET_WEAK_LDPATH 16
74 #define DBUS_CLIENT 20
75 #define DBUS_SERVICE 21
78 #define SET_SESSIONMAX 23
83 #define SET_ROOT_HTTP 26
85 #define SET_NO_HTTPD 28
88 #define SET_TRACEDITF 'D'
89 #define SET_TRACEEVT 'E'
91 #define DISPLAY_HELP 'h'
92 #if defined(WITH_MONITORING_OPTION)
93 #define SET_MONITORING 'M'
96 #define SET_TCP_PORT 'p'
98 #define SET_RNDTOKEN 'r'
99 #define SET_TRACESVC 'S'
100 #define SET_TRACESES 's'
101 #define SET_TRACEREQ 'T'
102 #define SET_AUTH_TOKEN 't'
103 #define SET_UPLOAD_DIR 'u'
104 #define DISPLAY_VERSION 'V'
105 #define SET_VERBOSE 'v'
106 #define SET_WORK_DIR 'w'
108 const char shortopts[] =
109 "c:D:E:ehn:p:qrS:s:T:t:u:Vvw:"
110 #if defined(WITH_MONITORING_OPTION)
115 // Command line structure hold cli --command + help text
117 int val; // command number within application
118 int has_arg; // command number within application
119 char *name; // command as used in --xxxx cli
120 char *help; // help text
124 static AFB_options cliOptions[] = {
126 {SET_VERBOSE, 0, "verbose", "Verbose Mode, repeat to increase verbosity"},
127 {SET_QUIET, 0, "quiet", "Quiet Mode, repeat to decrease verbosity"},
129 {SET_FORGROUND, 0, "foreground", "Get all in foreground mode"},
130 {SET_BACKGROUND, 0, "daemon", "Get all in background mode"},
132 {SET_NAME, 1, "name", "Set the visible name"},
134 {SET_TCP_PORT, 1, "port", "HTTP listening TCP port [default 1234]"},
135 {SET_ROOT_HTTP, 1, "roothttp", "HTTP Root Directory [default no root http (files not served but apis still available)]"},
136 {SET_ROOT_BASE, 1, "rootbase", "Angular Base Root URL [default /opa]"},
137 {SET_ROOT_API, 1, "rootapi", "HTML Root API URL [default /api]"},
138 {SET_ALIAS, 1, "alias", "Multiple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
140 {SET_APITIMEOUT, 1, "apitimeout", "Binding API timeout in seconds [default 10]"},
141 {SET_CNTXTIMEOUT, 1, "cntxtimeout", "Client Session Context Timeout [default 900]"},
142 {SET_CACHE_TIMEOUT, 1, "cache-eol", "Client cache end of live [default 3600]"},
144 {SET_WORK_DIR, 1, "workdir", "Set the working directory [default: $PWD or current working directory]"},
145 {SET_UPLOAD_DIR, 1, "uploaddir", "Directory for uploading files [default: workdir]"},
146 {SET_ROOT_DIR, 1, "rootdir", "Root Directory of the application [default: workdir]"},
147 {SET_SESSION_DIR, 1, "sessiondir", "OBSOLETE (was: Sessions file path)"},
149 {SET_LDPATH, 1, "ldpaths", "Load bindings from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
150 {SO_BINDING, 1, "binding", "Load the binding of path"},
151 {SET_WEAK_LDPATH, 1, "weak-ldpaths","Same as --ldpaths but ignore errors"},
152 {NO_LDPATH, 0, "no-ldpaths", "Discard default ldpaths loading"},
154 {SET_AUTH_TOKEN, 1, "token", "Initial Secret [default=random, use --token="" to allow any token]"},
155 {SET_RNDTOKEN, 0, "random-token","Enforce a random token"},
157 {DISPLAY_VERSION, 0, "version", "Display version and copyright"},
158 {DISPLAY_HELP, 0, "help", "Display this help"},
160 {SET_MODE, 1, "mode", "Set the mode: either local, remote or global"},
162 {DBUS_CLIENT, 1, "dbus-client", "Bind to an afb service through dbus"},
163 {DBUS_SERVICE, 1, "dbus-server", "Provides an afb service through dbus"},
164 {WS_CLIENT, 1, "ws-client", "Bind to an afb service through websocket"},
165 {WS_SERVICE, 1, "ws-server", "Provides an afb service through websockets"},
167 {SET_SESSIONMAX, 1, "session-max", "Max count of session simultaneously [default 10]"},
169 {SET_TRACEREQ, 1, "tracereq", "Log the requests: no, common, extra, all"},
170 {SET_TRACEDITF, 1, "traceditf", "Log the requests: no, common, extra, all"},
171 {SET_TRACESVC, 1, "tracesvc", "Log the requests: no, all"},
172 {SET_TRACEEVT, 1, "traceevt", "Log the requests: no, common, extra, all"},
173 {SET_TRACESES, 1, "traceses", "Log the sessions: no, all"},
175 {ADD_CALL, 1, "call", "call at start format of val: API/VERB:json-args"},
177 {SET_NO_HTTPD, 0, "no-httpd", "Forbids HTTP service"},
178 {SET_EXEC, 0, "exec", "Execute the remaining arguments"},
180 #if defined(WITH_MONITORING_OPTION)
181 {SET_MONITORING, 0, "monitoring", "enable HTTP monitoring at <ROOT>/monitoring/"},
194 static struct enumdesc tracereq_desc[] = {
196 { "common", afb_hook_flags_req_common },
197 { "extra", afb_hook_flags_req_extra },
198 { "all", afb_hook_flags_req_all },
202 static struct enumdesc traceditf_desc[] = {
204 { "common", afb_hook_flags_ditf_common },
205 { "extra", afb_hook_flags_ditf_extra },
206 { "all", afb_hook_flags_ditf_all },
210 static struct enumdesc tracesvc_desc[] = {
212 { "all", afb_hook_flags_svc_all },
216 static struct enumdesc traceevt_desc[] = {
218 { "common", afb_hook_flags_evt_common },
219 { "extra", afb_hook_flags_evt_extra },
220 { "all", afb_hook_flags_evt_all },
224 static struct enumdesc traceses_desc[] = {
226 { "common", afb_hook_flags_session_common },
227 { "all", afb_hook_flags_session_all },
231 static struct enumdesc mode_desc[] = {
232 { "local", AFB_MODE_LOCAL },
233 { "remote", AFB_MODE_REMOTE },
234 { "global", AFB_MODE_GLOBAL },
238 /*----------------------------------------------------------
240 | print version and copyright
241 +--------------------------------------------------------- */
242 static void printVersion(FILE * file)
244 static const char version[] =
246 " AFB [Application Framework Binder] version="AFB_VERSION"\n"
248 " Copyright (C) 2015, 2016, 2017 \"IoT.bzh\"\n"
249 " AFB comes with ABSOLUTELY NO WARRANTY.\n"
250 " Licence Apache 2\n"
253 fprintf(file, "%s", version);
256 /*----------------------------------------------------------
258 | print information from long option array
259 +--------------------------------------------------------- */
261 static void printHelp(FILE * file, const char *name)
266 fprintf(file, "%s:\nallowed options\n", name);
267 for (ind = 0; cliOptions[ind].name != NULL; ind++) {
268 strcpy(command, cliOptions[ind].name);
269 if (cliOptions[ind].has_arg)
270 strcat(command, "=xxxx");
271 fprintf(file, " --%-15s %s\n", command, cliOptions[ind].help);
274 "Example:\n %s --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
279 /*----------------------------------------------------------
280 | adds a string to the list
281 +--------------------------------------------------------- */
282 static void list_add(struct afb_config_list **head, char *value)
284 struct afb_config_list *item;
290 while (item != NULL) {
298 item = malloc(sizeof *item);
300 ERROR("out of memory");
312 /*---------------------------------------------------------
313 | helpers for argument scanning
314 +--------------------------------------------------------- */
316 static const char *name_of_option(int optc)
318 AFB_options *o = cliOptions;
319 while (o->name && o->val != optc)
321 return o->name ? : "<unknown-option-name>";
324 static const char *current_argument(int optc)
327 ERROR("option [--%s] needs a value i.e. --%s=xxx",
328 name_of_option(optc), name_of_option(optc));
334 static char *argvalstr(int optc)
336 char *result = strdup(current_argument(optc));
337 if (result == NULL) {
338 ERROR("can't alloc memory");
344 static int argvalenum(int optc, struct enumdesc *desc)
349 const char *name = current_argument(optc);
352 while(desc[i].name && strcmp(desc[i].name, name))
358 len += strlen(desc[i++].name);
359 list = malloc(len + i + i);
361 ERROR("option [--%s] bad value (found %s)",
362 name_of_option(optc), name);
365 strcpy(list, desc[i].name ? : "");
366 while(desc[++i].name)
367 strcat(strcat(list, ", "), desc[i].name);
368 ERROR("option [--%s] bad value, only accepts values %s (found %s)",
369 name_of_option(optc), list, name);
374 return desc[i].value;
377 static int argvalint(int optc, int mini, int maxi, int base)
379 const char *beg, *end;
381 beg = current_argument(optc);
382 val = strtol(beg, (char**)&end, base);
383 if (*end || end == beg) {
384 ERROR("option [--%s] requires a valid integer (found %s)",
385 name_of_option(optc), beg);
388 if (val < (long int)mini || val > (long int)maxi) {
389 ERROR("option [--%s] value out of bounds (not %d<=%ld<=%d)",
390 name_of_option(optc), mini, val, maxi);
396 static int argvalintdec(int optc, int mini, int maxi)
398 return argvalint(optc, mini, maxi, 10);
401 static void noarg(int optc)
404 ERROR("option [--%s] need no value (found %s)", name_of_option(optc), optarg);
409 static char **make_exec(char **argv)
411 char **result, *iter;
416 for (i = 0 ; argv[i] ; i++)
417 length += strlen(argv[i]) + 1;
419 result = malloc(length + ((unsigned)(i + 1)) * sizeof *result);
420 if (result == NULL) {
421 ERROR("can't alloc memory");
425 iter = (char*)&result[i+1];
426 for (i = 0 ; argv[i] ; i++) {
428 iter = stpcpy(iter, argv[i]) + 1;
434 /*---------------------------------------------------------
435 | Parse option and launch action
436 +--------------------------------------------------------- */
438 static void parse_arguments(int argc, char **argv, struct afb_config *config)
440 char *programName = argv[0];
443 struct option *gnuOptions;
445 // ------------------ Process Command Line -----------------------
447 // build GNU getopt info from cliOptions
448 nbcmd = sizeof(cliOptions) / sizeof(AFB_options);
449 gnuOptions = malloc(sizeof(*gnuOptions) * (unsigned)nbcmd);
450 for (ind = 0; ind < nbcmd; ind++) {
451 gnuOptions[ind].name = cliOptions[ind].name;
452 gnuOptions[ind].has_arg = cliOptions[ind].has_arg;
453 gnuOptions[ind].flag = 0;
454 gnuOptions[ind].val = cliOptions[ind].val;
457 // get all options from command line
458 while ((optc = getopt_long(argc, argv, shortopts, gnuOptions, NULL)) != EOF) {
469 config->httpdPort = argvalintdec(optc, 1024, 32767);
473 config->apiTimeout = argvalintdec(optc, 0, INT_MAX);
476 case SET_CNTXTIMEOUT:
477 config->cntxTimeout = argvalintdec(optc, 0, INT_MAX);
481 config->rootdir = argvalstr(optc);
482 INFO("Forcing Rootdir=%s", config->rootdir);
486 config->roothttp = argvalstr(optc);
487 INFO("Forcing Root HTTP=%s", config->roothttp);
491 config->rootbase = argvalstr(optc);
492 INFO("Forcing Rootbase=%s", config->rootbase);
496 config->rootapi = argvalstr(optc);
497 INFO("Forcing Rootapi=%s", config->rootapi);
501 list_add(&config->aliases, argvalstr(optc));
505 config->token = argvalstr(optc);
509 list_add(&config->ldpaths, argvalstr(optc));
512 case SET_WEAK_LDPATH:
513 list_add(&config->weak_ldpaths, argvalstr(optc));
518 config->no_ldpaths = 1;
522 list_add(&config->calls, argvalstr(optc));
525 case SET_SESSION_DIR:
526 /* config->sessiondir = argvalstr(optc); */
527 WARNING("Obsolete option %s ignored", name_of_option(optc));
531 config->uploaddir = argvalstr(optc);
535 config->workdir = argvalstr(optc);
538 case SET_CACHE_TIMEOUT:
539 config->cacheTimeout = argvalintdec(optc, 0, INT_MAX);
543 config->nbSessionMax = argvalintdec(optc, 1, INT_MAX);
548 config->background = 0;
553 config->background = 1;
557 config->name = argvalstr(optc);
561 config->mode = argvalenum(optc, mode_desc);
565 list_add(&config->dbus_clients, argvalstr(optc));
569 list_add(&config->dbus_servers, argvalstr(optc));
573 list_add(&config->ws_clients, argvalstr(optc));
577 list_add(&config->ws_servers, argvalstr(optc));
581 list_add(&config->so_bindings, argvalstr(optc));
585 config->tracereq = argvalenum(optc, tracereq_desc);
589 config->traceditf = argvalenum(optc, traceditf_desc);
593 config->tracesvc = argvalenum(optc, tracesvc_desc);
597 config->traceevt = argvalenum(optc, traceevt_desc);
601 config->traceses = argvalenum(optc, traceses_desc);
610 config->exec = make_exec(&argv[optind]);
611 optind = argc; /* stop option scanning */
615 config->random_token = 1;
618 #if defined(WITH_MONITORING_OPTION)
620 config->monitoring = 1;
624 case DISPLAY_VERSION:
626 printVersion(stdout);
630 printHelp(stdout, programName);
640 static void fulfill_config(struct afb_config *config)
643 if (config->httpdPort == 0)
644 config->httpdPort = 1234;
646 // default binding API timeout
647 if (config->apiTimeout == 0)
648 config->apiTimeout = DEFLT_API_TIMEOUT;
650 // default AUTH_TOKEN
651 if (config->random_token)
652 config->token = NULL;
654 // cache timeout default one hour
655 if (config->cacheTimeout == 0)
656 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
658 // cache timeout default one hour
659 if (config->cntxTimeout == 0)
660 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
662 // max count of sessions
663 if (config->nbSessionMax == 0)
664 config->nbSessionMax = CTX_NBCLIENTS;
666 /* set directories */
667 if (config->workdir == NULL)
668 config->workdir = ".";
670 if (config->rootdir == NULL)
671 config->rootdir = ".";
673 if (config->uploaddir == NULL)
674 config->uploaddir = ".";
676 // if no Angular/HTML5 rootbase let's try '/' as default
677 if (config->rootbase == NULL)
678 config->rootbase = "/opa";
680 if (config->rootapi == NULL)
681 config->rootapi = "/api";
683 if (config->ldpaths == NULL && config->weak_ldpaths == NULL && !config->no_ldpaths)
684 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
686 #if defined(WITH_MONITORING_OPTION)
687 if (config->monitoring)
688 list_add(&config->aliases, strdup("/monitoring:"BINDING_INSTALL_DIR"/monitoring"));
691 // if no config dir create a default path from uploaddir
692 if (config->console == NULL) {
693 config->console = malloc(512);
694 strncpy(config->console, config->uploaddir, 512);
695 strncat(config->console, "/AFB-console.out", 512);
699 void afb_config_dump(struct afb_config *config)
701 struct afb_config_list *l;
705 #define NN(x) (x)?:""
706 #define P(...) fprintf(stderr, __VA_ARGS__)
707 #define PF(x) P("-- %15s: ", #x)
709 #define S(x) PF(x);P("%s",NN(config->x));PE;
710 #define D(x) PF(x);P("%d",config->x);PE;
711 #define B(x) PF(x);P("%s",config->x?"yes":"no");PE;
712 #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;
713 #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);}
714 #define V(x) P("-- %15s:", #x);for(v=config->x;v&&*v;v++)P(" %s",*v); PE;
716 P("---BEGIN-OF-CONFIG---\n");
746 E(tracereq,tracereq_desc)
747 E(traceditf,traceditf_desc)
748 E(tracesvc,tracesvc_desc)
749 E(traceevt,traceevt_desc)
750 E(traceses,traceses_desc)
755 #if defined(WITH_MONITORING_OPTION)
759 P("---END-OF-CONFIG---\n");
773 static void on_environment_list(struct afb_config_list **to, const char *name)
775 char *value = getenv(name);
781 static void on_environment_enum(int *to, const char *name, struct enumdesc *desc)
783 char *value = getenv(name);
787 if (strcmp(desc->name, value))
794 WARNING("Unknown value %s for environment variable %s, ignored", value, name);
798 static void parse_environment(struct afb_config *config)
800 on_environment_enum(&config->tracereq, "AFB_TRACEREQ", tracereq_desc);
801 on_environment_enum(&config->traceditf, "AFB_TRACEDITF", traceditf_desc);
802 on_environment_enum(&config->tracesvc, "AFB_TRACESVC", tracesvc_desc);
803 on_environment_enum(&config->traceevt, "AFB_TRACEEVT", traceevt_desc);
804 on_environment_enum(&config->traceses, "AFB_TRACESES", traceses_desc);
805 on_environment_list(&config->ldpaths, "AFB_LDPATHS");
808 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
810 struct afb_config *result;
812 result = calloc(1, sizeof *result);
814 parse_environment(result);
815 parse_arguments(argc, argv, result);
816 fulfill_config(result);
818 afb_config_dump(result);
822 struct json_object *afb_config_json(struct afb_config *config)
824 struct json_object *r, *a;
825 struct afb_config_list *l;
829 #define XA(t,o) json_object_array_add(t,o);
830 #define XO(t,x,o) json_object_object_add(t,x,o);
831 #define YS(s) ((s)?json_object_new_string(s):NULL)
833 #define AO(o) XA(a,o)
834 #define AS(s) AO(YS(s))
835 #define RO(x,o) XO(r,x,o)
836 #define RS(x,s) RO(x,YS(s))
837 #define RA(x) RO(x,(a=json_object_new_array()))
838 #define RI(x,i) RO(x,json_object_new_int(i))
839 #define RB(x,b) RO(x,json_object_new_boolean(b))
841 #define S(x) RS(#x,config->x)
842 #define V(x) RA(#x);for(v=config->x;v&&*v;v++)AS(*v);
843 #define L(x) RA(#x);for(l=config->x;l;l=l->next)AS(l->value);
844 #define D(x) RI(#x,config->x)
845 #define B(x) RB(#x,config->x)
846 #define E(x,d) for(e=d;e->name&&e->value!=config->x;e++);if(e->name){RS(#x,e->name);}else{D(x);}
848 r = json_object_new_object();
878 E(tracereq,tracereq_desc)
879 E(traceditf,traceditf_desc)
880 E(tracesvc,tracesvc_desc)
881 E(traceevt,traceevt_desc)
882 E(traceses,traceses_desc)
887 #if defined(WITH_MONITORING_OPTION)