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