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