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