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