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