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.
19 #define AFB_BINDING_PRAGMA_NO_VERBOSE_MACRO
28 #include <uuid/uuid.h>
31 #include "afb-config.h"
34 #include <afb/afb-binding-v1.h>
36 #if !defined(BINDING_INSTALL_DIR)
37 #error "you should define BINDING_INSTALL_DIR"
40 #define AFB_VERSION "0.6"
43 #define DEFLT_CNTX_TIMEOUT 3600 // default Client Connection
45 #define DEFLT_API_TIMEOUT 20 // default Plugin API Timeout [0=NoLimit
47 #define DEFLT_CACHE_TIMEOUT 100000 // default Static File Chache
50 #define DEFLT_AUTH_TOKEN NULL // expect for debug should == NULL
51 #define CTX_NBCLIENTS 10 // allow a default of 10 authenticated
55 // Define command line option
56 #define SET_BACKGROUND 2
57 #define SET_FORGROUND 3
59 #define SET_TCP_PORT 5
60 #define SET_ROOT_DIR 6
61 #define SET_ROOT_BASE 7
62 #define SET_ROOT_API 8
65 #define SET_CACHE_TIMEOUT 10
66 #define SET_SESSION_DIR 11
69 #define SET_APITIMEOUT 14
70 #define SET_CNTXTIMEOUT 15
75 #define DBUS_CLIENT 20
76 #define DBUS_SERVICE 21
79 #define SET_SESSIONMAX 23
84 #define SET_ROOT_HTTP 26
86 #define SET_NO_HTTPD 28
89 #define SET_TRACEDITF 'D'
90 #define SET_TRACEEVT 'E'
92 #define DISPLAY_HELP 'h'
94 #define SET_RNDTOKEN 'r'
95 #define SET_TRACESVC 'S'
96 #define SET_TRACEREQ 'T'
97 #define SET_AUTH_TOKEN 't'
98 #define SET_UPLOAD_DIR 'u'
99 #define DISPLAY_VERSION 'V'
100 #define SET_VERBOSE 'v'
101 #define SET_WORK_DIR 'w'
103 #define SHORTOPTS "c:D:E:ehqrT:t:u:Vvw:"
105 // Command line structure hold cli --command + help text
107 int val; // command number within application
108 int has_arg; // command number within application
109 char *name; // command as used in --xxxx cli
110 char *help; // help text
114 static AFB_options cliOptions[] = {
116 {SET_VERBOSE, 0, "verbose", "Verbose Mode, repeat to increase verbosity"},
117 {SET_QUIET, 0, "quiet", "Quiet Mode, repeat to decrease verbosity"},
119 {SET_FORGROUND, 0, "foreground", "Get all in foreground mode"},
120 {SET_BACKGROUND, 0, "daemon", "Get all in background mode"},
122 {SET_TCP_PORT, 1, "port", "HTTP listening TCP port [default 1234]"},
123 {SET_ROOT_HTTP, 1, "roothttp", "HTTP Root Directory [default no root http (files not served but apis still available)]"},
124 {SET_ROOT_BASE, 1, "rootbase", "Angular Base Root URL [default /opa]"},
125 {SET_ROOT_API, 1, "rootapi", "HTML Root API URL [default /api]"},
126 {SET_ALIAS, 1, "alias", "Multiple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
128 {SET_APITIMEOUT, 1, "apitimeout", "Binding API timeout in seconds [default 10]"},
129 {SET_CNTXTIMEOUT, 1, "cntxtimeout", "Client Session Context Timeout [default 900]"},
130 {SET_CACHE_TIMEOUT, 1, "cache-eol", "Client cache end of live [default 3600]"},
132 {SET_WORK_DIR, 1, "workdir", "Set the working directory [default: $PWD or current working directory]"},
133 {SET_UPLOAD_DIR, 1, "uploaddir", "Directory for uploading files [default: workdir]"},
134 {SET_ROOT_DIR, 1, "rootdir", "Root Directory of the application [default: workdir]"},
135 {SET_SESSION_DIR, 1, "sessiondir", "OBSOLETE (was: Sessions file path)"},
137 {SET_LDPATH, 1, "ldpaths", "Load bindings from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
138 {SO_BINDING, 1, "binding", "Load the binding of path"},
140 {SET_AUTH_TOKEN, 1, "token", "Initial Secret [default=no-session, --token= for session without authentication]"},
141 {SET_RNDTOKEN, 0, "random-token","Creates a random token"},
143 {DISPLAY_VERSION, 0, "version", "Display version and copyright"},
144 {DISPLAY_HELP, 0, "help", "Display this help"},
146 {SET_MODE, 1, "mode", "Set the mode: either local, remote or global"},
148 {DBUS_CLIENT, 1, "dbus-client", "Bind to an afb service through dbus"},
149 {DBUS_SERVICE, 1, "dbus-server", "Provides an afb service through dbus"},
150 {WS_CLIENT, 1, "ws-client", "Bind to an afb service through websocket"},
151 {WS_SERVICE, 1, "ws-server", "Provides an afb service through websockets"},
153 {SET_SESSIONMAX, 1, "session-max", "Max count of session simultaneously [default 10]"},
155 {SET_TRACEREQ, 1, "tracereq", "Log the requests: no, common, extra, all"},
156 {SET_TRACEDITF, 1, "traceditf", "Log the requests: no, common, extra, all"},
157 {SET_TRACESVC, 1, "tracesvc", "Log the requests: no, all"},
158 {SET_TRACEEVT, 1, "traceevt", "Log the requests: no, common, extra, all"},
160 {ADD_CALL, 1, "call", "call at start format of val: API/VERB:json-args"},
162 {SET_NO_HTTPD, 0, "no-httpd", "Forbids HTTP service"},
163 {SET_EXEC, 0, "exec", "Execute the remaining arguments"},
176 static struct enumdesc tracereq_desc[] = {
178 { "common", afb_hook_flags_req_common },
179 { "extra", afb_hook_flags_req_extra },
180 { "all", afb_hook_flags_req_all },
184 static struct enumdesc traceditf_desc[] = {
186 { "common", afb_hook_flags_ditf_common },
187 { "extra", afb_hook_flags_ditf_extra },
188 { "all", afb_hook_flags_ditf_all },
192 static struct enumdesc tracesvc_desc[] = {
194 { "all", afb_hook_flags_svc_all },
198 static struct enumdesc traceevt_desc[] = {
200 { "common", afb_hook_flags_evt_common },
201 { "extra", afb_hook_flags_evt_extra },
202 { "all", afb_hook_flags_evt_all },
206 static struct enumdesc mode_desc[] = {
207 { "local", AFB_MODE_LOCAL },
208 { "remote", AFB_MODE_REMOTE },
209 { "global", AFB_MODE_GLOBAL },
213 /*----------------------------------------------------------
215 | print version and copyright
216 +--------------------------------------------------------- */
217 static void printVersion(FILE * file)
219 fprintf(file, "\n----------------------------------------- \n");
220 fprintf(file, " AFB [Application Framework Binder] version=%s |\n",
222 fprintf(file, " \n");
224 " Copyright (C) 2015, 2016, 2017 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
225 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
226 fprintf(file, " Licence Apache 2\n\n");
229 /*----------------------------------------------------------
231 | print information from long option array
232 +--------------------------------------------------------- */
234 static void printHelp(FILE * file, const char *name)
239 fprintf(file, "%s:\nallowed options\n", name);
240 for (ind = 0; cliOptions[ind].name != NULL; ind++) {
241 strcpy(command, cliOptions[ind].name);
242 if (cliOptions[ind].has_arg)
243 strcat(command, "=xxxx");
244 fprintf(file, " --%-15s %s\n", command, cliOptions[ind].help);
247 "Example:\n %s --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
252 /*----------------------------------------------------------
253 | adds a string to the list
254 +--------------------------------------------------------- */
255 static char *random_token()
257 static char uuidstr[37];
259 uuid_generate_random(uuid);
260 uuid_unparse(uuid, uuidstr);
264 /*----------------------------------------------------------
265 | adds a string to the list
266 +--------------------------------------------------------- */
267 static void list_add(struct afb_config_list **head, char *value)
269 struct afb_config_list *item;
275 while (item != NULL) {
283 item = malloc(sizeof *item);
285 ERROR("out of memory");
297 /*---------------------------------------------------------
298 | helpers for argument scanning
299 +--------------------------------------------------------- */
301 static const char *optname(int optc)
303 AFB_options *o = cliOptions;
304 while (o->name && o->val != optc)
306 return o->name ? : "<unknown-option-name>";
309 static char *argvalstr(int optc)
312 ERROR("option [--%s] needs a value i.e. --%s=xxx",
313 optname(optc), optname(optc));
319 static int argvalenum(int optc, struct enumdesc *desc)
323 char *list, *name = argvalstr(optc);
326 while(desc[i].name && strcmp(desc[i].name, name))
332 len += strlen(desc[i++].name);
333 list = malloc(len + i + i);
335 ERROR("option [--%s] bad value (found %s)",
336 optname(optc), name);
339 strcpy(list, desc[i].name ? : "");
340 while(desc[++i].name)
341 strcat(strcat(list, ", "), desc[i].name);
342 ERROR("option [--%s] bad value, only accepts values %s (found %s)",
343 optname(optc), list, name);
348 return desc[i].value;
351 static int argvalint(int optc, int mini, int maxi, int base)
355 beg = argvalstr(optc);
356 val = strtol(beg, &end, base);
357 if (*end || end == beg) {
358 ERROR("option [--%s] requires a valid integer (found %s)",
362 if (val < (long int)mini || val > (long int)maxi) {
363 ERROR("option [--%s] value out of bounds (not %d<=%ld<=%d)",
364 optname(optc), mini, val, maxi);
370 static int argvalintdec(int optc, int mini, int maxi)
372 return argvalint(optc, mini, maxi, 10);
375 static void noarg(int optc)
378 ERROR("option [--%s] need no value (found %s)", optname(optc), optarg);
383 /*---------------------------------------------------------
384 | Parse option and launch action
385 +--------------------------------------------------------- */
387 static void parse_arguments(int argc, char **argv, struct afb_config *config)
389 char *programName = argv[0];
392 struct option *gnuOptions;
394 // ------------------ Process Command Line -----------------------
396 // build GNU getopt info from cliOptions
397 nbcmd = sizeof(cliOptions) / sizeof(AFB_options);
398 gnuOptions = malloc(sizeof(*gnuOptions) * (unsigned)nbcmd);
399 for (ind = 0; ind < nbcmd; ind++) {
400 gnuOptions[ind].name = cliOptions[ind].name;
401 gnuOptions[ind].has_arg = cliOptions[ind].has_arg;
402 gnuOptions[ind].flag = 0;
403 gnuOptions[ind].val = cliOptions[ind].val;
406 // get all options from command line
407 while ((optc = getopt_long(argc, argv, SHORTOPTS, gnuOptions, NULL)) != EOF) {
418 config->httpdPort = argvalintdec(optc, 1024, 32767);
422 config->apiTimeout = argvalintdec(optc, 0, INT_MAX);
425 case SET_CNTXTIMEOUT:
426 config->cntxTimeout = argvalintdec(optc, 0, INT_MAX);
430 config->rootdir = argvalstr(optc);
431 INFO("Forcing Rootdir=%s", config->rootdir);
435 config->roothttp = argvalstr(optc);
436 INFO("Forcing Root HTTP=%s", config->roothttp);
440 config->rootbase = argvalstr(optc);
441 INFO("Forcing Rootbase=%s", config->rootbase);
445 config->rootapi = argvalstr(optc);
446 INFO("Forcing Rootapi=%s", config->rootapi);
450 list_add(&config->aliases, argvalstr(optc));
454 config->token = argvalstr(optc);
458 list_add(&config->ldpaths, argvalstr(optc));
462 list_add(&config->calls, argvalstr(optc));
465 case SET_SESSION_DIR:
466 /* config->sessiondir = argvalstr(optc); */
467 WARNING("Obsolete otpion %s ignored", optname(optc));
471 config->uploaddir = argvalstr(optc);
475 config->workdir = argvalstr(optc);
478 case SET_CACHE_TIMEOUT:
479 config->cacheTimeout = argvalintdec(optc, 0, INT_MAX);
483 config->nbSessionMax = argvalintdec(optc, 1, INT_MAX);
488 config->background = 0;
493 config->background = 1;
497 config->mode = argvalenum(optc, mode_desc);
501 list_add(&config->dbus_clients, argvalstr(optc));
505 list_add(&config->dbus_servers, argvalstr(optc));
509 list_add(&config->ws_clients, argvalstr(optc));
513 list_add(&config->ws_servers, argvalstr(optc));
517 list_add(&config->so_bindings, argvalstr(optc));
521 config->tracereq = argvalenum(optc, tracereq_desc);
525 config->traceditf = argvalenum(optc, traceditf_desc);
529 config->tracesvc = argvalenum(optc, tracesvc_desc);
533 config->traceevt = argvalenum(optc, traceevt_desc);
542 config->exec = &argv[optind];
547 config->token = random_token();
550 case DISPLAY_VERSION:
552 printVersion(stdout);
556 printHelp(stdout, programName);
566 // load config from disk and merge with CLI option
567 static void config_set_default(struct afb_config *config)
570 if (config->httpdPort == 0)
571 config->httpdPort = 1234;
573 // default binding API timeout
574 if (config->apiTimeout == 0)
575 config->apiTimeout = DEFLT_API_TIMEOUT;
577 // default AUTH_TOKEN
578 if (config->token == NULL)
579 config->token = DEFLT_AUTH_TOKEN;
581 // cache timeout default one hour
582 if (config->cacheTimeout == 0)
583 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
585 // cache timeout default one hour
586 if (config->cntxTimeout == 0)
587 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
589 // max count of sessions
590 if (config->nbSessionMax == 0)
591 config->nbSessionMax = CTX_NBCLIENTS;
593 /* set directories */
594 if (config->workdir == NULL)
595 config->workdir = ".";
597 if (config->rootdir == NULL)
598 config->rootdir = ".";
600 if (config->uploaddir == NULL)
601 config->uploaddir = ".";
603 // if no Angular/HTML5 rootbase let's try '/' as default
604 if (config->rootbase == NULL)
605 config->rootbase = "/opa";
607 if (config->rootapi == NULL)
608 config->rootapi = "/api";
610 if (config->ldpaths == NULL)
611 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
613 // if no config dir create a default path from uploaddir
614 if (config->console == NULL) {
615 config->console = malloc(512);
616 strncpy(config->console, config->uploaddir, 512);
617 strncat(config->console, "/AFB-console.out", 512);
621 void afb_config_dump(struct afb_config *config)
623 struct afb_config_list *l;
627 #define NN(x) (x)?:""
628 #define P(...) fprintf(stderr, __VA_ARGS__)
629 #define PF(x) P("-- %15s: ", #x)
631 #define S(x) PF(x);P("%s",NN(config->x));PE;
632 #define D(x) PF(x);P("%d",config->x);PE;
633 #define H(x) PF(x);P("%x",config->x);PE;
634 #define B(x) PF(x);P("%s",config->x?"yes":"no");PE;
635 #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;
636 #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);}
637 #define V(x) P("-- %15s:", #x);for(v=config->x;v&&*v;v++)P(" %s",*v); PE;
639 P("---BEGIN-OF-CONFIG---\n");
667 E(tracereq,tracereq_desc)
668 E(traceditf,traceditf_desc)
670 P("---END-OF-CONFIG---\n");
685 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
687 struct afb_config *result;
689 result = calloc(1, sizeof *result);
691 parse_arguments(argc, argv, result);
692 config_set_default(result);
694 afb_config_dump(result);