afb-config: Fix wrong error message and more info
[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 #if defined(WITH_LEGACY_BINDING_V1)
56 #   define HAS_BINDING_V1 1
57 #else
58 #   define HAS_BINDING_V1 0
59 #endif
60 #if defined(WITH_LEGACY_BINDING_VDYN)
61 #   define HAS_BINDING_VDYN 1
62 #else
63 #   define HAS_BINDING_VDYN 0
64 #endif
65 #if defined(WITH_SUPERVISION)
66 #   define HAS_SUPERVISION 1
67 #else
68 #   define HAS_SUPERVISION 0
69 #endif
70
71 /**
72  * The default timeout of sessions in seconds
73  */
74 #define DEFAULT_SESSION_TIMEOUT         32000000
75
76 /**
77  * The default timeout of api calls in seconds
78  */
79 #define DEFAULT_API_TIMEOUT             20
80
81 /**
82  * The default timeout of cache in seconds
83  */
84 #define DEFAULT_CACHE_TIMEOUT           100000
85
86 /**
87  * The default maximum count of sessions
88  */
89 #define DEFAULT_MAX_SESSION_COUNT       200
90
91 /**
92  * The default HTTP port to serve
93  */
94 #define DEFAULT_HTTP_PORT               1234
95
96
97
98
99
100 // Define command line option
101 #define SET_BACKGROUND     1
102 #define SET_FORGROUND      2
103 #define SET_ROOT_DIR       3
104 #define SET_ROOT_BASE      4
105 #define SET_ROOT_API       5
106 #define SET_ALIAS          6
107
108 #define SET_CACHE_TIMEOUT  7
109
110 #define AUTO_WS            8
111 #define AUTO_LINK          9
112
113 #define SET_LDPATH         10
114 #define SET_APITIMEOUT     11
115 #define SET_CNTXTIMEOUT    12
116 #define SET_WEAK_LDPATH    13
117 #define NO_LDPATH          14
118
119 #define SET_SESSIONMAX     15
120
121 #define WS_CLIENT          16
122 #define WS_SERVICE         17
123
124 #define SET_ROOT_HTTP      18
125
126 #define SET_NO_HTTPD       19
127
128 #define SET_TRACEEVT       20
129 #define SET_TRACESES       21
130 #define SET_TRACEREQ       22
131 #define SET_TRACEAPI       23
132 #if !defined(REMOVE_LEGACY_TRACE)
133 #define SET_TRACEDITF      24
134 #define SET_TRACESVC       25
135 #endif
136
137 #if HAS_DBUS
138 #   define DBUS_CLIENT        30
139 #   define DBUS_SERVICE       31
140 #endif
141
142
143 #define AUTO_API           'A'
144 #define SO_BINDING         'b'
145 #define ADD_CALL           'c'
146 #define SET_EXEC           'e'
147 #define DISPLAY_HELP       'h'
148 #define SET_LOG            'l'
149 #if HAS_MONITORING
150 #define SET_MONITORING     'M'
151 #endif
152 #define SET_NAME           'n'
153 #define SET_TCP_PORT       'p'
154 #define SET_QUIET          'q'
155 #define SET_RNDTOKEN       'r'
156 #define SET_AUTH_TOKEN     't'
157 #define SET_UPLOAD_DIR     'u'
158 #define DISPLAY_VERSION    'V'
159 #define SET_VERBOSE        'v'
160 #define SET_WORK_DIR       'w'
161
162 const char shortopts[] =
163         "A:"
164         "b:"
165         "c:"
166         "e"
167         "h"
168         "l:"
169 #if HAS_MONITORING
170         "M"
171 #endif
172         "n:"
173         "p:"
174         "q"
175         "r"
176         "t:"
177         "u:"
178         "V"
179         "v"
180         "w:"
181 ;
182
183 // Command line structure hold cli --command + help text
184 typedef struct {
185         int val;                // command number within application
186         int has_arg;            // command number within application
187         char *name;             // command as used in --xxxx cli
188         char *help;             // help text
189 } AFB_options;
190
191 // Supported option
192 static AFB_options cliOptions[] = {
193 /* *INDENT-OFF* */
194         {SET_VERBOSE,       0, "verbose",     "Verbose Mode, repeat to increase verbosity"},
195         {SET_QUIET,         0, "quiet",       "Quiet Mode, repeat to decrease verbosity"},
196         {SET_LOG,           1, "log",         "Tune log level"},
197
198         {SET_FORGROUND,     0, "foreground",  "Get all in foreground mode"},
199         {SET_BACKGROUND,    0, "daemon",      "Get all in background mode"},
200
201         {SET_NAME,          1, "name",        "Set the visible name"},
202
203         {SET_TCP_PORT,      1, "port",        "HTTP listening TCP port  [default " d2s(DEFAULT_HTTP_PORT) "]"},
204         {SET_ROOT_HTTP,     1, "roothttp",    "HTTP Root Directory [default no root http (files not served but apis still available)]"},
205         {SET_ROOT_BASE,     1, "rootbase",    "Angular Base Root URL [default /opa]"},
206         {SET_ROOT_API,      1, "rootapi",     "HTML Root API URL [default /api]"},
207         {SET_ALIAS,         1, "alias",       "Multiple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
208
209         {SET_APITIMEOUT,    1, "apitimeout",  "Binding API timeout in seconds [default " d2s(DEFAULT_API_TIMEOUT) "]"},
210         {SET_CNTXTIMEOUT,   1, "cntxtimeout", "Client Session Context Timeout [default " d2s(DEFAULT_SESSION_TIMEOUT) "]"},
211         {SET_CACHE_TIMEOUT, 1, "cache-eol",   "Client cache end of live [default " d2s(DEFAULT_CACHE_TIMEOUT) "]"},
212
213         {SET_WORK_DIR,      1, "workdir",     "Set the working directory [default: $PWD or current working directory]"},
214         {SET_UPLOAD_DIR,    1, "uploaddir",   "Directory for uploading files [default: workdir]"},
215         {SET_ROOT_DIR,      1, "rootdir",     "Root Directory of the application [default: workdir]"},
216
217         {SET_LDPATH,        1, "ldpaths",     "Load bindings from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
218         {SO_BINDING,        1, "binding",     "Load the binding of path"},
219         {SET_WEAK_LDPATH,   1, "weak-ldpaths","Same as --ldpaths but ignore errors"},
220         {NO_LDPATH,         0, "no-ldpaths",  "Discard default ldpaths loading"},
221
222         {SET_AUTH_TOKEN,    1, "token",       "Initial Secret [default=random, use --token="" to allow any token]"},
223         {SET_RNDTOKEN,      0, "random-token","Enforce a random token"},
224
225         {DISPLAY_VERSION,   0, "version",     "Display version and copyright"},
226         {DISPLAY_HELP,      0, "help",        "Display this help"},
227
228 #if HAS_DBUS
229         {DBUS_CLIENT,       1, "dbus-client", "Bind to an afb service through dbus"},
230         {DBUS_SERVICE,      1, "dbus-server", "Provide an afb service through dbus"},
231 #endif
232         {WS_CLIENT,         1, "ws-client",   "Bind to an afb service through websocket"},
233         {WS_SERVICE,        1, "ws-server",   "Provide an afb service through websockets"},
234
235         {AUTO_API,          1, "auto-api",    "Automatic load of api of the given directory"},
236
237         {SET_SESSIONMAX,    1, "session-max", "Max count of session simultaneously [default " d2s(DEFAULT_MAX_SESSION_COUNT) "]"},
238
239         {SET_TRACEREQ,      1, "tracereq",    "Log the requests: no, common, extra, all"},
240 #if !defined(REMOVE_LEGACY_TRACE)
241         {SET_TRACEDITF,     1, "traceditf",   "Log the daemons: no, common, all"},
242         {SET_TRACESVC,      1, "tracesvc",    "Log the services: no, all"},
243 #endif
244         {SET_TRACEEVT,      1, "traceevt",    "Log the events: no, common, extra, all"},
245         {SET_TRACESES,      1, "traceses",    "Log the sessions: no, all"},
246         {SET_TRACEAPI,      1, "traceapi",    "Log the apis: no, common, api, event, all"},
247
248         {ADD_CALL,          1, "call",        "call at start format of val: API/VERB:json-args"},
249
250         {SET_NO_HTTPD,      0, "no-httpd",    "Forbid HTTP service"},
251         {SET_EXEC,          0, "exec",        "Execute the remaining arguments"},
252
253 #if HAS_MONITORING
254         {SET_MONITORING,    0, "monitoring",  "Enable HTTP monitoring at <ROOT>/monitoring/"},
255 #endif
256         {0, 0, NULL, NULL}
257 /* *INDENT-ON* */
258 };
259
260
261 struct enumdesc
262 {
263         const char *name;
264         int value;
265 };
266
267 static struct enumdesc tracereq_desc[] = {
268         { "no",     0 },
269         { "common", afb_hook_flags_req_common },
270         { "extra",  afb_hook_flags_req_extra },
271         { "all",    afb_hook_flags_req_all },
272         { NULL, 0 }
273 };
274
275 #if !defined(REMOVE_LEGACY_TRACE)
276 static struct enumdesc traceditf_desc[] = {
277         { "no",     0 },
278         { "common", afb_hook_flags_api_ditf_common },
279         { "all",    afb_hook_flags_api_ditf_all },
280         { NULL, 0 }
281 };
282
283 static struct enumdesc tracesvc_desc[] = {
284         { "no",     0 },
285         { "all",    afb_hook_flags_api_svc_all },
286         { NULL, 0 }
287 };
288 #endif
289
290 static struct enumdesc traceevt_desc[] = {
291         { "no",     0 },
292         { "common", afb_hook_flags_evt_common },
293         { "extra",  afb_hook_flags_evt_extra },
294         { "all",    afb_hook_flags_evt_all },
295         { NULL, 0 }
296 };
297
298 static struct enumdesc traceses_desc[] = {
299         { "no",     0 },
300         { "common", afb_hook_flags_session_common },
301         { "all",    afb_hook_flags_session_all },
302         { NULL, 0 }
303 };
304
305 static struct enumdesc traceapi_desc[] = {
306         { "no",         0 },
307         { "common",     afb_hook_flags_api_common },
308         { "api",        afb_hook_flags_api_api|afb_hook_flag_api_start },
309         { "event",      afb_hook_flags_api_event|afb_hook_flag_api_start },
310         { "all",        afb_hook_flags_api_all },
311         { NULL, 0 }
312 };
313
314 /*----------------------------------------------------------
315  | printversion
316  |   print version and copyright
317  +--------------------------------------------------------- */
318 static void printVersion(FILE * file)
319 {
320         static char pm[2] = { '-', '+' };
321         fprintf(file,
322                 "\n"
323                 "  AGL Framework Binder [AFB %s] %cDBUS %cMONITOR %cSUPERVISION [BINDINGS %cV1 %cVDYN +V2 +V3]\n"
324                 "\n",
325                         AFB_VERSION,
326                         pm[HAS_DBUS],
327                         pm[HAS_MONITORING],
328                         pm[HAS_SUPERVISION],
329                         pm[HAS_BINDING_V1],
330                         pm[HAS_BINDING_VDYN]
331                 );
332         fprintf(file,
333                 "  Copyright (C) 2015-2018 \"IoT.bzh\"\n"
334                 "  AFB comes with ABSOLUTELY NO WARRANTY.\n"
335                 "  Licence Apache 2\n"
336                 "\n");
337 }
338
339 /*----------------------------------------------------------
340  | printHelp
341  |   print information from long option array
342  +--------------------------------------------------------- */
343
344 static void printHelp(FILE * file, const char *name)
345 {
346         int ind;
347         char command[50], sht[4];
348
349         sht[3] = 0;
350         fprintf(file, "%s:\nallowed options\n", name);
351         for (ind = 0; cliOptions[ind].name != NULL; ind++) {
352                 if (((cliOptions[ind].val >= 'a' && cliOptions[ind].val <= 'z')
353                  || (cliOptions[ind].val >= 'A' && cliOptions[ind].val <= 'Z')
354                  || (cliOptions[ind].val >= '0' && cliOptions[ind].val <= '9'))
355                  && strchr(shortopts, (char)cliOptions[ind].val)) {
356                         sht[0] = '-';
357                         sht[1] = (char)cliOptions[ind].val;
358                         sht[2] = ',';
359                 } else {
360                         sht[0] = sht[1] = sht[2] = ' ';
361                 }
362                 strcpy(command, cliOptions[ind].name);
363                 if (cliOptions[ind].has_arg)
364                         strcat(command, "=xxxx");
365                 fprintf(file, " %s --%-17s %s\n", sht, command, cliOptions[ind].help);
366         }
367         fprintf(file,
368                 "Example:\n  %s  --verbose --port=" d2s(DEFAULT_HTTP_PORT) " --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
369                 name);
370 }
371
372
373 /*----------------------------------------------------------
374  |   adds a string to the list
375  +--------------------------------------------------------- */
376 static void list_add(struct afb_config_list **head, char *value)
377 {
378         struct afb_config_list *item;
379
380         /*
381          * search tail
382          */
383         item = *head;
384         while (item != NULL) {
385                 head = &item->next;
386                 item = item->next;
387         }
388
389         /*
390          * alloc the item
391          */
392         item = malloc(sizeof *item);
393         if (item == NULL) {
394                 ERROR("out of memory");
395                 exit(1);
396         }
397
398         /*
399          * init the item
400          */
401         *head = item;
402         item->value = value;
403         item->next = NULL;
404 }
405
406 /*---------------------------------------------------------
407  |   helpers for argument scanning
408  +--------------------------------------------------------- */
409
410 static const char *name_of_option(int optc)
411 {
412         AFB_options *o = cliOptions;
413         while (o->name && o->val != optc)
414                 o++;
415         return o->name ? : "<unknown-option-name>";
416 }
417
418 static const char *current_argument(int optc)
419 {
420         if (optarg == 0) {
421                 ERROR("option [--%s] needs a value i.e. --%s=xxx",
422                       name_of_option(optc), name_of_option(optc));
423                 exit(1);
424         }
425         return optarg;
426 }
427
428 static char *argvalstr(int optc)
429 {
430         char *result = strdup(current_argument(optc));
431         if (result == NULL) {
432                 ERROR("can't alloc memory");
433                 exit(1);
434         }
435         return result;
436 }
437
438 static int argvalenum(int optc, struct enumdesc *desc)
439 {
440         int i;
441         size_t len;
442         char *list;
443         const char *name = current_argument(optc);
444
445         i = 0;
446         while(desc[i].name && strcmp(desc[i].name, name))
447                 i++;
448         if (!desc[i].name) {
449                 len = 0;
450                 i = 0;
451                 while(desc[i].name)
452                         len += strlen(desc[i++].name);
453                 list = malloc(len + i + i);
454                 if (!i || !list)
455                         ERROR("option [--%s] bad value (found %s)",
456                                 name_of_option(optc), name);
457                 else {
458                         i = 0;
459                         strcpy(list, desc[i].name ? : "");
460                         while(desc[++i].name)
461                                 strcat(strcat(list, ", "), desc[i].name);
462                         ERROR("option [--%s] bad value, only accepts values %s (found %s)",
463                                 name_of_option(optc), list, name);
464                 }
465                 free(list);
466                 exit(1);
467         }
468         return desc[i].value;
469 }
470
471 static int argvalint(int optc, int mini, int maxi, int base)
472 {
473         const char *beg, *end;
474         long int val;
475         beg = current_argument(optc);
476         val = strtol(beg, (char**)&end, base);
477         if (*end || end == beg) {
478                 ERROR("option [--%s] requires a valid integer (found %s)",
479                         name_of_option(optc), beg);
480                 exit(1);
481         }
482         if (val < (long int)mini || val > (long int)maxi) {
483                 ERROR("option [--%s] value out of bounds (not %d<=%ld<=%d)",
484                         name_of_option(optc), mini, val, maxi);
485                 exit(1);
486         }
487         return (int)val;
488 }
489
490 static int argvalintdec(int optc, int mini, int maxi)
491 {
492         return argvalint(optc, mini, maxi, 10);
493 }
494
495 static void noarg(int optc)
496 {
497         if (optarg != 0) {
498                 ERROR("option [--%s] need no value (found %s)", name_of_option(optc), optarg);
499                 exit(1);
500         }
501 }
502
503 static char **make_exec(char **argv)
504 {
505         char **result, *iter;
506         size_t length;
507         int i;
508
509         length = 0;
510         for (i = 0 ; argv[i] ; i++)
511                 length += strlen(argv[i]) + 1;
512
513         result = malloc(length + ((unsigned)(i + 1)) * sizeof *result);
514         if (result == NULL) {
515                 ERROR("can't alloc memory");
516                 exit(1);
517         }
518
519         iter = (char*)&result[i+1];
520         for (i = 0 ; argv[i] ; i++) {
521                 result[i] = iter;
522                 iter = stpcpy(iter, argv[i]) + 1;
523         }
524         result[i] = NULL;
525         return result;
526 }
527
528 /*---------------------------------------------------------
529  |   set the log levels
530  +--------------------------------------------------------- */
531
532 static void set_log(char *args)
533 {
534         char o = 0, s, *p, *i = args;
535         int lvl;
536
537         for(;;) switch (*i) {
538         case 0:
539                 return;
540         case '+':
541         case '-':
542                 o = *i;
543                 /*@fallthrough@*/
544         case ' ':
545         case ',':
546                 i++;
547                 break;
548         default:
549                 p = i;
550                 while (isalpha(*p)) p++;
551                 s = *p;
552                 *p = 0;
553                 lvl = verbose_level_of_name(i);
554                 if (lvl < 0) {
555                         i = strdupa(i);
556                         *p = s;
557                         ERROR("Bad log name '%s' in %s", i, args);
558                         exit(1);
559                 }
560                 *p = s;
561                 i = p;
562                 if (o == '-')
563                         verbose_sub(lvl);
564                 else {
565                         if (!o) {
566                                 verbose_clear();
567                                 o = '+';
568                         }
569                         verbose_add(lvl);
570                 }
571                 break;
572         }
573 }
574
575 /*---------------------------------------------------------
576  |   Parse option and launch action
577  +--------------------------------------------------------- */
578
579 static void parse_arguments(int argc, char **argv, struct afb_config *config)
580 {
581         char *programName = argv[0];
582         int optc, ind;
583         int nbcmd;
584         struct option *gnuOptions;
585
586         // ------------------ Process Command Line -----------------------
587
588         // build GNU getopt info from cliOptions
589         nbcmd = sizeof(cliOptions) / sizeof(AFB_options);
590         gnuOptions = malloc(sizeof(*gnuOptions) * (unsigned)nbcmd);
591         for (ind = 0; ind < nbcmd; ind++) {
592                 gnuOptions[ind].name = cliOptions[ind].name;
593                 gnuOptions[ind].has_arg = cliOptions[ind].has_arg;
594                 gnuOptions[ind].flag = 0;
595                 gnuOptions[ind].val = cliOptions[ind].val;
596         }
597
598         // get all options from command line
599         while ((optc = getopt_long(argc, argv, shortopts, gnuOptions, NULL)) != EOF) {
600                 switch (optc) {
601                 case SET_VERBOSE:
602                         verbose_inc();
603                         break;
604
605                 case SET_QUIET:
606                         verbose_dec();
607                         break;
608
609                 case SET_LOG:
610                         set_log(argvalstr(optc));
611                         break;
612
613                 case SET_TCP_PORT:
614                         config->http_port = argvalintdec(optc, 1024, 32767);
615                         break;
616
617                 case SET_APITIMEOUT:
618                         config->api_timeout = argvalintdec(optc, 0, INT_MAX);
619                         break;
620
621                 case SET_CNTXTIMEOUT:
622                         config->session_timeout = argvalintdec(optc, 0, INT_MAX);
623                         break;
624
625                 case SET_ROOT_DIR:
626                         config->rootdir = argvalstr(optc);
627                         INFO("Forcing Rootdir=%s", config->rootdir);
628                         break;
629
630                 case SET_ROOT_HTTP:
631                         config->roothttp = argvalstr(optc);
632                         INFO("Forcing Root HTTP=%s", config->roothttp);
633                         break;
634
635                 case SET_ROOT_BASE:
636                         config->rootbase = argvalstr(optc);
637                         INFO("Forcing Rootbase=%s", config->rootbase);
638                         break;
639
640                 case SET_ROOT_API:
641                         config->rootapi = argvalstr(optc);
642                         INFO("Forcing Rootapi=%s", config->rootapi);
643                         break;
644
645                 case SET_ALIAS:
646                         list_add(&config->aliases, argvalstr(optc));
647                         break;
648
649                 case SET_AUTH_TOKEN:
650                         config->token = argvalstr(optc);
651                         break;
652
653                 case SET_LDPATH:
654                         list_add(&config->ldpaths, argvalstr(optc));
655                         break;
656
657                 case SET_WEAK_LDPATH:
658                         list_add(&config->weak_ldpaths, argvalstr(optc));
659                         break;
660
661                 case NO_LDPATH:
662                         noarg(optc);
663                         config->no_ldpaths = 1;
664                         break;
665
666                 case ADD_CALL:
667                         list_add(&config->calls, argvalstr(optc));
668                         break;
669
670                 case SET_UPLOAD_DIR:
671                         config->uploaddir = argvalstr(optc);
672                         break;
673
674                 case SET_WORK_DIR:
675                         config->workdir = argvalstr(optc);
676                         break;
677
678                 case SET_CACHE_TIMEOUT:
679                         config->cache_timeout = argvalintdec(optc, 0, INT_MAX);
680                         break;
681
682                 case SET_SESSIONMAX:
683                         config->max_session_count = argvalintdec(optc, 1, INT_MAX);
684                         break;
685
686                 case SET_FORGROUND:
687                         noarg(optc);
688                         config->background = 0;
689                         break;
690
691                 case SET_BACKGROUND:
692                         noarg(optc);
693                         config->background = 1;
694                         break;
695
696                 case SET_NAME:
697                         config->name = argvalstr(optc);
698                         break;
699
700 #if HAS_DBUS
701                 case DBUS_CLIENT:
702                         list_add(&config->dbus_clients, argvalstr(optc));
703                         break;
704
705                 case DBUS_SERVICE:
706                         list_add(&config->dbus_servers, argvalstr(optc));
707                         break;
708 #endif
709
710                 case WS_CLIENT:
711                         list_add(&config->ws_clients, argvalstr(optc));
712                         break;
713
714                 case WS_SERVICE:
715                         list_add(&config->ws_servers, argvalstr(optc));
716                         break;
717
718                 case SO_BINDING:
719                         list_add(&config->so_bindings, argvalstr(optc));
720                         break;
721
722                 case AUTO_API:
723                         list_add(&config->auto_api, argvalstr(optc));
724                         break;
725
726                 case SET_TRACEREQ:
727                         config->tracereq = argvalenum(optc, tracereq_desc);
728                         break;
729
730 #if !defined(REMOVE_LEGACY_TRACE)
731                 case SET_TRACEDITF:
732                         config->traceditf = argvalenum(optc, traceditf_desc);
733                         break;
734
735                 case SET_TRACESVC:
736                         config->tracesvc = argvalenum(optc, tracesvc_desc);
737                         break;
738 #endif
739
740                 case SET_TRACEEVT:
741                         config->traceevt = argvalenum(optc, traceevt_desc);
742                         break;
743
744                 case SET_TRACESES:
745                         config->traceses = argvalenum(optc, traceses_desc);
746                         break;
747
748                 case SET_TRACEAPI:
749                         config->traceapi = argvalenum(optc, traceapi_desc);
750                         break;
751
752                 case SET_NO_HTTPD:
753                         noarg(optc);
754                         config->no_httpd = 1;
755                         break;
756
757                 case SET_EXEC:
758                         config->exec = make_exec(&argv[optind]);
759                         optind = argc; /* stop option scanning */
760                         break;
761
762                 case SET_RNDTOKEN:
763                         config->random_token = 1;
764                         break;
765
766 #if HAS_MONITORING
767                 case SET_MONITORING:
768                         config->monitoring = 1;
769                         break;
770 #endif
771
772                 case DISPLAY_VERSION:
773                         noarg(optc);
774                         printVersion(stdout);
775                         exit(0);
776
777                 case DISPLAY_HELP:
778                         printHelp(stdout, programName);
779                         exit(0);
780
781                 default:
782                         exit(1);
783                 }
784         }
785         free(gnuOptions);
786 }
787
788 static void fulfill_config(struct afb_config *config)
789 {
790         // default HTTP port
791         if (config->http_port == 0)
792                 config->http_port = DEFAULT_HTTP_PORT;
793
794         // default binding API timeout
795         if (config->api_timeout == 0)
796                 config->api_timeout = DEFAULT_API_TIMEOUT;
797
798         // default AUTH_TOKEN
799         if (config->random_token)
800                 config->token = NULL;
801
802         // cache timeout default one hour
803         if (config->cache_timeout == 0)
804                 config->cache_timeout = DEFAULT_CACHE_TIMEOUT;
805
806         // cache timeout default one hour
807         if (config->session_timeout == 0)
808                 config->session_timeout = DEFAULT_SESSION_TIMEOUT;
809
810         // max count of sessions
811         if (config->max_session_count == 0)
812                 config->max_session_count = DEFAULT_MAX_SESSION_COUNT;
813
814         /* set directories */
815         if (config->workdir == NULL)
816                 config->workdir = ".";
817
818         if (config->rootdir == NULL)
819                 config->rootdir = ".";
820
821         if (config->uploaddir == NULL)
822                 config->uploaddir = ".";
823
824         // if no Angular/HTML5 rootbase let's try '/' as default
825         if (config->rootbase == NULL)
826                 config->rootbase = "/opa";
827
828         if (config->rootapi == NULL)
829                 config->rootapi = "/api";
830
831         if (config->ldpaths == NULL && config->weak_ldpaths == NULL && !config->no_ldpaths)
832                 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
833
834 #if HAS_MONITORING
835         if (config->monitoring)
836                 list_add(&config->aliases, strdup("/monitoring:"BINDING_INSTALL_DIR"/monitoring"));
837 #endif
838
839         // if no config dir create a default path from uploaddir
840         if (config->console == NULL) {
841                 config->console = malloc(512);
842                 strncpy(config->console, config->uploaddir, 512);
843                 strncat(config->console, "/AFB-console.out", 512);
844         }
845
846 #if !defined(REMOVE_LEGACY_TRACE)
847         config->traceapi |= config->traceditf | config->tracesvc;
848 #endif
849 }
850
851 void afb_config_dump(struct afb_config *config)
852 {
853         struct afb_config_list *l;
854         struct enumdesc *e;
855         char **v;
856
857 #define NN(x)   (x)?:""
858 #define P(...)  fprintf(stderr, __VA_ARGS__)
859 #define PF(x)   P("-- %15s: ", #x)
860 #define PE      P("\n")
861 #define S(x)    PF(x);P("%s",NN(config->x));PE;
862 #define D(x)    PF(x);P("%d",config->x);PE;
863 #define B(x)    PF(x);P("%s",config->x?"yes":"no");PE;
864 #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;
865 #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);}
866 #define V(x)    P("-- %15s:", #x);for(v=config->x;v&&*v;v++)P(" %s",*v); PE;
867
868         P("---BEGIN-OF-CONFIG---\n");
869         S(console)
870         S(rootdir)
871         S(roothttp)
872         S(rootbase)
873         S(rootapi)
874         S(workdir)
875         S(uploaddir)
876         S(token)
877         S(name)
878
879         L(aliases)
880 #if HAS_DBUS
881         L(dbus_clients)
882         L(dbus_servers)
883 #endif
884         L(ws_clients)
885         L(ws_servers)
886         L(so_bindings)
887         L(auto_api)
888         L(ldpaths)
889         L(weak_ldpaths)
890         L(calls)
891
892         V(exec)
893
894         D(http_port)
895         D(cache_timeout)
896         D(api_timeout)
897         D(session_timeout)
898         D(max_session_count)
899
900         E(tracereq,tracereq_desc)
901 #if !defined(REMOVE_LEGACY_TRACE)
902         E(traceditf,traceditf_desc)
903         E(tracesvc,tracesvc_desc)
904 #endif
905         E(traceevt,traceevt_desc)
906         E(traceses,traceses_desc)
907         E(traceapi,traceapi_desc)
908
909         B(no_ldpaths)
910         B(no_httpd)
911         B(background)
912 #if HAS_MONITORING
913         B(monitoring)
914 #endif
915         B(random_token)
916         P("---END-OF-CONFIG---\n");
917
918 #undef V
919 #undef E
920 #undef L
921 #undef B
922 #undef D
923 #undef S
924 #undef PE
925 #undef PF
926 #undef P
927 #undef NN
928 }
929
930 static void on_environment_list(struct afb_config_list **to, const char *name)
931 {
932         char *value = getenv(name);
933
934         if (value)
935                 list_add(to, value);
936 }
937
938 static void on_environment_enum(int *to, const char *name, struct enumdesc *desc)
939 {
940         char *value = getenv(name);
941
942         if (value) {
943                 while (desc->name) {
944                         if (strcmp(desc->name, value))
945                                 desc++;
946                         else {
947                                 *to = desc->value;
948                                 return;
949                         }
950                 }
951                 WARNING("Unknown value %s for environment variable %s, ignored", value, name);
952         }
953 }
954
955 static void parse_environment(struct afb_config *config)
956 {
957         on_environment_enum(&config->tracereq, "AFB_TRACEREQ", tracereq_desc);
958 #if !defined(REMOVE_LEGACY_TRACE)
959         on_environment_enum(&config->traceditf, "AFB_TRACEDITF", traceditf_desc);
960         on_environment_enum(&config->tracesvc, "AFB_TRACESVC", tracesvc_desc);
961 #endif
962         on_environment_enum(&config->traceevt, "AFB_TRACEEVT", traceevt_desc);
963         on_environment_enum(&config->traceses, "AFB_TRACESES", traceses_desc);
964         on_environment_enum(&config->traceapi, "AFB_TRACEAPI", traceapi_desc);
965         on_environment_list(&config->ldpaths, "AFB_LDPATHS");
966 }
967
968 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
969 {
970         struct afb_config *result;
971
972         result = calloc(1, sizeof *result);
973
974         parse_environment(result);
975         parse_arguments(argc, argv, result);
976         fulfill_config(result);
977         if (verbose_wants(Log_Level_Info))
978                 afb_config_dump(result);
979         return result;
980 }
981
982 struct json_object *afb_config_json(struct afb_config *config)
983 {
984         struct json_object *r, *a;
985         struct afb_config_list *l;
986         struct enumdesc *e;
987         char **v;
988
989 #define XA(t,o)         json_object_array_add(t,o);
990 #define XO(t,x,o)       json_object_object_add(t,x,o);
991 #define YS(s)           ((s)?json_object_new_string(s):NULL)
992
993 #define AO(o)           XA(a,o)
994 #define AS(s)           AO(YS(s))
995 #define RO(x,o)         XO(r,x,o)
996 #define RS(x,s)         RO(x,YS(s))
997 #define RA(x)           RO(x,(a=json_object_new_array()))
998 #define RI(x,i)         RO(x,json_object_new_int(i))
999 #define RB(x,b)         RO(x,json_object_new_boolean(b))
1000
1001 #define S(x)            RS(#x,config->x)
1002 #define V(x)            RA(#x);for(v=config->x;v&&*v;v++)AS(*v);
1003 #define L(x)            RA(#x);for(l=config->x;l;l=l->next)AS(l->value);
1004 #define D(x)            RI(#x,config->x)
1005 #define B(x)            RB(#x,config->x)
1006 #define E(x,d)          for(e=d;e->name&&e->value!=config->x;e++);if(e->name){RS(#x,e->name);}else{D(x);}
1007
1008         r = json_object_new_object();
1009         S(console)
1010         S(rootdir)
1011         S(roothttp)
1012         S(rootbase)
1013         S(rootapi)
1014         S(workdir)
1015         S(uploaddir)
1016         S(token)
1017         S(name)
1018
1019         L(aliases)
1020 #if HAS_DBUS
1021         L(dbus_clients)
1022         L(dbus_servers)
1023 #endif
1024         L(ws_clients)
1025         L(ws_servers)
1026         L(so_bindings)
1027         L(auto_api)
1028         L(ldpaths)
1029         L(weak_ldpaths)
1030         L(calls)
1031
1032         V(exec)
1033
1034         D(http_port)
1035         D(cache_timeout)
1036         D(api_timeout)
1037         D(session_timeout)
1038         D(max_session_count)
1039
1040         E(tracereq,tracereq_desc)
1041 #if !defined(REMOVE_LEGACY_TRACE)
1042         E(traceditf,traceditf_desc)
1043         E(tracesvc,tracesvc_desc)
1044 #endif
1045         E(traceevt,traceevt_desc)
1046         E(traceses,traceses_desc)
1047         E(traceapi,traceapi_desc)
1048
1049         B(no_ldpaths)
1050         B(no_httpd)
1051         B(background)
1052 #if HAS_MONITORING
1053         B(monitoring)
1054 #endif
1055         B(random_token)
1056
1057 #undef E
1058 #undef B
1059 #undef D
1060 #undef L
1061 #undef V
1062 #undef S
1063
1064 #undef RB
1065 #undef RI
1066 #undef RA
1067 #undef RS
1068 #undef RS
1069 #undef AS
1070 #undef AO
1071
1072 #undef YS
1073 #undef XO
1074 #undef XA
1075
1076         return r;
1077 }
1078