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 NO_BINDING_VERBOSE_MACRO
28 #include <uuid/uuid.h>
31 #include "afb-config.h"
34 #include <afb/afb-binding.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
74 #define SET_READYFD 19
76 #define DBUS_CLIENT 20
77 #define DBUS_SERVICE 21
80 #define SET_SESSIONMAX 23
85 #define SET_ROOT_HTTP 26
87 #define SET_NO_HTTPD 28
90 #define DISPLAY_HELP 'h'
92 #define SET_RNDTOKEN 'r'
93 #define SET_TRACEREQ 'T'
94 #define SET_AUTH_TOKEN 't'
95 #define SET_UPLOAD_DIR 'u'
96 #define DISPLAY_VERSION 'V'
97 #define SET_VERBOSE 'v'
98 #define SET_WORK_DIR 'w'
100 #define SHORTOPTS "ehqrT:t:u:Vvw:"
102 // Command line structure hold cli --command + help text
104 int val; // command number within application
105 int has_arg; // command number within application
106 char *name; // command as used in --xxxx cli
107 char *help; // help text
111 static AFB_options cliOptions[] = {
113 {SET_VERBOSE, 0, "verbose", "Verbose Mode, repeat to increase verbosity"},
114 {SET_QUIET, 0, "quiet", "Quiet Mode, repeat to decrease verbosity"},
116 {SET_FORGROUND, 0, "foreground", "Get all in foreground mode"},
117 {SET_BACKGROUND, 0, "daemon", "Get all in background mode"},
119 {SET_TCP_PORT, 1, "port", "HTTP listening TCP port [default 1234]"},
120 {SET_ROOT_HTTP, 1, "roothttp", "HTTP Root Directory [default rootdir]"},
121 {SET_ROOT_BASE, 1, "rootbase", "Angular Base Root URL [default /opa]"},
122 {SET_ROOT_API, 1, "rootapi", "HTML Root API URL [default /api]"},
123 {SET_ALIAS, 1, "alias", "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
125 {SET_APITIMEOUT, 1, "apitimeout", "Binding API timeout in seconds [default 10]"},
126 {SET_CNTXTIMEOUT, 1, "cntxtimeout", "Client Session Context Timeout [default 900]"},
127 {SET_CACHE_TIMEOUT, 1, "cache-eol", "Client cache end of live [default 3600]"},
129 {SET_WORK_DIR, 1, "workdir", "Set the working directory [default: $PWD or current working directory]"},
130 {SET_UPLOAD_DIR, 1, "uploaddir", "Directory for uploading files [default: workdir]"},
131 {SET_ROOT_DIR, 1, "rootdir", "Root Directory of the application [default: workdir]"},
132 {SET_SESSION_DIR, 1, "sessiondir", "OBSOLETE (was: Sessions file path)"},
134 {SET_LDPATH, 1, "ldpaths", "Load bindings from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
135 {SO_BINDING, 1, "binding", "Load the binding of path"},
137 {SET_AUTH_TOKEN, 1, "token", "Initial Secret [default=no-session, --token= for session without authentication]"},
138 {SET_RNDTOKEN, 0, "random-token","Creates a random token"},
140 {DISPLAY_VERSION, 0, "version", "Display version and copyright"},
141 {DISPLAY_HELP, 0, "help", "Display this help"},
143 {SET_MODE, 1, "mode", "Set the mode: either local, remote or global"},
144 {SET_READYFD, 1, "readyfd", "Set the #fd to signal when ready"},
146 {DBUS_CLIENT, 1, "dbus-client", "Bind to an afb service through dbus"},
147 {DBUS_SERVICE, 1, "dbus-server", "Provides an afb service through dbus"},
148 {WS_CLIENT, 1, "ws-client", "Bind to an afb service through websocket"},
149 {WS_SERVICE, 1, "ws-server", "Provides an afb service through websockets"},
151 {SET_SESSIONMAX, 1, "session-max", "Max count of session simultaneously [default 10]"},
153 {SET_TRACEREQ, 1, "tracereq", "Log the requests: no, common, extra, all"},
155 {SET_NO_HTTPD, 0, "no-httpd", "Forbids HTTP service"},
156 {SET_EXEC, 0, "exec", "Execute the remaining arguments"},
169 static struct enumdesc tracereq_desc[] = {
171 { "common", afb_hook_flags_req_common },
172 { "extra", afb_hook_flags_req_extra },
173 { "all", afb_hook_flags_req_all },
177 static struct enumdesc mode_desc[] = {
178 { "local", AFB_MODE_LOCAL },
179 { "remote", AFB_MODE_REMOTE },
180 { "global", AFB_MODE_GLOBAL },
184 /*----------------------------------------------------------
186 | print version and copyright
187 +--------------------------------------------------------- */
188 static void printVersion(FILE * file)
190 fprintf(file, "\n----------------------------------------- \n");
191 fprintf(file, " AFB [Application Framework Binder] version=%s |\n",
193 fprintf(file, " \n");
195 " Copyright (C) 2015, 2016, 2017 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
196 fprintf(file, " AFB comes with ABSOLUTELY NO WARRANTY.\n");
197 fprintf(file, " Licence Apache 2\n\n");
200 /*----------------------------------------------------------
202 | print information from long option array
203 +--------------------------------------------------------- */
205 static void printHelp(FILE * file, const char *name)
210 fprintf(file, "%s:\nallowed options\n", name);
211 for (ind = 0; cliOptions[ind].name != NULL; ind++) {
212 strcpy(command, cliOptions[ind].name);
213 if (cliOptions[ind].has_arg)
214 strcat(command, "=xxxx");
215 fprintf(file, " --%-15s %s\n", command, cliOptions[ind].help);
218 "Example:\n %s --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
223 /*----------------------------------------------------------
224 | adds a string to the list
225 +--------------------------------------------------------- */
226 static char *random_token()
228 static char uuidstr[37];
230 uuid_generate_random(uuid);
231 uuid_unparse(uuid, uuidstr);
235 /*----------------------------------------------------------
236 | adds a string to the list
237 +--------------------------------------------------------- */
238 static void list_add(struct afb_config_list **head, char *value)
240 struct afb_config_list *item;
246 while (item != NULL) {
254 item = malloc(sizeof *item);
256 ERROR("out of memory");
268 /*---------------------------------------------------------
269 | helpers for argument scanning
270 +--------------------------------------------------------- */
272 static const char *optname(int optc)
274 AFB_options *o = cliOptions;
275 while (o->name && o->val != optc)
277 return o->name ? : "<unknown-option-name>";
280 static char *argvalstr(int optc)
283 ERROR("option [--%s] needs a value i.e. --%s=xxx",
284 optname(optc), optname(optc));
290 static int argvalenum(int optc, struct enumdesc *desc)
294 char *list, *name = argvalstr(optc);
297 while(desc[i].name && strcmp(desc[i].name, name))
303 len += strlen(desc[i++].name);
304 list = malloc(len + i + i);
306 ERROR("option [--%s] bad value (found %s)",
307 optname(optc), name);
310 strcpy(list, desc[i].name ? : "");
311 while(desc[++i].name)
312 strcat(strcat(list, ", "), desc[i].name);
313 ERROR("option [--%s] bad value, only accepts values %s (found %s)",
314 optname(optc), list, name);
319 return desc[i].value;
322 static int argvalint(int optc, int mini, int maxi, int base)
326 beg = argvalstr(optc);
327 val = strtol(beg, &end, base);
328 if (*end || end == beg) {
329 ERROR("option [--%s] requires a valid integer (found %s)",
333 if (val < (long int)mini || val > (long int)maxi) {
334 ERROR("option [--%s] value out of bounds (not %d<=%ld<=%d)",
335 optname(optc), mini, val, maxi);
341 static int argvalintdec(int optc, int mini, int maxi)
343 return argvalint(optc, mini, maxi, 10);
346 static void noarg(int optc)
349 ERROR("option [--%s] need no value (found %s)", optname(optc), optarg);
354 /*---------------------------------------------------------
355 | Parse option and launch action
356 +--------------------------------------------------------- */
358 static void parse_arguments(int argc, char **argv, struct afb_config *config)
360 char *programName = argv[0];
363 struct option *gnuOptions;
365 // ------------------ Process Command Line -----------------------
367 // build GNU getopt info from cliOptions
368 nbcmd = sizeof(cliOptions) / sizeof(AFB_options);
369 gnuOptions = malloc(sizeof(*gnuOptions) * (unsigned)nbcmd);
370 for (ind = 0; ind < nbcmd; ind++) {
371 gnuOptions[ind].name = cliOptions[ind].name;
372 gnuOptions[ind].has_arg = cliOptions[ind].has_arg;
373 gnuOptions[ind].flag = 0;
374 gnuOptions[ind].val = cliOptions[ind].val;
377 // get all options from command line
378 while ((optc = getopt_long(argc, argv, SHORTOPTS, gnuOptions, NULL)) != EOF) {
389 config->httpdPort = argvalintdec(optc, 1024, 32767);
393 config->apiTimeout = argvalintdec(optc, 0, INT_MAX);
396 case SET_CNTXTIMEOUT:
397 config->cntxTimeout = argvalintdec(optc, 0, INT_MAX);
401 config->rootdir = argvalstr(optc);
402 INFO("Forcing Rootdir=%s", config->rootdir);
406 config->roothttp = argvalstr(optc);
407 INFO("Forcing Root HTTP=%s", config->roothttp);
411 config->rootbase = argvalstr(optc);
412 INFO("Forcing Rootbase=%s", config->rootbase);
416 config->rootapi = argvalstr(optc);
417 INFO("Forcing Rootapi=%s", config->rootapi);
421 list_add(&config->aliases, argvalstr(optc));
425 config->token = argvalstr(optc);
429 list_add(&config->ldpaths, argvalstr(optc));
432 case SET_SESSION_DIR:
433 /* config->sessiondir = argvalstr(optc); */
434 WARNING("Obsolete otpion %s ignored", optname(optc));
438 config->uploaddir = argvalstr(optc);
442 config->workdir = argvalstr(optc);
445 case SET_CACHE_TIMEOUT:
446 config->cacheTimeout = argvalintdec(optc, 0, INT_MAX);
450 config->nbSessionMax = argvalintdec(optc, 1, INT_MAX);
455 config->background = 0;
460 config->background = 1;
464 config->mode = argvalenum(optc, mode_desc);
468 config->readyfd = argvalintdec(optc, 0, INT_MAX);
472 list_add(&config->dbus_clients, argvalstr(optc));
476 list_add(&config->dbus_servers, argvalstr(optc));
480 list_add(&config->ws_clients, argvalstr(optc));
484 list_add(&config->ws_servers, argvalstr(optc));
488 list_add(&config->so_bindings, argvalstr(optc));
492 config->tracereq = argvalenum(optc, tracereq_desc);
501 config->exec = &argv[optind];
506 config->token = random_token();
509 case DISPLAY_VERSION:
511 printVersion(stdout);
515 printHelp(stdout, programName);
525 // load config from disk and merge with CLI option
526 static void config_set_default(struct afb_config *config)
529 if (config->httpdPort == 0)
530 config->httpdPort = 1234;
532 // default binding API timeout
533 if (config->apiTimeout == 0)
534 config->apiTimeout = DEFLT_API_TIMEOUT;
536 // default AUTH_TOKEN
537 if (config->token == NULL)
538 config->token = DEFLT_AUTH_TOKEN;
540 // cache timeout default one hour
541 if (config->cacheTimeout == 0)
542 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
544 // cache timeout default one hour
545 if (config->cntxTimeout == 0)
546 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
548 // max count of sessions
549 if (config->nbSessionMax == 0)
550 config->nbSessionMax = CTX_NBCLIENTS;
552 /* set directories */
553 if (config->workdir == NULL)
554 config->workdir = get_current_dir_name();
556 if (config->rootdir == NULL)
557 config->rootdir = config->workdir;
559 if (config->uploaddir == NULL)
560 config->uploaddir = config->workdir;
562 // if no Angular/HTML5 rootbase let's try '/' as default
563 if (config->rootbase == NULL)
564 config->rootbase = "/opa";
566 if (config->rootapi == NULL)
567 config->rootapi = "/api";
569 if (config->ldpaths == NULL)
570 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
572 // if no config dir create a default path from uploaddir
573 if (config->console == NULL) {
574 config->console = malloc(512);
575 strncpy(config->console, config->uploaddir, 512);
576 strncat(config->console, "/AFB-console.out", 512);
580 void afb_config_dump(struct afb_config *config)
582 struct afb_config_list *l;
586 #define NN(x) (x)?:""
587 #define P(...) fprintf(stderr, __VA_ARGS__)
588 #define PF(x) P("-- %15s: ", #x)
590 #define S(x) PF(x);P("%s",NN(config->x));PE;
591 #define D(x) PF(x);P("%d",config->x);PE;
592 #define H(x) PF(x);P("%x",config->x);PE;
593 #define B(x) PF(x);P("%s",config->x?"yes":"no");PE;
594 #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;
595 #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);}
596 #define V(x) P("-- %15s:", #x);for(v=config->x;v&&*v;v++)P(" %s",*v); PE;
598 P("---BEGIN-OF-CONFIG---\n");
626 E(tracereq,tracereq_desc)
628 P("---END-OF-CONFIG---\n");
643 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
645 struct afb_config *result;
647 result = calloc(1, sizeof *result);
649 parse_arguments(argc, argv, result);
650 config_set_default(result);
652 afb_config_dump(result);