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