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