aa223e60423f5ff2aee6fdb09d091ce9b62030f0
[src/app-framework-binder.git] / src / afb-config.c
1 /*
2  * Copyright (C) 2015-2018 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
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
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <getopt.h>
24 #include <limits.h>
25 #include <unistd.h>
26 #include <ctype.h>
27
28 #include <json-c/json.h>
29
30 #include "verbose.h"
31 #include "afb-config.h"
32 #include "afb-hook.h"
33
34 #define _d2s_(x)  #x
35 #define d2s(x)    _d2s_(x)
36
37 #if !defined(BINDING_INSTALL_DIR)
38 #error "you should define BINDING_INSTALL_DIR"
39 #endif
40 #if !defined(AFB_VERSION)
41 #error "you should define AFB_VERSION"
42 #endif
43
44 /* set the HAS_ options */
45 #if defined(WITH_MONITORING_OPTION)
46 #   define HAS_MONITORING 1
47 #else
48 #   define HAS_MONITORING 0
49 #endif
50 #if defined(WITH_DBUS_TRANSPARENCY)
51 #   define HAS_DBUS 1
52 #else
53 #   define HAS_DBUS 0
54 #endif
55
56 /**
57  * The default timeout of sessions in seconds
58  */
59 #define DEFAULT_SESSION_TIMEOUT         32000000
60
61 /**
62  * The default timeout of api calls in seconds
63  */
64 #define DEFAULT_API_TIMEOUT             20
65
66 /**
67  * The default timeout of cache in seconds
68  */
69 #define DEFAULT_CACHE_TIMEOUT           100000
70
71 /**
72  * The default maximum count of sessions
73  */
74 #define DEFAULT_MAX_SESSION_COUNT       200
75
76 /**
77  * The default HTTP port to serve
78  */
79 #define DEFAULT_HTTP_PORT               1234
80
81
82
83
84
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
91 #define SET_ALIAS          6
92
93 #define SET_CACHE_TIMEOUT  7
94
95 #define AUTO_WS            8
96 #define AUTO_LINK          9
97
98 #define SET_LDPATH         10
99 #define SET_APITIMEOUT     11
100 #define SET_CNTXTIMEOUT    12
101 #define SET_WEAK_LDPATH    13
102 #define NO_LDPATH          14
103
104 #define SET_SESSIONMAX     15
105
106 #define WS_CLIENT          16
107 #define WS_SERVICE         17
108
109 #define SET_ROOT_HTTP      18
110
111 #define SET_NO_HTTPD       19
112
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
120 #endif
121
122 #if HAS_DBUS
123 #   define DBUS_CLIENT        30
124 #   define DBUS_SERVICE       31
125 #endif
126
127
128 #define AUTO_API           'A'
129 #define SO_BINDING         'b'
130 #define ADD_CALL           'c'
131 #define SET_EXEC           'e'
132 #define DISPLAY_HELP       'h'
133 #define SET_LOG            'l'
134 #if HAS_MONITORING
135 #define SET_MONITORING     'M'
136 #endif
137 #define SET_NAME           'n'
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'
146
147 const char shortopts[] =
148         "A:"
149         "b:"
150         "c:"
151         "e"
152         "h"
153         "l:"
154 #if HAS_MONITORING
155         "M"
156 #endif
157         "n:"
158         "p:"
159         "q"
160         "r"
161         "t:"
162         "u:"
163         "V"
164         "v"
165         "w:"
166 ;
167
168 // Command line structure hold cli --command + help text
169 typedef struct {
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
174 } AFB_options;
175
176 // Supported option
177 static AFB_options cliOptions[] = {
178 /* *INDENT-OFF* */
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"},
182
183         {SET_FORGROUND,     0, "foreground",  "Get all in foreground mode"},
184         {SET_BACKGROUND,    0, "daemon",      "Get all in background mode"},
185
186         {SET_NAME,          1, "name",        "Set the visible name"},
187
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]"},
193
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) "]"},
197
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]"},
201
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"},
206
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"},
209
210         {DISPLAY_VERSION,   0, "version",     "Display version and copyright"},
211         {DISPLAY_HELP,      0, "help",        "Display this help"},
212
213 #if HAS_DBUS
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"},
216 #endif
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"},
219
220         {AUTO_API,          1, "auto-api",    "Automatic load of api of the given directory"},
221
222         {SET_SESSIONMAX,    1, "session-max", "Max count of session simultaneously [default " d2s(DEFAULT_MAX_SESSION_COUNT) "]"},
223
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"},
228 #endif
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"},
232
233         {ADD_CALL,          1, "call",        "call at start format of val: API/VERB:json-args"},
234
235         {SET_NO_HTTPD,      0, "no-httpd",    "Forbid HTTP service"},
236         {SET_EXEC,          0, "exec",        "Execute the remaining arguments"},
237
238 #if HAS_MONITORING
239         {SET_MONITORING,    0, "monitoring",  "Enable HTTP monitoring at <ROOT>/monitoring/"},
240 #endif
241         {0, 0, NULL, NULL}
242 /* *INDENT-ON* */
243 };
244
245
246 struct enumdesc
247 {
248         const char *name;
249         int value;
250 };
251
252 static struct enumdesc tracereq_desc[] = {
253         { "no",     0 },
254         { "common", afb_hook_flags_req_common },
255         { "extra",  afb_hook_flags_req_extra },
256         { "all",    afb_hook_flags_req_all },
257         { NULL, 0 }
258 };
259
260 #if !defined(REMOVE_LEGACY_TRACE)
261 static struct enumdesc traceditf_desc[] = {
262         { "no",     0 },
263         { "common", afb_hook_flags_api_ditf_common },
264         { "all",    afb_hook_flags_api_ditf_all },
265         { NULL, 0 }
266 };
267
268 static struct enumdesc tracesvc_desc[] = {
269         { "no",     0 },
270         { "all",    afb_hook_flags_api_svc_all },
271         { NULL, 0 }
272 };
273 #endif
274
275 static struct enumdesc traceevt_desc[] = {
276         { "no",     0 },
277         { "common", afb_hook_flags_evt_common },
278         { "extra",  afb_hook_flags_evt_extra },
279         { "all",    afb_hook_flags_evt_all },
280         { NULL, 0 }
281 };
282
283 static struct enumdesc traceses_desc[] = {
284         { "no",     0 },
285         { "common", afb_hook_flags_session_common },
286         { "all",    afb_hook_flags_session_all },
287         { NULL, 0 }
288 };
289
290 static struct enumdesc traceapi_desc[] = {
291         { "no",         0 },
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 },
296         { NULL, 0 }
297 };
298
299 /*----------------------------------------------------------
300  | printversion
301  |   print version and copyright
302  +--------------------------------------------------------- */
303 static void printVersion(FILE * file)
304 {
305         static char pm[2] = { '-', '+' };
306         fprintf(file,
307                 "\n"
308                 "  AGL Framework Binder [AFB %s] %cDBUS %cMONITOR\n"
309                 "\n",
310                         AFB_VERSION,
311                         pm[HAS_DBUS],
312                         pm[HAS_MONITORING]
313                 );
314         fprintf(file,
315                 "  Copyright (C) 2015-2018 \"IoT.bzh\"\n"
316                 "  AFB comes with ABSOLUTELY NO WARRANTY.\n"
317                 "  Licence Apache 2\n"
318                 "\n");
319 }
320
321 /*----------------------------------------------------------
322  | printHelp
323  |   print information from long option array
324  +--------------------------------------------------------- */
325
326 static void printHelp(FILE * file, const char *name)
327 {
328         int ind;
329         char command[50], sht[4];
330
331         sht[3] = 0;
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)) {
338                         sht[0] = '-';
339                         sht[1] = (char)cliOptions[ind].val;
340                         sht[2] = ',';
341                 } else {
342                         sht[0] = sht[1] = sht[2] = ' ';
343                 }
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);
348         }
349         fprintf(file,
350                 "Example:\n  %s  --verbose --port=" d2s(DEFAULT_HTTP_PORT) " --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
351                 name);
352 }
353
354
355 /*----------------------------------------------------------
356  |   adds a string to the list
357  +--------------------------------------------------------- */
358 static void list_add(struct afb_config_list **head, char *value)
359 {
360         struct afb_config_list *item;
361
362         /*
363          * search tail
364          */
365         item = *head;
366         while (item != NULL) {
367                 head = &item->next;
368                 item = item->next;
369         }
370
371         /*
372          * alloc the item
373          */
374         item = malloc(sizeof *item);
375         if (item == NULL) {
376                 ERROR("out of memory");
377                 exit(1);
378         }
379
380         /*
381          * init the item
382          */
383         *head = item;
384         item->value = value;
385         item->next = NULL;
386 }
387
388 /*---------------------------------------------------------
389  |   helpers for argument scanning
390  +--------------------------------------------------------- */
391
392 static const char *name_of_option(int optc)
393 {
394         AFB_options *o = cliOptions;
395         while (o->name && o->val != optc)
396                 o++;
397         return o->name ? : "<unknown-option-name>";
398 }
399
400 static const char *current_argument(int optc)
401 {
402         if (optarg == 0) {
403                 ERROR("option [--%s] needs a value i.e. --%s=xxx",
404                       name_of_option(optc), name_of_option(optc));
405                 exit(1);
406         }
407         return optarg;
408 }
409
410 static char *argvalstr(int optc)
411 {
412         char *result = strdup(current_argument(optc));
413         if (result == NULL) {
414                 ERROR("can't alloc memory");
415                 exit(1);
416         }
417         return result;
418 }
419
420 static int argvalenum(int optc, struct enumdesc *desc)
421 {
422         int i;
423         size_t len;
424         char *list;
425         const char *name = current_argument(optc);
426
427         i = 0;
428         while(desc[i].name && strcmp(desc[i].name, name))
429                 i++;
430         if (!desc[i].name) {
431                 len = 0;
432                 i = 0;
433                 while(desc[i].name)
434                         len += strlen(desc[i++].name);
435                 list = malloc(len + i + i);
436                 if (!i || !list)
437                         ERROR("option [--%s] bad value (found %s)",
438                                 name_of_option(optc), name);
439                 else {
440                         i = 0;
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);
446                 }
447                 free(list);
448                 exit(1);
449         }
450         return desc[i].value;
451 }
452
453 static int argvalint(int optc, int mini, int maxi, int base)
454 {
455         const char *beg, *end;
456         long int val;
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);
462                 exit(1);
463         }
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);
467                 exit(1);
468         }
469         return (int)val;
470 }
471
472 static int argvalintdec(int optc, int mini, int maxi)
473 {
474         return argvalint(optc, mini, maxi, 10);
475 }
476
477 static void noarg(int optc)
478 {
479         if (optarg != 0) {
480                 ERROR("option [--%s] need no value (found %s)", name_of_option(optc), optarg);
481                 exit(1);
482         }
483 }
484
485 static char **make_exec(char **argv)
486 {
487         char **result, *iter;
488         size_t length;
489         int i;
490
491         length = 0;
492         for (i = 0 ; argv[i] ; i++)
493                 length += strlen(argv[i]) + 1;
494
495         result = malloc(length + ((unsigned)(i + 1)) * sizeof *result);
496         if (result == NULL) {
497                 ERROR("can't alloc memory");
498                 exit(1);
499         }
500
501         iter = (char*)&result[i+1];
502         for (i = 0 ; argv[i] ; i++) {
503                 result[i] = iter;
504                 iter = stpcpy(iter, argv[i]) + 1;
505         }
506         result[i] = NULL;
507         return result;
508 }
509
510 /*---------------------------------------------------------
511  |   set the log levels
512  +--------------------------------------------------------- */
513
514 static void set_log(char *args)
515 {
516         char o = 0, s, *p, *i = args;
517         int lvl;
518
519         for(;;) switch (*i) {
520         case 0:
521                 return;
522         case '+':
523         case '-':
524                 o = *i;
525                 /*@fallthrough@*/
526         case ' ':
527         case ',':
528                 i++;
529                 break;
530         default:
531                 p = i;
532                 while (isalpha(*p)) p++;
533                 s = *p;
534                 *p = 0;
535                 lvl = verbose_level_of_name(i);
536                 if (lvl < 0) {
537                         i = strdupa(p);
538                         *p = s;
539                         ERROR("Bad log name '%s' in %s", i, args);
540                         exit(1);
541                 }
542                 *p = s;
543                 i = p;
544                 if (o == '-')
545                         verbose_sub(lvl);
546                 else {
547                         if (!o) {
548                                 verbose_clear();
549                                 o = '+';
550                         }
551                         verbose_add(lvl);
552                 }
553                 break;
554         }
555 }
556
557 /*---------------------------------------------------------
558  |   Parse option and launch action
559  +--------------------------------------------------------- */
560
561 static void parse_arguments(int argc, char **argv, struct afb_config *config)
562 {
563         char *programName = argv[0];
564         int optc, ind;
565         int nbcmd;
566         struct option *gnuOptions;
567
568         // ------------------ Process Command Line -----------------------
569
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;
578         }
579
580         // get all options from command line
581         while ((optc = getopt_long(argc, argv, shortopts, gnuOptions, NULL)) != EOF) {
582                 switch (optc) {
583                 case SET_VERBOSE:
584                         verbose_inc();
585                         break;
586
587                 case SET_QUIET:
588                         verbose_dec();
589                         break;
590
591                 case SET_LOG:
592                         set_log(argvalstr(optc));
593                         break;
594
595                 case SET_TCP_PORT:
596                         config->http_port = argvalintdec(optc, 1024, 32767);
597                         break;
598
599                 case SET_APITIMEOUT:
600                         config->api_timeout = argvalintdec(optc, 0, INT_MAX);
601                         break;
602
603                 case SET_CNTXTIMEOUT:
604                         config->session_timeout = argvalintdec(optc, 0, INT_MAX);
605                         break;
606
607                 case SET_ROOT_DIR:
608                         config->rootdir = argvalstr(optc);
609                         INFO("Forcing Rootdir=%s", config->rootdir);
610                         break;
611
612                 case SET_ROOT_HTTP:
613                         config->roothttp = argvalstr(optc);
614                         INFO("Forcing Root HTTP=%s", config->roothttp);
615                         break;
616
617                 case SET_ROOT_BASE:
618                         config->rootbase = argvalstr(optc);
619                         INFO("Forcing Rootbase=%s", config->rootbase);
620                         break;
621
622                 case SET_ROOT_API:
623                         config->rootapi = argvalstr(optc);
624                         INFO("Forcing Rootapi=%s", config->rootapi);
625                         break;
626
627                 case SET_ALIAS:
628                         list_add(&config->aliases, argvalstr(optc));
629                         break;
630
631                 case SET_AUTH_TOKEN:
632                         config->token = argvalstr(optc);
633                         break;
634
635                 case SET_LDPATH:
636                         list_add(&config->ldpaths, argvalstr(optc));
637                         break;
638
639                 case SET_WEAK_LDPATH:
640                         list_add(&config->weak_ldpaths, argvalstr(optc));
641                         break;
642
643                 case NO_LDPATH:
644                         noarg(optc);
645                         config->no_ldpaths = 1;
646                         break;
647
648                 case ADD_CALL:
649                         list_add(&config->calls, argvalstr(optc));
650                         break;
651
652                 case SET_UPLOAD_DIR:
653                         config->uploaddir = argvalstr(optc);
654                         break;
655
656                 case SET_WORK_DIR:
657                         config->workdir = argvalstr(optc);
658                         break;
659
660                 case SET_CACHE_TIMEOUT:
661                         config->cache_timeout = argvalintdec(optc, 0, INT_MAX);
662                         break;
663
664                 case SET_SESSIONMAX:
665                         config->max_session_count = argvalintdec(optc, 1, INT_MAX);
666                         break;
667
668                 case SET_FORGROUND:
669                         noarg(optc);
670                         config->background = 0;
671                         break;
672
673                 case SET_BACKGROUND:
674                         noarg(optc);
675                         config->background = 1;
676                         break;
677
678                 case SET_NAME:
679                         config->name = argvalstr(optc);
680                         break;
681
682 #if HAS_DBUS
683                 case DBUS_CLIENT:
684                         list_add(&config->dbus_clients, argvalstr(optc));
685                         break;
686
687                 case DBUS_SERVICE:
688                         list_add(&config->dbus_servers, argvalstr(optc));
689                         break;
690 #endif
691
692                 case WS_CLIENT:
693                         list_add(&config->ws_clients, argvalstr(optc));
694                         break;
695
696                 case WS_SERVICE:
697                         list_add(&config->ws_servers, argvalstr(optc));
698                         break;
699
700                 case SO_BINDING:
701                         list_add(&config->so_bindings, argvalstr(optc));
702                         break;
703
704                 case AUTO_API:
705                         list_add(&config->auto_api, argvalstr(optc));
706                         break;
707
708                 case SET_TRACEREQ:
709                         config->tracereq = argvalenum(optc, tracereq_desc);
710                         break;
711
712 #if !defined(REMOVE_LEGACY_TRACE)
713                 case SET_TRACEDITF:
714                         config->traceditf = argvalenum(optc, traceditf_desc);
715                         break;
716
717                 case SET_TRACESVC:
718                         config->tracesvc = argvalenum(optc, tracesvc_desc);
719                         break;
720 #endif
721
722                 case SET_TRACEEVT:
723                         config->traceevt = argvalenum(optc, traceevt_desc);
724                         break;
725
726                 case SET_TRACESES:
727                         config->traceses = argvalenum(optc, traceses_desc);
728                         break;
729
730                 case SET_TRACEAPI:
731                         config->traceapi = argvalenum(optc, traceapi_desc);
732                         break;
733
734                 case SET_NO_HTTPD:
735                         noarg(optc);
736                         config->no_httpd = 1;
737                         break;
738
739                 case SET_EXEC:
740                         config->exec = make_exec(&argv[optind]);
741                         optind = argc; /* stop option scanning */
742                         break;
743
744                 case SET_RNDTOKEN:
745                         config->random_token = 1;
746                         break;
747
748 #if HAS_MONITORING
749                 case SET_MONITORING:
750                         config->monitoring = 1;
751                         break;
752 #endif
753
754                 case DISPLAY_VERSION:
755                         noarg(optc);
756                         printVersion(stdout);
757                         exit(0);
758
759                 case DISPLAY_HELP:
760                         printHelp(stdout, programName);
761                         exit(0);
762
763                 default:
764                         exit(1);
765                 }
766         }
767         free(gnuOptions);
768 }
769
770 static void fulfill_config(struct afb_config *config)
771 {
772         // default HTTP port
773         if (config->http_port == 0)
774                 config->http_port = DEFAULT_HTTP_PORT;
775
776         // default binding API timeout
777         if (config->api_timeout == 0)
778                 config->api_timeout = DEFAULT_API_TIMEOUT;
779
780         // default AUTH_TOKEN
781         if (config->random_token)
782                 config->token = NULL;
783
784         // cache timeout default one hour
785         if (config->cache_timeout == 0)
786                 config->cache_timeout = DEFAULT_CACHE_TIMEOUT;
787
788         // cache timeout default one hour
789         if (config->session_timeout == 0)
790                 config->session_timeout = DEFAULT_SESSION_TIMEOUT;
791
792         // max count of sessions
793         if (config->max_session_count == 0)
794                 config->max_session_count = DEFAULT_MAX_SESSION_COUNT;
795
796         /* set directories */
797         if (config->workdir == NULL)
798                 config->workdir = ".";
799
800         if (config->rootdir == NULL)
801                 config->rootdir = ".";
802
803         if (config->uploaddir == NULL)
804                 config->uploaddir = ".";
805
806         // if no Angular/HTML5 rootbase let's try '/' as default
807         if (config->rootbase == NULL)
808                 config->rootbase = "/opa";
809
810         if (config->rootapi == NULL)
811                 config->rootapi = "/api";
812
813         if (config->ldpaths == NULL && config->weak_ldpaths == NULL && !config->no_ldpaths)
814                 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
815
816 #if HAS_MONITORING
817         if (config->monitoring)
818                 list_add(&config->aliases, strdup("/monitoring:"BINDING_INSTALL_DIR"/monitoring"));
819 #endif
820
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);
826         }
827
828 #if !defined(REMOVE_LEGACY_TRACE)
829         config->traceapi |= config->traceditf | config->tracesvc;
830 #endif
831 }
832
833 void afb_config_dump(struct afb_config *config)
834 {
835         struct afb_config_list *l;
836         struct enumdesc *e;
837         char **v;
838
839 #define NN(x)   (x)?:""
840 #define P(...)  fprintf(stderr, __VA_ARGS__)
841 #define PF(x)   P("-- %15s: ", #x)
842 #define PE      P("\n")
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;
849
850         P("---BEGIN-OF-CONFIG---\n");
851         S(console)
852         S(rootdir)
853         S(roothttp)
854         S(rootbase)
855         S(rootapi)
856         S(workdir)
857         S(uploaddir)
858         S(token)
859         S(name)
860
861         L(aliases)
862 #if HAS_DBUS
863         L(dbus_clients)
864         L(dbus_servers)
865 #endif
866         L(ws_clients)
867         L(ws_servers)
868         L(so_bindings)
869         L(auto_api)
870         L(ldpaths)
871         L(weak_ldpaths)
872         L(calls)
873
874         V(exec)
875
876         D(http_port)
877         D(cache_timeout)
878         D(api_timeout)
879         D(session_timeout)
880         D(max_session_count)
881
882         E(tracereq,tracereq_desc)
883 #if !defined(REMOVE_LEGACY_TRACE)
884         E(traceditf,traceditf_desc)
885         E(tracesvc,tracesvc_desc)
886 #endif
887         E(traceevt,traceevt_desc)
888         E(traceses,traceses_desc)
889         E(traceapi,traceapi_desc)
890
891         B(no_ldpaths)
892         B(no_httpd)
893         B(background)
894 #if HAS_MONITORING
895         B(monitoring)
896 #endif
897         B(random_token)
898         P("---END-OF-CONFIG---\n");
899
900 #undef V
901 #undef E
902 #undef L
903 #undef B
904 #undef D
905 #undef S
906 #undef PE
907 #undef PF
908 #undef P
909 #undef NN
910 }
911
912 static void on_environment_list(struct afb_config_list **to, const char *name)
913 {
914         char *value = getenv(name);
915
916         if (value)
917                 list_add(to, value);
918 }
919
920 static void on_environment_enum(int *to, const char *name, struct enumdesc *desc)
921 {
922         char *value = getenv(name);
923
924         if (value) {
925                 while (desc->name) {
926                         if (strcmp(desc->name, value))
927                                 desc++;
928                         else {
929                                 *to = desc->value;
930                                 return;
931                         }
932                 }
933                 WARNING("Unknown value %s for environment variable %s, ignored", value, name);
934         }
935 }
936
937 static void parse_environment(struct afb_config *config)
938 {
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);
943 #endif
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");
948 }
949
950 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
951 {
952         struct afb_config *result;
953
954         result = calloc(1, sizeof *result);
955
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);
961         return result;
962 }
963
964 struct json_object *afb_config_json(struct afb_config *config)
965 {
966         struct json_object *r, *a;
967         struct afb_config_list *l;
968         struct enumdesc *e;
969         char **v;
970
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)
974
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))
982
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);}
989
990         r = json_object_new_object();
991         S(console)
992         S(rootdir)
993         S(roothttp)
994         S(rootbase)
995         S(rootapi)
996         S(workdir)
997         S(uploaddir)
998         S(token)
999         S(name)
1000
1001         L(aliases)
1002 #if HAS_DBUS
1003         L(dbus_clients)
1004         L(dbus_servers)
1005 #endif
1006         L(ws_clients)
1007         L(ws_servers)
1008         L(so_bindings)
1009         L(auto_api)
1010         L(ldpaths)
1011         L(weak_ldpaths)
1012         L(calls)
1013
1014         V(exec)
1015
1016         D(http_port)
1017         D(cache_timeout)
1018         D(api_timeout)
1019         D(session_timeout)
1020         D(max_session_count)
1021
1022         E(tracereq,tracereq_desc)
1023 #if !defined(REMOVE_LEGACY_TRACE)
1024         E(traceditf,traceditf_desc)
1025         E(tracesvc,tracesvc_desc)
1026 #endif
1027         E(traceevt,traceevt_desc)
1028         E(traceses,traceses_desc)
1029         E(traceapi,traceapi_desc)
1030
1031         B(no_ldpaths)
1032         B(no_httpd)
1033         B(background)
1034 #if HAS_MONITORING
1035         B(monitoring)
1036 #endif
1037         B(random_token)
1038
1039 #undef E
1040 #undef B
1041 #undef D
1042 #undef L
1043 #undef V
1044 #undef S
1045
1046 #undef RB
1047 #undef RI
1048 #undef RA
1049 #undef RS
1050 #undef RS
1051 #undef AS
1052 #undef AO
1053
1054 #undef YS
1055 #undef XO
1056 #undef XA
1057
1058         return r;
1059 }
1060