afb-args: Fix output of --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                 "+"
379 #else
380                 "-"
381 #endif
382                 "BINDINGS "
383 #if WITH_LEGACY_BINDING_V1
384                 "+V1 "
385 #endif
386 #if WITH_LEGACY_BINDING_VDYN
387                 "+VDYN "
388 #endif
389 #if WITH_LEGACY_BINDING_V2
390                 "+V2 "
391 #endif
392                 "+V3]\n"
393                 "\n",
394                 AFB_VERSION
395         );
396         fprintf(file,
397                 "  Copyright (C) 2015-2019 \"IoT.bzh\"\n"
398                 "  AFB comes with ABSOLUTELY NO WARRANTY.\n"
399                 "  Licence Apache 2\n"
400                 "\n");
401 }
402
403 /*----------------------------------------------------------
404  | printHelp
405  |   print information from long option array
406  +--------------------------------------------------------- */
407
408 static void printHelp(FILE * file, const char *name)
409 {
410         int ind;
411         char command[50], sht[4];
412
413         fprintf(file, "%s:\nallowed options\n", strrchr(name, '/') ? strrchr(name, '/') + 1 : name);
414         sht[3] = 0;
415         for (ind = 0; optdefs[ind].name != NULL; ind++) {
416                 if (is_short_option(optdefs[ind].id)) {
417                         sht[0] = '-';
418                         sht[1] = (char)optdefs[ind].id;
419                         sht[2] = ',';
420                 } else {
421                         sht[0] = sht[1] = sht[2] = ' ';
422                 }
423                 strcpy(command, optdefs[ind].name);
424                 if (optdefs[ind].has_arg)
425                         strcat(command, "=xxxx");
426                 fprintf(file, " %s --%-17s %s\n", sht, command, optdefs[ind].help);
427         }
428         fprintf(file,
429                 "Example:\n  %s  --verbose --port="
430                 d2s(DEFAULT_HTTP_PORT)
431                 " --token='azerty'"
432 #if WITH_DYNAMIC_BINDING
433                 " --ldpaths=build/bindings:/usr/lib64/agl/bindings"
434 #endif
435                 "\n",
436                 name);
437 }
438
439 static void dump(struct json_object *config, FILE *file, const char *prefix, const char *title)
440 {
441         const char *head, *tail;
442
443         if (title)
444                 fprintf(file, "%s----BEGIN OF %s-----\n", prefix ?: "", title);
445
446         head = json_object_to_json_string_ext(config, JSON_C_TO_STRING_PRETTY
447                 |JSON_C_TO_STRING_SPACED|JSON_C_TO_STRING_NOSLASHESCAPE);
448
449         if (!prefix)
450                 fprintf(file, "%s\n", head);
451         else {
452                 while(*head) {
453                         for (tail = head ; *tail && *tail != '\n' ; tail++);
454                         fprintf(file, "%s %.*s\n", prefix, (int)(tail - head), head);
455                         head = tail + !!*tail;
456                 }
457         }
458
459         if (title)
460                 fprintf(file, "%s----END OF %s-----\n", prefix ?: "", title);
461 }
462
463 /**********************************
464 * json helpers
465 ***********************************/
466
467 static struct json_object *joomchk(struct json_object *value)
468 {
469         return oomchk(value);
470 }
471
472 static struct json_object *to_jstr(const char *value)
473 {
474         return joomchk(json_object_new_string(value));
475 }
476
477 static struct json_object *to_jint(int value)
478 {
479         return joomchk(json_object_new_int(value));
480 }
481
482 static struct json_object *to_jbool(int value)
483 {
484         return joomchk(json_object_new_boolean(value));
485 }
486
487 /**********************************
488 * arguments helpers
489 ***********************************/
490
491 static int string_to_bool(const char *value)
492 {
493         static const char true_names[] = "1\0yes\0true\0on";
494         static const char false_names[] = "0\0no\0false\0off";
495         size_t pos;
496
497         pos = 0;
498         while (pos < sizeof true_names)
499                 if (strcasecmp(value, &true_names[pos]))
500                         pos += 1 + strlen(&true_names[pos]);
501                 else
502                         return 1;
503
504         pos = 0;
505         while (pos < sizeof false_names)
506                 if (strcasecmp(value, &false_names[pos]))
507                         pos += 1 + strlen(&false_names[pos]);
508                 else
509                         return 0;
510
511         return -1;
512 }
513
514 static void noarg(int optid)
515 {
516         if (optarg) {
517                 ERROR("option [--%s] need no value (found %s)", name_of_optid(optid), optarg);
518                 exit(1);
519         }
520 }
521
522 static const char *get_arg(int optid)
523 {
524         if (optarg == 0) {
525                 ERROR("option [--%s] needs a value i.e. --%s=xxx",
526                                 name_of_optid(optid), name_of_optid(optid));
527                 exit(1);
528         }
529         return optarg;
530 }
531
532 static int get_arg_bool(int optid)
533 {
534         int value = string_to_bool(get_arg(optid));
535         if (value < 0) {
536                 ERROR("option [--%s] needs a boolean value: yes/no, true/false, on/off, 1/0",
537                                 name_of_optid(optid));
538                 exit(1);
539         }
540         return value;
541 }
542
543 static void config_del(struct json_object *config, int optid)
544 {
545         return json_object_object_del(config, name_of_optid(optid));
546 }
547
548 static int config_has(struct json_object *config, int optid)
549 {
550         return json_object_object_get_ex(config, name_of_optid(optid), NULL);
551 }
552
553 static int config_has_bool(struct json_object *config, int optid)
554 {
555         struct json_object *x;
556         return json_object_object_get_ex(config, name_of_optid(optid), &x)
557                 && json_object_get_boolean(x);
558 }
559
560 __attribute__((unused))
561 static int config_has_str(struct json_object *config, int optid, const char *val)
562 {
563         int i, n;
564         struct json_object *a;
565
566         if (!json_object_object_get_ex(config, name_of_optid(optid), &a))
567                 return 0;
568
569         if (!json_object_is_type(a, json_type_array))
570                 return !strcmp(val, json_object_get_string(a));
571
572         n = (int)json_object_array_length(a);
573         for (i = 0 ; i < n ; i++) {
574                 if (!strcmp(val, json_object_get_string(json_object_array_get_idx(a, i))))
575                         return 1;
576         }
577         return 0;
578 }
579
580 static void config_set(struct json_object *config, int optid, struct json_object *val)
581 {
582         json_object_object_add(config, name_of_optid(optid), val);
583 }
584
585 static void config_set_str(struct json_object *config, int optid, const char *val)
586 {
587         config_set(config, optid, to_jstr(val));
588 }
589
590 static void config_set_optstr(struct json_object *config, int optid)
591 {
592         config_set_str(config, optid, get_arg(optid));
593 }
594
595 static void config_set_int(struct json_object *config, int optid, int value)
596 {
597         config_set(config, optid, to_jint(value));
598 }
599
600 static void config_set_bool(struct json_object *config, int optid, int value)
601 {
602         config_set(config, optid, to_jbool(value));
603 }
604
605 static void config_set_optint_base(struct json_object *config, int optid, int mini, int maxi, int base)
606 {
607         const char *beg, *end;
608         long int val;
609
610         beg = get_arg(optid);
611         val = strtol(beg, (char**)&end, base);
612         if (*end || end == beg) {
613                 ERROR("option [--%s] requires a valid integer (found %s)",
614                         name_of_optid(optid), beg);
615                 exit(1);
616         }
617         if (val < (long int)mini || val > (long int)maxi) {
618                 ERROR("option [--%s] value %ld out of bounds (not in [%d , %d])",
619                         name_of_optid(optid), val, mini, maxi);
620                 exit(1);
621         }
622         config_set_int(config, optid, (int)val);
623 }
624
625 static void config_set_optint(struct json_object *config, int optid, int mini, int maxi)
626 {
627         return config_set_optint_base(config, optid, mini, maxi, 10);
628 }
629
630 __attribute__((unused))
631 static void config_set_optenum(struct json_object *config, int optid, int (*func)(const char*))
632 {
633         const char *name = get_arg(optid);
634         get_enum_val(name, optid, func);
635         config_set_str(config, optid, name);
636 }
637
638 static void config_add(struct json_object *config, int optid, struct json_object *val)
639 {
640         struct json_object *a;
641         if (!json_object_object_get_ex(config, name_of_optid(optid), &a)) {
642                 a = joomchk(json_object_new_array());
643                 json_object_object_add(config, name_of_optid(optid), a);
644         }
645         json_object_array_add(a, val);
646 }
647
648 static void config_add_str(struct json_object *config, int optid, const char *val)
649 {
650         config_add(config, optid, to_jstr(val));
651 }
652
653 static void config_add_optstr(struct json_object *config, int optid)
654 {
655         config_add_str(config, optid, get_arg(optid));
656 }
657
658 static void config_mix2_cb(void *closure, struct json_object *obj, const char *name)
659 {
660         struct json_object *dest, *base = closure;
661
662         if (!name)
663                 name = "";
664
665         if (!json_object_object_get_ex(base, name, &dest)) {
666                 dest = joomchk(json_object_new_object());
667                 json_object_object_add(base, name, dest);
668         }
669         if (json_object_is_type(obj, json_type_object))
670                 wrap_json_object_add(dest, obj);
671         else
672                 json_object_object_add(dest, "", json_object_get(obj));
673 }
674
675 static void config_mix2(struct json_object *config, int optid, struct json_object *val)
676 {
677         struct json_object *obj;
678
679         if (!json_object_object_get_ex(config, name_of_optid(optid), &obj)) {
680                 obj = joomchk(json_object_new_object());
681                 json_object_object_add(config, name_of_optid(optid), obj);
682         }
683         wrap_json_for_all(val, config_mix2_cb, obj);
684 }
685
686 static void config_mix2_str(struct json_object *config, int optid, const char *val)
687 {
688         size_t st1, st2;
689         const char *api, *key;
690         struct json_object *obj, *sub;
691         enum json_tokener_error jerr;
692
693         st1 = strcspn(val, "/:{[\"");
694         st2 = strcspn(&val[st1], ":{[\"");
695         if (val[st1] != '/' || val[st1 + st2] != ':') {
696                 obj = json_tokener_parse_verbose(val, &jerr);
697                 if (jerr != json_tokener_success)
698                         obj = json_object_new_string(val);
699         } else {
700                 api = st1 == 0 ? "*" : strndupa(val, st1);
701                 val += st1 + 1;
702                 key = st2 <= 1 || (st2 == 2 && *val == '*') ? NULL : strndupa(val, st2 - 1);
703                 val += st2;
704                 sub = json_tokener_parse_verbose(val, &jerr);
705                 if (jerr != json_tokener_success)
706                         sub = json_object_new_string(val);
707
708                 if (key) {
709                         obj = json_object_new_object();
710                         json_object_object_add(obj, key, sub);
711                         sub = obj;
712                 }
713                 obj = json_object_new_object();
714                 json_object_object_add(obj, api, sub);
715         }
716         config_mix2(config, optid, obj);
717         json_object_put(obj);
718 }
719
720 static void config_mix2_optstr(struct json_object *config, int optid)
721 {
722         config_mix2_str(config, optid, get_arg(optid));
723 }
724
725 /*---------------------------------------------------------
726  |   set the log levels
727  +--------------------------------------------------------- */
728
729 static void set_log(const char *args)
730 {
731         char o = 0, s, *p, *i = strdupa(args);
732         int lvl;
733
734         for(;;) switch (*i) {
735         case 0:
736                 return;
737         case '+':
738         case '-':
739                 o = *i;
740                 /*@fallthrough@*/
741         case ' ':
742         case ',':
743                 i++;
744                 break;
745         default:
746                 p = i;
747                 while (isalpha(*p)) p++;
748                 s = *p;
749                 *p = 0;
750                 lvl = verbose_level_of_name(i);
751                 if (lvl < 0) {
752                         i = strdupa(i);
753                         *p = s;
754                         ERROR("Bad log name '%s' in %s", i, args);
755                         exit(1);
756                 }
757                 *p = s;
758                 i = p;
759                 if (o == '-')
760                         verbose_sub(lvl);
761                 else {
762                         if (!o) {
763                                 verbose_clear();
764                                 o = '+';
765                         }
766                         verbose_add(lvl);
767                 }
768                 break;
769         }
770 }
771
772 /*---------------------------------------------------------
773  |   Parse option and launch action
774  +--------------------------------------------------------- */
775
776 static void parse_arguments_inner(int argc, char **argv, struct json_object *config, struct option *options)
777 {
778         struct json_object *conf;
779         int optid, cind, dodump = 0;
780
781         for (;;) {
782                 cind = optind;
783                 optid = getopt_long(argc, argv, shortopts, options, NULL);
784                 if (optid < 0) {
785                         /* end of options */
786                         break;
787                 }
788                 switch (optid) {
789                 case SET_VERBOSE:
790                         verbose_inc();
791                         break;
792
793                 case SET_COLOR:
794                         verbose_colorize();
795                         break;
796
797                 case SET_QUIET:
798                         verbose_dec();
799                         break;
800
801                 case SET_LOG:
802                         set_log(get_arg(optid));
803                         break;
804
805                 case SET_PORT:
806                         config_set_optint(config, optid, 1024, 32767);
807                         break;
808
809                 case SET_API_TIMEOUT:
810                 case SET_SESSION_TIMEOUT:
811                 case SET_CACHE_TIMEOUT:
812                         config_set_optint(config, optid, 0, INT_MAX);
813                         break;
814
815                 case SET_SESSIONMAX:
816                         config_set_optint(config, optid, 1, INT_MAX);
817                         break;
818
819                 case SET_ROOT_DIR:
820                 case SET_ROOT_HTTP:
821                 case SET_ROOT_BASE:
822                 case SET_ROOT_API:
823                 case SET_TOKEN:
824                 case SET_UPLOAD_DIR:
825                 case SET_WORK_DIR:
826                 case SET_NAME:
827                         config_set_optstr(config, optid);
828                         break;
829
830 #if WITH_DBUS_TRANSPARENCY
831                 case ADD_DBUS_CLIENT:
832                 case ADD_DBUS_SERVICE:
833 #endif
834                 case ADD_ALIAS:
835 #if WITH_DYNAMIC_BINDING
836                 case ADD_LDPATH:
837                 case ADD_WEAK_LDPATH:
838                 case ADD_BINDING:
839 #endif
840                 case ADD_CALL:
841                 case ADD_WS_CLIENT:
842                 case ADD_WS_SERVICE:
843                 case ADD_AUTO_API:
844                         config_add_optstr(config, optid);
845                         break;
846
847                 case ADD_SET:
848                         config_mix2_optstr(config, optid);
849                         break;
850
851 #if defined(WITH_MONITORING_OPTION)
852                 case SET_MONITORING:
853 #endif
854                 case SET_RANDOM_TOKEN:
855                 case SET_NO_HTTPD:
856 #if WITH_DYNAMIC_BINDING
857                 case SET_NO_LDPATH:
858 #endif
859                         noarg(optid);
860                         config_set_bool(config, optid, 1);
861                         break;
862
863
864                 case SET_FOREGROUND:
865                 case SET_BACKGROUND:
866                 case SET_DAEMON:
867                         noarg(optid);
868                         config_set_bool(config, SET_DAEMON, optid != SET_FOREGROUND);
869                         break;
870
871                 case SET_TRAP_FAULTS:
872                         config_set_bool(config, optid, get_arg_bool(optid));
873                         break;
874
875
876 #if WITH_AFB_HOOK
877                 case SET_TRACEREQ:
878                         config_set_optenum(config, optid, afb_hook_flags_xreq_from_text);
879                         break;
880
881                 case SET_TRACEEVT:
882                         config_set_optenum(config, optid, afb_hook_flags_evt_from_text);
883                         break;
884
885                 case SET_TRACESES:
886                         config_set_optenum(config, optid, afb_hook_flags_session_from_text);
887                         break;
888
889                 case SET_TRACEAPI:
890                         config_set_optenum(config, optid, afb_hook_flags_api_from_text);
891                         break;
892
893                 case SET_TRACEGLOB:
894                         config_set_optenum(config, optid, afb_hook_flags_global_from_text);
895                         break;
896
897 #if !defined(REMOVE_LEGACY_TRACE)
898                 case SET_TRACEDITF:
899                         config_set_optenum(config, optid, afb_hook_flags_legacy_ditf_from_text);
900                         break;
901
902                 case SET_TRACESVC:
903                         config_set_optenum(config, optid, afb_hook_flags_legacy_svc_from_text);
904                         break;
905 #endif
906 #endif
907
908                 case SET_EXEC:
909                         if (optind == argc) {
910                                 ERROR("The option --exec requires arguments");
911                                 exit(1);
912                         }
913                         while (optind != argc)
914                                 config_add_str(config, optid, argv[optind++]);
915                         break;
916
917                 case SET_CONFIG:
918                         conf = json_object_from_file(get_arg(optid));
919                         if (!conf) {
920                                 ERROR("Can't read config file %s", get_arg(optid));
921                                 exit(1);
922                         }
923                         wrap_json_object_add(config, conf);
924                         json_object_put(conf);
925                         break;
926
927                 case DUMP_CONFIG:
928                         noarg(optid);
929                         dodump = 1;
930                         break;
931
932                 case GET_VERSION:
933                         noarg(optid);
934                         printVersion(stdout);
935                         exit(0);
936
937                 case GET_HELP:
938                         printHelp(stdout, argv[0]);
939                         exit(0);
940
941                 default:
942                         ERROR("Bad option detected, check %s", argv[cind]);
943                         exit(1);
944                 }
945         }
946         /* TODO: check for extra value */
947
948         if (dodump) {
949                 dump(config, stdout, NULL, NULL);
950                 exit(0);
951         }
952 }
953
954 static void parse_arguments(int argc, char **argv, struct json_object *config)
955 {
956         int ind;
957         struct option *options;
958
959         /* create GNU getopt options from optdefs */
960         options = malloc((sizeof optdefs / sizeof * optdefs) * sizeof * options);
961         for (ind = 0; optdefs[ind].name; ind++) {
962                 options[ind].name = optdefs[ind].name;
963                 options[ind].has_arg = optdefs[ind].has_arg;
964                 options[ind].flag = NULL;
965                 options[ind].val = optdefs[ind].id;
966         }
967         memset(&options[ind], 0, sizeof options[ind]);
968
969         /* parse the arguments */
970         parse_arguments_inner(argc, argv, config, options);
971
972         /* release the memory of options */
973         free(options);
974 }
975
976 static void fulfill_config(struct json_object *config)
977 {
978         int i;
979
980         for (i = 0 ; i < sizeof default_optint_values / sizeof * default_optint_values ; i++)
981                 if (!config_has(config, default_optint_values[i].optid))
982                         config_set_int(config, default_optint_values[i].optid, default_optint_values[i].valdef);
983
984         for (i = 0 ; i < sizeof default_optstr_values / sizeof * default_optstr_values ; i++)
985                 if (!config_has(config, default_optstr_values[i].optid))
986                         config_set_str(config, default_optstr_values[i].optid, default_optstr_values[i].valdef);
987
988         // default AUTH_TOKEN
989         if (config_has_bool(config, SET_RANDOM_TOKEN))
990                 config_del(config, SET_TOKEN);
991
992 #if WITH_DYNAMIC_BINDING && defined(INTRINSIC_BINDING_DIR)
993         if (!config_has(config, ADD_LDPATH) && !config_has(config, ADD_WEAK_LDPATH) && !config_has_bool(config, SET_NO_LDPATH))
994                 config_add_str(config, ADD_LDPATH, INTRINSIC_BINDING_DIR);
995 #endif
996
997 #if defined(WITH_MONITORING_OPTION)
998         if (config_has_bool(config, SET_MONITORING) && !config_has_str(config, ADD_ALIAS, MONITORING_ALIAS))
999                 config_add_str(config, ADD_ALIAS, MONITORING_ALIAS);
1000 #endif
1001
1002 #if !defined(REMOVE_LEGACY_TRACE) && 0
1003         config->traceapi |= config->traceditf | config->tracesvc;
1004 #endif
1005 }
1006
1007 static void on_environment(struct json_object *config, int optid, const char *name, void (*func)(struct json_object*, int, const char*))
1008 {
1009         char *value = secure_getenv(name);
1010
1011         if (value && *value)
1012                 func(config, optid, value);
1013 }
1014
1015 __attribute__((unused))
1016 static void on_environment_enum(struct json_object *config, int optid, const char *name, int (*func)(const char*))
1017 {
1018         char *value = secure_getenv(name);
1019
1020         if (value) {
1021                 if (func(value) == -1)
1022                         WARNING("Unknown value %s for environment variable %s, ignored", value, name);
1023                 else
1024                         config_set_str(config, optid, value);
1025         }
1026 }
1027
1028 static void on_environment_bool(struct json_object *config, int optid, const char *name)
1029 {
1030         char *value = secure_getenv(name);
1031         int asbool;
1032
1033         if (value) {
1034                 asbool = string_to_bool(value);
1035                 if (asbool < 0)
1036                         WARNING("Unknown value %s for environment variable %s, ignored", value, name);
1037                 else
1038                         config_set_bool(config, optid, asbool);
1039         }
1040 }
1041
1042 static void parse_environment(struct json_object *config)
1043 {
1044 #if WITH_AFB_HOOK
1045         on_environment_enum(config, SET_TRACEREQ, "AFB_TRACEREQ", afb_hook_flags_xreq_from_text);
1046         on_environment_enum(config, SET_TRACEEVT, "AFB_TRACEEVT", afb_hook_flags_evt_from_text);
1047         on_environment_enum(config, SET_TRACESES, "AFB_TRACESES", afb_hook_flags_session_from_text);
1048         on_environment_enum(config, SET_TRACEAPI, "AFB_TRACEAPI", afb_hook_flags_api_from_text);
1049         on_environment_enum(config, SET_TRACEGLOB, "AFB_TRACEGLOB", afb_hook_flags_global_from_text);
1050 #if !defined(REMOVE_LEGACY_TRACE)
1051         on_environment_enum(config, SET_TRACEDITF, "AFB_TRACEDITF", afb_hook_flags_legacy_ditf_from_text);
1052         on_environment_enum(config, SET_TRACESVC, "AFB_TRACESVC", afb_hook_flags_legacy_svc_from_text);
1053 #endif
1054 #endif
1055 #if WITH_DYNAMIC_BINDING
1056         on_environment(config, ADD_LDPATH, "AFB_LDPATHS", config_add_str);
1057 #endif
1058         on_environment(config, ADD_SET, "AFB_SET", config_mix2_str);
1059         on_environment_bool(config, SET_TRAP_FAULTS, "AFB_TRAP_FAULTS");
1060 }
1061
1062 struct json_object *afb_args_parse(int argc, char **argv)
1063 {
1064         struct json_object *result;
1065
1066         init_options();
1067
1068         result = json_object_new_object();
1069
1070         parse_environment(result);
1071         parse_arguments(argc, argv, result);
1072         fulfill_config(result);
1073         if (verbose_wants(Log_Level_Info))
1074                 dump(result, stderr, "--", "CONFIG");
1075         return result;
1076 }
1077
1078