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