3c0d28e90f600a87901dcf6421cc3de18eab9c42
[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 #if !defined(JSON_C_TO_STRING_NOSLASHESCAPE)
30 #define JSON_C_TO_STRING_NOSLASHESCAPE 0
31 #endif
32
33 #include "verbose.h"
34 #include "afb-config.h"
35 #include "afb-hook-flags.h"
36 #include "wrap-json.h"
37
38 #define _d2s_(x)  #x
39 #define d2s(x)    _d2s_(x)
40
41 #if !defined(BINDING_INSTALL_DIR)
42 #error "you should define BINDING_INSTALL_DIR"
43 #endif
44 #if !defined(AFB_VERSION)
45 #error "you should define AFB_VERSION"
46 #endif
47
48 /**
49  * The default timeout of sessions in seconds
50  */
51 #define DEFAULT_SESSION_TIMEOUT         32000000
52
53 /**
54  * The default timeout of api calls in seconds
55  */
56 #define DEFAULT_API_TIMEOUT             20
57
58 /**
59  * The default timeout of cache in seconds
60  */
61 #define DEFAULT_CACHE_TIMEOUT           100000
62
63 /**
64  * The default maximum count of sessions
65  */
66 #define DEFAULT_MAX_SESSION_COUNT       200
67
68 /**
69  * The default HTTP port to serve
70  */
71 #define DEFAULT_HTTP_PORT               1234
72
73 // Define command line option
74 #define SET_BACKGROUND       1
75 #define SET_FOREGROUND       2
76 #define SET_ROOT_DIR         3
77 #define SET_ROOT_BASE        4
78 #define SET_ROOT_API         5
79 #define ADD_ALIAS            6
80
81 #define SET_CACHE_TIMEOUT    7
82
83 #define AUTO_WS              8
84 #define AUTO_LINK            9
85
86 #define ADD_LDPATH          10
87 #define SET_API_TIMEOUT     11
88 #define SET_SESSION_TIMEOUT 12
89 #define ADD_WEAK_LDPATH     13
90 #define SET_NO_LDPATH       14
91
92 #define SET_SESSIONMAX      15
93
94 #define ADD_WS_CLIENT       16
95 #define ADD_WS_SERVICE      17
96
97 #define SET_ROOT_HTTP       18
98
99 #define SET_NO_HTTPD        19
100
101 #define SET_TRACEEVT        20
102 #define SET_TRACESES        21
103 #define SET_TRACEREQ        22
104 #define SET_TRACEAPI        23
105 #define SET_TRACEGLOB       24
106 #if !defined(REMOVE_LEGACY_TRACE)
107 #define SET_TRACEDITF       25
108 #define SET_TRACESVC        26
109 #endif
110
111 #if defined(WITH_DBUS_TRANSPARENCY)
112 #   define ADD_DBUS_CLIENT  30
113 #   define ADD_DBUS_SERVICE 31
114 #endif
115
116
117 #define ADD_AUTO_API       'A'
118 #define ADD_BINDING        'b'
119 #define SET_CONFIG         'C'
120 #define ADD_CALL           'c'
121 #define SET_DAEMON         'D'
122 #define SET_EXEC           'e'
123 #define GET_HELP           'h'
124 #define SET_LOG            'l'
125 #if defined(WITH_MONITORING_OPTION)
126 #define SET_MONITORING     'M'
127 #endif
128 #define SET_NAME           'n'
129 #define SET_OUTPUT         'o'
130 #define SET_PORT           'p'
131 #define SET_QUIET          'q'
132 #define SET_RANDOM_TOKEN   'r'
133 #define SET_TOKEN          't'
134 #define SET_UPLOAD_DIR     'u'
135 #define GET_VERSION        'V'
136 #define SET_VERBOSE        'v'
137 #define SET_WORK_DIR       'w'
138
139 /* structure for defining of options */
140 struct option_desc {
141         int id;         /* id of the option         */
142         int has_arg;    /* is a value required      */
143         char *name;     /* long name of the option  */
144         char *help;     /* help text                */
145 };
146
147 /* definition of options */
148 static struct option_desc optdefs[] = {
149 /* *INDENT-OFF* */
150         {SET_VERBOSE,         0, "verbose",     "Verbose Mode, repeat to increase verbosity"},
151         {SET_QUIET,           0, "quiet",       "Quiet Mode, repeat to decrease verbosity"},
152         {SET_LOG,             1, "log",         "Tune log level"},
153
154         {SET_FOREGROUND,      0, "foreground",  "Get all in foreground mode"},
155         {SET_BACKGROUND,      0, "background",  "Get all in background mode"},
156         {SET_DAEMON,          0, "daemon",      "Get all in background mode"},
157
158         {SET_NAME,            1, "name",        "Set the visible name"},
159
160         {SET_PORT,            1, "port",        "HTTP listening TCP port  [default " d2s(DEFAULT_HTTP_PORT) "]"},
161         {SET_ROOT_HTTP,       1, "roothttp",    "HTTP Root Directory [default no root http (files not served but apis still available)]"},
162         {SET_ROOT_BASE,       1, "rootbase",    "Angular Base Root URL [default /opa]"},
163         {SET_ROOT_API,        1, "rootapi",     "HTML Root API URL [default /api]"},
164         {ADD_ALIAS,           1, "alias",       "Multiple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
165
166         {SET_API_TIMEOUT,     1, "apitimeout",  "Binding API timeout in seconds [default " d2s(DEFAULT_API_TIMEOUT) "]"},
167         {SET_SESSION_TIMEOUT, 1, "cntxtimeout", "Client Session Context Timeout [default " d2s(DEFAULT_SESSION_TIMEOUT) "]"},
168         {SET_CACHE_TIMEOUT,   1, "cache-eol",   "Client cache end of live [default " d2s(DEFAULT_CACHE_TIMEOUT) "]"},
169
170         {SET_WORK_DIR,        1, "workdir",     "Set the working directory [default: $PWD or current working directory]"},
171         {SET_UPLOAD_DIR,      1, "uploaddir",   "Directory for uploading files [default: workdir]"},
172         {SET_ROOT_DIR,        1, "rootdir",     "Root Directory of the application [default: workdir]"},
173
174         {ADD_LDPATH,          1, "ldpaths",     "Load bindings from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
175         {ADD_BINDING,         1, "binding",     "Load the binding of path"},
176         {ADD_WEAK_LDPATH,     1, "weak-ldpaths","Same as --ldpaths but ignore errors"},
177         {SET_NO_LDPATH,       0, "no-ldpaths",  "Discard default ldpaths loading"},
178
179         {SET_TOKEN,           1, "token",       "Initial Secret [default=random, use --token="" to allow any token]"},
180         {SET_RANDOM_TOKEN,    0, "random-token","Enforce a random token"},
181
182         {GET_VERSION,         0, "version",     "Display version and copyright"},
183         {GET_HELP,            0, "help",        "Display this help"},
184
185 #if defined(WITH_DBUS_TRANSPARENCY)
186         {ADD_DBUS_CLIENT,     1, "dbus-client", "Bind to an afb service through dbus"},
187         {ADD_DBUS_SERVICE,    1, "dbus-server", "Provide an afb service through dbus"},
188 #endif
189         {ADD_WS_CLIENT,       1, "ws-client",   "Bind to an afb service through websocket"},
190         {ADD_WS_SERVICE,      1, "ws-server",   "Provide an afb service through websockets"},
191
192         {ADD_AUTO_API,        1, "auto-api",    "Automatic load of api of the given directory"},
193
194         {SET_SESSIONMAX,      1, "session-max", "Max count of session simultaneously [default " d2s(DEFAULT_MAX_SESSION_COUNT) "]"},
195
196         {SET_TRACEREQ,        1, "tracereq",    "Log the requests: none, common, extra, all"},
197         {SET_TRACEEVT,        1, "traceevt",    "Log the events: none, common, extra, all"},
198         {SET_TRACESES,        1, "traceses",    "Log the sessions: none, all"},
199         {SET_TRACEAPI,        1, "traceapi",    "Log the apis: none, common, api, event, all"},
200         {SET_TRACEGLOB,       1, "traceglob",   "Log the globals: none, all"},
201 #if !defined(REMOVE_LEGACY_TRACE)
202         {SET_TRACEDITF,       1, "traceditf",   "Log the daemons: no, common, all"},
203         {SET_TRACESVC,        1, "tracesvc",    "Log the services: no, all"},
204 #endif
205
206         {ADD_CALL,            1, "call",        "Call at start, format of val: API/VERB:json-args"},
207
208         {SET_NO_HTTPD,        0, "no-httpd",    "Forbid HTTP service"},
209         {SET_EXEC,            0, "exec",        "Execute the remaining arguments"},
210
211 #if defined(WITH_MONITORING_OPTION)
212         {SET_MONITORING,      0, "monitoring",  "Enable HTTP monitoring at <ROOT>/monitoring/"},
213 #endif
214
215         {SET_CONFIG,          1, "config",      "Load options from the given config file"},
216         {SET_OUTPUT,          1, "output",      "Redirect stdout and stderr to output file (when --daemon)"},
217
218         {0, 0, NULL, NULL}
219 /* *INDENT-ON* */
220 };
221
222 #if defined(WITH_MONITORING_OPTION)
223 static const char MONITORING_ALIAS[] = "/monitoring:"BINDING_INSTALL_DIR"/monitoring";
224 #endif
225
226 static const struct {
227         int optid;
228         int valdef;
229 } default_optint_values[] = {
230         { SET_PORT,             DEFAULT_HTTP_PORT },
231         { SET_API_TIMEOUT,      DEFAULT_API_TIMEOUT },
232         { SET_CACHE_TIMEOUT,    DEFAULT_CACHE_TIMEOUT },
233         { SET_SESSION_TIMEOUT,  DEFAULT_SESSION_TIMEOUT },
234         { SET_SESSIONMAX,       DEFAULT_MAX_SESSION_COUNT }
235 };
236
237 static const struct {
238         int optid;
239         const char *valdef;
240 } default_optstr_values[] = {
241         { SET_WORK_DIR,         "." },
242         { SET_ROOT_DIR,         "." },
243         { SET_UPLOAD_DIR,       "." },
244         { SET_ROOT_BASE,        "/opa" },
245         { SET_ROOT_API,         "/api" }
246 };
247
248 /**********************************
249 * preparing items
250 ***********************************/
251
252 static char *shortopts = NULL;
253 static int *id2idx = NULL;
254
255 static void *oomchk(void *ptr)
256 {
257         if (!ptr) {
258                 ERROR("Out of memory");
259                 exit(1);
260         }
261         return ptr;
262 }
263
264 static char is_short_option(int val)
265 {
266         return (val >= 'a' && val <= 'z') || (val >= 'A' && val <= 'Z') || (val >= '0' && val <= '9');
267 }
268
269 static void init_options()
270 {
271         int i, ns, mi, id;
272
273         if (!shortopts) {
274                 ns = 2;
275                 mi = -1;
276                 for (i = 0 ; optdefs[i].name ; i++) {
277                         id = optdefs[i].id;
278                         if (id > mi)
279                                 mi = id;
280                         if (is_short_option(id))
281                                 ns += 1 + !!optdefs[i].has_arg;
282                 }
283                 shortopts = oomchk(malloc(2 + ns));
284                 id2idx = oomchk(calloc(1 + mi, sizeof *id2idx));
285                 shortopts[ns = 0] = ':';
286                 for (i = 0 ; optdefs[i].name ; i++) {
287                         id = optdefs[i].id;
288                         id2idx[id] = i;
289                         if (is_short_option(id)) {
290                                 shortopts[++ns] = (char)id;
291                                 if (optdefs[i].has_arg)
292                                         shortopts[++ns] = ':';
293                         }
294                 }
295                 shortopts[++ns] = 0;
296         }
297 }
298
299 static const char *name_of_optid(int optid)
300 {
301         return optdefs[id2idx[optid]].name;
302 }
303
304 static int get_enum_val(const char *name, int optid, int (*func)(const char*))
305 {
306         int i;
307
308         i = func(name);
309         if (i < 0) {
310                 ERROR("option [--%s] bad value (found %s)",
311                         name_of_optid(optid), name);
312                 exit(1);
313         }
314         return i;
315 }
316
317
318 /*----------------------------------------------------------
319  | printversion
320  |   print version and copyright
321  +--------------------------------------------------------- */
322 static void printVersion(FILE * file)
323 {
324         fprintf(file,
325                 "\n"
326                 "  AGL Framework Binder [AFB %s] "
327 #if defined(WITH_DBUS_TRANSPARENCY)
328                 "+"
329 #else
330                 "-"
331 #endif
332                 "DBUS "
333 #if defined(WITH_MONITORING_OPTION)
334                 "+"
335 #else
336                 "-"
337 #endif
338                 "MONITOR "
339 #if defined(WITH_SUPERVISION)
340                 "+"
341 #else
342                 "-"
343 #endif
344                 "SUPERVISION [BINDINGS "
345 #if defined(WITH_LEGACY_BINDING_V1)
346                 "+"
347 #else
348                 "-"
349 #endif
350                 "V1 "
351 #if defined(WITH_LEGACY_BINDING_VDYN)
352                 "+"
353 #else
354                 "-"
355 #endif
356                 "VDYN +V2 +V3]\n"
357                 "\n",
358                 AFB_VERSION
359         );
360         fprintf(file,
361                 "  Copyright (C) 2015-2018 \"IoT.bzh\"\n"
362                 "  AFB comes with ABSOLUTELY NO WARRANTY.\n"
363                 "  Licence Apache 2\n"
364                 "\n");
365 }
366
367 /*----------------------------------------------------------
368  | printHelp
369  |   print information from long option array
370  +--------------------------------------------------------- */
371
372 static void printHelp(FILE * file, const char *name)
373 {
374         int ind;
375         char command[50], sht[4];
376
377         fprintf(file, "%s:\nallowed options\n", strrchr(name, '/') ? strrchr(name, '/') + 1 : name);
378         sht[3] = 0;
379         for (ind = 0; optdefs[ind].name != NULL; ind++) {
380                 if (is_short_option(optdefs[ind].id)) {
381                         sht[0] = '-';
382                         sht[1] = (char)optdefs[ind].id;
383                         sht[2] = ',';
384                 } else {
385                         sht[0] = sht[1] = sht[2] = ' ';
386                 }
387                 strcpy(command, optdefs[ind].name);
388                 if (optdefs[ind].has_arg)
389                         strcat(command, "=xxxx");
390                 fprintf(file, " %s --%-17s %s\n", sht, command, optdefs[ind].help);
391         }
392         fprintf(file,
393                 "Example:\n  %s  --verbose --port="
394                 d2s(DEFAULT_HTTP_PORT)
395                 " --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
396                 name);
397 }
398
399 /*---------------------------------------------------------
400  |   helpers for argument scanning
401  +--------------------------------------------------------- */
402
403 static const char *current_argument(int optid)
404 {
405         if (optarg == 0) {
406                 ERROR("option [--%s] needs a value i.e. --%s=xxx",
407                       name_of_optid(optid), name_of_optid(optid));
408                 exit(1);
409         }
410         return optarg;
411 }
412
413 static char *argvalstr(int optid)
414 {
415         char *result = strdup(current_argument(optid));
416         if (result == NULL) {
417                 ERROR("can't alloc memory");
418                 exit(1);
419         }
420         return result;
421 }
422
423 /**********************************
424 * json helpers
425 ***********************************/
426
427 static struct json_object *joomchk(struct json_object *value)
428 {
429         return oomchk(value);
430 }
431
432 static struct json_object *to_jstr(const char *value)
433 {
434         return joomchk(json_object_new_string(value));
435 }
436
437 static struct json_object *to_jint(int value)
438 {
439         return joomchk(json_object_new_int(value));
440 }
441
442 static struct json_object *to_jbool(int value)
443 {
444         return joomchk(json_object_new_boolean(value));
445 }
446
447 /**********************************
448 * arguments helpers
449 ***********************************/
450
451 static void noarg(int optid)
452 {
453         if (optarg) {
454                 ERROR("option [--%s] need no value (found %s)", name_of_optid(optid), optarg);
455                 exit(1);
456         }
457 }
458
459 static const char *get_arg(int optid)
460 {
461         if (optarg == 0) {
462                 ERROR("option [--%s] needs a value i.e. --%s=xxx",
463                                 name_of_optid(optid), name_of_optid(optid));
464                 exit(1);
465         }
466         return optarg;
467 }
468
469 static void config_del(struct json_object *config, int optid)
470 {
471         return json_object_object_del(config, name_of_optid(optid));
472 }
473
474 static int config_has(struct json_object *config, int optid)
475 {
476         return json_object_object_get_ex(config, name_of_optid(optid), NULL);
477 }
478
479 static int config_has_bool(struct json_object *config, int optid)
480 {
481         struct json_object *x;
482         return json_object_object_get_ex(config, name_of_optid(optid), &x)
483                 && json_object_get_boolean(x);
484 }
485
486 static int config_has_str(struct json_object *config, int optid, const char *val)
487 {
488         int i, n;
489         struct json_object *a;
490
491         if (!json_object_object_get_ex(config, name_of_optid(optid), &a))
492                 return 0;
493
494         if (!json_object_is_type(a, json_type_array))
495                 return !strcmp(val, json_object_get_string(a));
496
497         n = (int)json_object_array_length(a);
498         for (i = 0 ; i < n ; i++) {
499                 if (!strcmp(val, json_object_get_string(json_object_array_get_idx(a, i))))
500                         return 1;
501         }
502         return 0;
503 }
504
505 static void config_set(struct json_object *config, int optid, struct json_object *val)
506 {
507         json_object_object_add(config, name_of_optid(optid), val);
508 }
509
510 static void config_set_str(struct json_object *config, int optid, const char *val)
511 {
512         config_set(config, optid, to_jstr(val));
513 }
514
515 static void config_set_optstr(struct json_object *config, int optid)
516 {
517         config_set_str(config, optid, get_arg(optid));
518 }
519
520 static void config_set_int(struct json_object *config, int optid, int value)
521 {
522         config_set(config, optid, to_jint(value));
523 }
524
525 static void config_set_bool(struct json_object *config, int optid, int value)
526 {
527         config_set(config, optid, to_jbool(value));
528 }
529
530 static void config_set_optint_base(struct json_object *config, int optid, int mini, int maxi, int base)
531 {
532         const char *beg, *end;
533         long int val;
534
535         beg = get_arg(optid);
536         val = strtol(beg, (char**)&end, base);
537         if (*end || end == beg) {
538                 ERROR("option [--%s] requires a valid integer (found %s)",
539                         name_of_optid(optid), beg);
540                 exit(1);
541         }
542         if (val < (long int)mini || val > (long int)maxi) {
543                 ERROR("option [--%s] value %ld out of bounds (not in [%d , %d])",
544                         name_of_optid(optid), val, mini, maxi);
545                 exit(1);
546         }
547         config_set_int(config, optid, (int)val);
548 }
549
550 static void config_set_optint(struct json_object *config, int optid, int mini, int maxi)
551 {
552         return config_set_optint_base(config, optid, mini, maxi, 10);
553 }
554
555 static void config_set_optenum(struct json_object *config, int optid, int (*func)(const char*))
556 {
557         const char *name = get_arg(optid);
558         get_enum_val(name, optid, func);
559         config_set_str(config, optid, name);
560 }
561
562 static void config_add(struct json_object *config, int optid, struct json_object *val)
563 {
564         struct json_object *a;
565         if (!json_object_object_get_ex(config, name_of_optid(optid), &a)) {
566                 a = json_object_new_array();
567                 oomchk(a);
568                 json_object_object_add(config, name_of_optid(optid), a);
569         }
570         json_object_array_add(a, val);
571 }
572
573 static void config_add_str(struct json_object *config, int optid, const char *val)
574 {
575         config_add(config, optid, to_jstr(val));
576 }
577
578 static void config_add_optstr(struct json_object *config, int optid)
579 {
580         config_add_str(config, optid, get_arg(optid));
581 }
582
583 /*---------------------------------------------------------
584  |   set the log levels
585  +--------------------------------------------------------- */
586
587 static void set_log(char *args)
588 {
589         char o = 0, s, *p, *i = args;
590         int lvl;
591
592         for(;;) switch (*i) {
593         case 0:
594                 return;
595         case '+':
596         case '-':
597                 o = *i;
598                 /*@fallthrough@*/
599         case ' ':
600         case ',':
601                 i++;
602                 break;
603         default:
604                 p = i;
605                 while (isalpha(*p)) p++;
606                 s = *p;
607                 *p = 0;
608                 lvl = verbose_level_of_name(i);
609                 if (lvl < 0) {
610                         i = strdupa(i);
611                         *p = s;
612                         ERROR("Bad log name '%s' in %s", i, args);
613                         exit(1);
614                 }
615                 *p = s;
616                 i = p;
617                 if (o == '-')
618                         verbose_sub(lvl);
619                 else {
620                         if (!o) {
621                                 verbose_clear();
622                                 o = '+';
623                         }
624                         verbose_add(lvl);
625                 }
626                 break;
627         }
628 }
629
630 /*---------------------------------------------------------
631  |   Parse option and launch action
632  +--------------------------------------------------------- */
633
634 static void parse_arguments_inner(int argc, char **argv, struct json_object *config, struct option *options)
635 {
636         struct json_object *conf;
637         int optid, cind;
638
639         for (;;) {
640                 cind = optind;
641                 optid = getopt_long(argc, argv, shortopts, options, NULL);
642                 if (optid < 0) {
643                         /* end of options */
644                         break;
645                 }
646                 switch (optid) {
647                 case SET_VERBOSE:
648                         verbose_inc();
649                         break;
650
651                 case SET_QUIET:
652                         verbose_dec();
653                         break;
654
655                 case SET_LOG:
656                         set_log(argvalstr(optid));
657                         break;
658
659                 case SET_PORT:
660                         config_set_optint(config, optid, 1024, 32767);
661                         break;
662
663                 case SET_API_TIMEOUT:
664                 case SET_SESSION_TIMEOUT:
665                 case SET_CACHE_TIMEOUT:
666                         config_set_optint(config, optid, 0, INT_MAX);
667                         break;
668
669                 case SET_SESSIONMAX:
670                         config_set_optint(config, optid, 1, INT_MAX);
671                         break;
672
673                 case SET_ROOT_DIR:
674                 case SET_ROOT_HTTP:
675                 case SET_ROOT_BASE:
676                 case SET_ROOT_API:
677                 case SET_TOKEN:
678                 case SET_UPLOAD_DIR:
679                 case SET_WORK_DIR:
680                 case SET_NAME:
681                         config_set_optstr(config, optid);
682                         break;
683
684 #if defined(WITH_DBUS_TRANSPARENCY)
685                 case ADD_DBUS_CLIENT:
686                 case ADD_DBUS_SERVICE:
687 #endif
688                 case ADD_ALIAS:
689                 case ADD_LDPATH:
690                 case ADD_WEAK_LDPATH:
691                 case ADD_CALL:
692                 case ADD_WS_CLIENT:
693                 case ADD_WS_SERVICE:
694                 case ADD_BINDING:
695                 case ADD_AUTO_API:
696                         config_add_optstr(config, optid);
697                         break;
698
699 #if defined(WITH_MONITORING_OPTION)
700                 case SET_MONITORING:
701 #endif
702                 case SET_RANDOM_TOKEN:
703                 case SET_NO_HTTPD:
704                 case SET_NO_LDPATH:
705                         noarg(optid);
706                         config_set_bool(config, optid, 1);
707                         break;
708
709
710                 case SET_FOREGROUND:
711                 case SET_BACKGROUND:
712                 case SET_DAEMON:
713                         noarg(optid);
714                         config_set_bool(config, SET_DAEMON, optid != SET_FOREGROUND);
715                         break;
716
717                 case SET_TRACEREQ:
718                         config_set_optenum(config, optid, afb_hook_flags_xreq_from_text);
719                         break;
720
721                 case SET_TRACEEVT:
722                         config_set_optenum(config, optid, afb_hook_flags_evt_from_text);
723                         break;
724
725                 case SET_TRACESES:
726                         config_set_optenum(config, optid, afb_hook_flags_session_from_text);
727                         break;
728
729                 case SET_TRACEAPI:
730                         config_set_optenum(config, optid, afb_hook_flags_api_from_text);
731                         break;
732
733                 case SET_TRACEGLOB:
734                         config_set_optenum(config, optid, afb_hook_flags_global_from_text);
735                         break;
736
737 #if !defined(REMOVE_LEGACY_TRACE)
738                 case SET_TRACEDITF:
739                         config_set_optenum(config, optid, afb_hook_flags_legacy_ditf_from_text);
740                         break;
741
742                 case SET_TRACESVC:
743                         config_set_optenum(config, optid, afb_hook_flags_legacy_svc_from_text);
744                         break;
745 #endif
746
747                 case SET_EXEC:
748                         if (optind == argc) {
749                                 ERROR("The option --exec requires arguments");
750                                 exit(1);
751                         }
752                         while (optind != argc)
753                                 config_add_str(config, optid, argv[optind++]);
754                         break;
755
756                 case SET_CONFIG:
757                         conf = json_object_from_file(get_arg(optid));
758                         if (!conf) {
759                                 ERROR("Can't read config file %s", get_arg(optid));
760                                 exit(1);
761                         }
762                         wrap_json_object_add(config, conf);
763                         json_object_put(conf);
764                         break;
765
766                 case GET_VERSION:
767                         noarg(optid);
768                         printVersion(stdout);
769                         exit(0);
770
771                 case GET_HELP:
772                         printHelp(stdout, argv[0]);
773                         exit(0);
774
775                 default:
776                         ERROR("Bad option detected, check %s", argv[cind]);
777                         exit(1);
778                 }
779         }
780         /* TODO: check for extra value */
781 }
782
783 static void parse_arguments(int argc, char **argv, struct json_object *config)
784 {
785         int ind;
786         struct option *options;
787
788         /* create GNU getopt options from optdefs */
789         options = malloc((sizeof optdefs / sizeof * optdefs) * sizeof * options);
790         for (ind = 0; optdefs[ind].name; ind++) {
791                 options[ind].name = optdefs[ind].name;
792                 options[ind].has_arg = optdefs[ind].has_arg;
793                 options[ind].flag = NULL;
794                 options[ind].val = optdefs[ind].id;
795         }
796         memset(&options[ind], 0, sizeof options[ind]);
797
798         /* parse the arguments */
799         parse_arguments_inner(argc, argv, config, options);
800
801         /* release the memory of options */
802         free(options);
803 }
804
805 static void fulfill_config(struct json_object *config)
806 {
807         int i;
808
809         for (i = 0 ; i < sizeof default_optint_values / sizeof * default_optint_values ; i++)
810                 if (!config_has(config, default_optint_values[i].optid))
811                         config_set_int(config, default_optint_values[i].optid, default_optint_values[i].valdef);
812
813         for (i = 0 ; i < sizeof default_optstr_values / sizeof * default_optstr_values ; i++)
814                 if (!config_has(config, default_optstr_values[i].optid))
815                         config_set_str(config, default_optstr_values[i].optid, default_optstr_values[i].valdef);
816
817         // default AUTH_TOKEN
818         if (config_has_bool(config, SET_RANDOM_TOKEN))
819                 config_del(config, SET_TOKEN);
820
821         if (!config_has(config, ADD_LDPATH) && !config_has(config, ADD_WEAK_LDPATH) && !config_has_bool(config, SET_NO_LDPATH))
822                 config_add_str(config, ADD_LDPATH, BINDING_INSTALL_DIR);
823
824 #if defined(WITH_MONITORING_OPTION)
825         if (config_has_bool(config, SET_MONITORING) && !config_has_str(config, ADD_ALIAS, MONITORING_ALIAS))
826                 config_add_str(config, ADD_ALIAS, MONITORING_ALIAS);
827 #endif
828
829 #if !defined(REMOVE_LEGACY_TRACE) && 0
830         config->traceapi |= config->traceditf | config->tracesvc;
831 #endif
832 }
833
834 static void dump(struct json_object *config, FILE *file, const char *prefix, const char *title)
835 {
836         char z;
837         const char *head, *tail;
838
839         if (!prefix) {
840                 z = 0;
841                 prefix = &z;
842         }
843
844         if (title)
845                 fprintf(file, "%s----BEGIN OF %s-----\n", prefix, title);
846
847         head = json_object_to_json_string_ext(config, JSON_C_TO_STRING_PRETTY
848                 |JSON_C_TO_STRING_SPACED|JSON_C_TO_STRING_NOSLASHESCAPE);
849
850         if (head) {
851                 while(*head) {
852                         for (tail = head ; *tail && *tail != '\n' ; tail++);
853                         fprintf(file, "%s %.*s\n", prefix, (int)(tail - head), head);
854                         head = tail + !!*tail;
855                 }
856         }
857
858         if (title)
859                 fprintf(file, "%s----END OF %s-----\n", prefix, title);
860 }
861
862 void afb_config_dump(struct json_object *config)
863 {
864         dump(config, stderr, "--", "CONFIG");
865 }
866
867 static void on_environment_add(struct json_object *config, int optid, const char *name)
868 {
869         char *value = getenv(name);
870
871         if (value && *value)
872                 config_add_str(config, optid, value);
873 }
874
875 static void on_environment_enum(struct json_object *config, int optid, const char *name, int (*func)(const char*))
876 {
877         char *value = getenv(name);
878
879         if (value) {
880                 if (func(value) == -1)
881                         WARNING("Unknown value %s for environment variable %s, ignored", value, name);
882                 else
883                         config_set_str(config, optid, value);
884         }
885 }
886
887 static void parse_environment(struct json_object *config)
888 {
889         on_environment_enum(config, SET_TRACEREQ, "AFB_TRACEREQ", afb_hook_flags_xreq_from_text);
890         on_environment_enum(config, SET_TRACEEVT, "AFB_TRACEEVT", afb_hook_flags_evt_from_text);
891         on_environment_enum(config, SET_TRACESES, "AFB_TRACESES", afb_hook_flags_session_from_text);
892         on_environment_enum(config, SET_TRACEAPI, "AFB_TRACEAPI", afb_hook_flags_api_from_text);
893         on_environment_enum(config, SET_TRACEGLOB, "AFB_TRACEGLOB", afb_hook_flags_global_from_text);
894         on_environment_add(config, ADD_LDPATH, "AFB_LDPATHS");
895 #if !defined(REMOVE_LEGACY_TRACE)
896         on_environment_enum(config, SET_TRACEDITF, "AFB_TRACEDITF", afb_hook_flags_legacy_ditf_from_text);
897         on_environment_enum(config, SET_TRACESVC, "AFB_TRACESVC", afb_hook_flags_legacy_svc_from_text);
898 #endif
899 }
900
901 struct json_object *afb_config_parse_arguments(int argc, char **argv)
902 {
903         struct json_object *result;
904
905         init_options();
906
907         result = json_object_new_object();
908
909         parse_environment(result);
910         parse_arguments(argc, argv, result);
911         fulfill_config(result);
912         if (verbose_wants(Log_Level_Info))
913                 afb_config_dump(result);
914         return result;
915 }
916
917 struct json_object *afb_config_json(struct json_object *config)
918 {
919         return NULL;
920 }
921