json-c: Remove escaping of slashs
[src/app-framework-binder.git] / src / afb-config.c
1 /*
2  * Copyright (C) 2015-2018 "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-config.h"
35 #include "afb-hook.h"
36
37 #define _d2s_(x)  #x
38 #define d2s(x)    _d2s_(x)
39
40 #if !defined(BINDING_INSTALL_DIR)
41 #error "you should define BINDING_INSTALL_DIR"
42 #endif
43 #if !defined(AFB_VERSION)
44 #error "you should define AFB_VERSION"
45 #endif
46
47 /**
48  * The default timeout of sessions in seconds
49  */
50 #define DEFAULT_SESSION_TIMEOUT         32000000
51
52 /**
53  * The default timeout of api calls in seconds
54  */
55 #define DEFAULT_API_TIMEOUT             20
56
57 /**
58  * The default timeout of cache in seconds
59  */
60 #define DEFAULT_CACHE_TIMEOUT           100000
61
62 /**
63  * The default maximum count of sessions
64  */
65 #define DEFAULT_MAX_SESSION_COUNT       200
66
67 /**
68  * The default HTTP port to serve
69  */
70 #define DEFAULT_HTTP_PORT               1234
71
72 // Define command line option
73 #define SET_BACKGROUND     1
74 #define SET_FORGROUND      2
75 #define SET_ROOT_DIR       3
76 #define SET_ROOT_BASE      4
77 #define SET_ROOT_API       5
78 #define SET_ALIAS          6
79
80 #define SET_CACHE_TIMEOUT  7
81
82 #define AUTO_WS            8
83 #define AUTO_LINK          9
84
85 #define SET_LDPATH         10
86 #define SET_APITIMEOUT     11
87 #define SET_CNTXTIMEOUT    12
88 #define SET_WEAK_LDPATH    13
89 #define NO_LDPATH          14
90
91 #define SET_SESSIONMAX     15
92
93 #define WS_CLIENT          16
94 #define 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 #if !defined(REMOVE_LEGACY_TRACE)
105 #define SET_TRACEDITF      24
106 #define SET_TRACESVC       25
107 #endif
108
109 #if defined(WITH_DBUS_TRANSPARENCY)
110 #   define DBUS_CLIENT        30
111 #   define DBUS_SERVICE       31
112 #endif
113
114
115 #define AUTO_API           'A'
116 #define SO_BINDING         'b'
117 #define ADD_CALL           'c'
118 #define SET_EXEC           'e'
119 #define DISPLAY_HELP       'h'
120 #define SET_LOG            'l'
121 #if defined(WITH_MONITORING_OPTION)
122 #define SET_MONITORING     'M'
123 #endif
124 #define SET_NAME           'n'
125 #define SET_TCP_PORT       'p'
126 #define SET_QUIET          'q'
127 #define SET_RNDTOKEN       'r'
128 #define SET_AUTH_TOKEN     't'
129 #define SET_UPLOAD_DIR     'u'
130 #define DISPLAY_VERSION    'V'
131 #define SET_VERBOSE        'v'
132 #define SET_WORK_DIR       'w'
133
134 const char shortopts[] =
135         "A:"
136         "b:"
137         "c:"
138         "e"
139         "h"
140         "l:"
141 #if defined(WITH_MONITORING_OPTION)
142         "M"
143 #endif
144         "n:"
145         "p:"
146         "q"
147         "r"
148         "t:"
149         "u:"
150         "V"
151         "v"
152         "w:"
153 ;
154
155 // Command line structure hold cli --command + help text
156 typedef struct {
157         int val;                // command number within application
158         int has_arg;            // command number within application
159         char *name;             // command as used in --xxxx cli
160         char *help;             // help text
161 } AFB_options;
162
163 // Supported option
164 static AFB_options cliOptions[] = {
165 /* *INDENT-OFF* */
166         {SET_VERBOSE,       0, "verbose",     "Verbose Mode, repeat to increase verbosity"},
167         {SET_QUIET,         0, "quiet",       "Quiet Mode, repeat to decrease verbosity"},
168         {SET_LOG,           1, "log",         "Tune log level"},
169
170         {SET_FORGROUND,     0, "foreground",  "Get all in foreground mode"},
171         {SET_BACKGROUND,    0, "daemon",      "Get all in background mode"},
172
173         {SET_NAME,          1, "name",        "Set the visible name"},
174
175         {SET_TCP_PORT,      1, "port",        "HTTP listening TCP port  [default " d2s(DEFAULT_HTTP_PORT) "]"},
176         {SET_ROOT_HTTP,     1, "roothttp",    "HTTP Root Directory [default no root http (files not served but apis still available)]"},
177         {SET_ROOT_BASE,     1, "rootbase",    "Angular Base Root URL [default /opa]"},
178         {SET_ROOT_API,      1, "rootapi",     "HTML Root API URL [default /api]"},
179         {SET_ALIAS,         1, "alias",       "Multiple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
180
181         {SET_APITIMEOUT,    1, "apitimeout",  "Binding API timeout in seconds [default " d2s(DEFAULT_API_TIMEOUT) "]"},
182         {SET_CNTXTIMEOUT,   1, "cntxtimeout", "Client Session Context Timeout [default " d2s(DEFAULT_SESSION_TIMEOUT) "]"},
183         {SET_CACHE_TIMEOUT, 1, "cache-eol",   "Client cache end of live [default " d2s(DEFAULT_CACHE_TIMEOUT) "]"},
184
185         {SET_WORK_DIR,      1, "workdir",     "Set the working directory [default: $PWD or current working directory]"},
186         {SET_UPLOAD_DIR,    1, "uploaddir",   "Directory for uploading files [default: workdir]"},
187         {SET_ROOT_DIR,      1, "rootdir",     "Root Directory of the application [default: workdir]"},
188
189         {SET_LDPATH,        1, "ldpaths",     "Load bindings from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
190         {SO_BINDING,        1, "binding",     "Load the binding of path"},
191         {SET_WEAK_LDPATH,   1, "weak-ldpaths","Same as --ldpaths but ignore errors"},
192         {NO_LDPATH,         0, "no-ldpaths",  "Discard default ldpaths loading"},
193
194         {SET_AUTH_TOKEN,    1, "token",       "Initial Secret [default=random, use --token="" to allow any token]"},
195         {SET_RNDTOKEN,      0, "random-token","Enforce a random token"},
196
197         {DISPLAY_VERSION,   0, "version",     "Display version and copyright"},
198         {DISPLAY_HELP,      0, "help",        "Display this help"},
199
200 #if defined(WITH_DBUS_TRANSPARENCY)
201         {DBUS_CLIENT,       1, "dbus-client", "Bind to an afb service through dbus"},
202         {DBUS_SERVICE,      1, "dbus-server", "Provide an afb service through dbus"},
203 #endif
204         {WS_CLIENT,         1, "ws-client",   "Bind to an afb service through websocket"},
205         {WS_SERVICE,        1, "ws-server",   "Provide an afb service through websockets"},
206
207         {AUTO_API,          1, "auto-api",    "Automatic load of api of the given directory"},
208
209         {SET_SESSIONMAX,    1, "session-max", "Max count of session simultaneously [default " d2s(DEFAULT_MAX_SESSION_COUNT) "]"},
210
211         {SET_TRACEREQ,      1, "tracereq",    "Log the requests: no, common, extra, 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         {SET_TRACEEVT,      1, "traceevt",    "Log the events: no, common, extra, all"},
217         {SET_TRACESES,      1, "traceses",    "Log the sessions: no, all"},
218         {SET_TRACEAPI,      1, "traceapi",    "Log the apis: no, common, api, event, all"},
219
220         {ADD_CALL,          1, "call",        "call at start format of val: API/VERB:json-args"},
221
222         {SET_NO_HTTPD,      0, "no-httpd",    "Forbid HTTP service"},
223         {SET_EXEC,          0, "exec",        "Execute the remaining arguments"},
224
225 #if defined(WITH_MONITORING_OPTION)
226         {SET_MONITORING,    0, "monitoring",  "Enable HTTP monitoring at <ROOT>/monitoring/"},
227 #endif
228         {0, 0, NULL, NULL}
229 /* *INDENT-ON* */
230 };
231
232
233 struct enumdesc
234 {
235         const char *name;
236         int value;
237 };
238
239 static struct enumdesc tracereq_desc[] = {
240         { "no",     0 },
241         { "common", afb_hook_flags_req_common },
242         { "extra",  afb_hook_flags_req_extra },
243         { "all",    afb_hook_flags_req_all },
244         { NULL, 0 }
245 };
246
247 #if !defined(REMOVE_LEGACY_TRACE)
248 static struct enumdesc traceditf_desc[] = {
249         { "no",     0 },
250         { "common", afb_hook_flags_api_ditf_common },
251         { "all",    afb_hook_flags_api_ditf_all },
252         { NULL, 0 }
253 };
254
255 static struct enumdesc tracesvc_desc[] = {
256         { "no",     0 },
257         { "all",    afb_hook_flags_api_svc_all },
258         { NULL, 0 }
259 };
260 #endif
261
262 static struct enumdesc traceevt_desc[] = {
263         { "no",     0 },
264         { "common", afb_hook_flags_evt_common },
265         { "extra",  afb_hook_flags_evt_extra },
266         { "all",    afb_hook_flags_evt_all },
267         { NULL, 0 }
268 };
269
270 static struct enumdesc traceses_desc[] = {
271         { "no",     0 },
272         { "common", afb_hook_flags_session_common },
273         { "all",    afb_hook_flags_session_all },
274         { NULL, 0 }
275 };
276
277 static struct enumdesc traceapi_desc[] = {
278         { "no",         0 },
279         { "common",     afb_hook_flags_api_common },
280         { "api",        afb_hook_flags_api_api|afb_hook_flag_api_start },
281         { "event",      afb_hook_flags_api_event|afb_hook_flag_api_start },
282         { "all",        afb_hook_flags_api_all },
283         { NULL, 0 }
284 };
285
286 /*----------------------------------------------------------
287  | printversion
288  |   print version and copyright
289  +--------------------------------------------------------- */
290 static void printVersion(FILE * file)
291 {
292         fprintf(file,
293                 "\n"
294                 "  AGL Framework Binder [AFB %s] "
295 #if defined(WITH_DBUS_TRANSPARENCY)
296                 "+"
297 #else
298                 "-"
299 #endif
300                 "DBUS "
301 #if defined(WITH_MONITORING_OPTION)
302                 "+"
303 #else
304                 "-"
305 #endif
306                 "MONITOR "
307 #if defined(WITH_SUPERVISION)
308                 "+"
309 #else
310                 "-"
311 #endif
312                 "SUPERVISION [BINDINGS "
313 #if defined(WITH_LEGACY_BINDING_V1)
314                 "+"
315 #else
316                 "-"
317 #endif
318                 "V1 "
319 #if defined(WITH_LEGACY_BINDING_VDYN)
320                 "+"
321 #else
322                 "-"
323 #endif
324                 "VDYN +V2 +V3]\n"
325                 "\n",
326                 AFB_VERSION
327         );
328         fprintf(file,
329                 "  Copyright (C) 2015-2018 \"IoT.bzh\"\n"
330                 "  AFB comes with ABSOLUTELY NO WARRANTY.\n"
331                 "  Licence Apache 2\n"
332                 "\n");
333 }
334
335 /*----------------------------------------------------------
336  | printHelp
337  |   print information from long option array
338  +--------------------------------------------------------- */
339
340 static void printHelp(FILE * file, const char *name)
341 {
342         int ind;
343         char command[50], sht[4];
344
345         sht[3] = 0;
346         fprintf(file, "%s:\nallowed options\n", name);
347         for (ind = 0; cliOptions[ind].name != NULL; ind++) {
348                 if (((cliOptions[ind].val >= 'a' && cliOptions[ind].val <= 'z')
349                  || (cliOptions[ind].val >= 'A' && cliOptions[ind].val <= 'Z')
350                  || (cliOptions[ind].val >= '0' && cliOptions[ind].val <= '9'))
351                  && strchr(shortopts, (char)cliOptions[ind].val)) {
352                         sht[0] = '-';
353                         sht[1] = (char)cliOptions[ind].val;
354                         sht[2] = ',';
355                 } else {
356                         sht[0] = sht[1] = sht[2] = ' ';
357                 }
358                 strcpy(command, cliOptions[ind].name);
359                 if (cliOptions[ind].has_arg)
360                         strcat(command, "=xxxx");
361                 fprintf(file, " %s --%-17s %s\n", sht, command, cliOptions[ind].help);
362         }
363         fprintf(file,
364                 "Example:\n  %s  --verbose --port=" d2s(DEFAULT_HTTP_PORT) " --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
365                 name);
366 }
367
368
369 /*----------------------------------------------------------
370  |   adds a string to the list
371  +--------------------------------------------------------- */
372 static void list_add(struct afb_config_list **head, char *value)
373 {
374         struct afb_config_list *item;
375
376         /*
377          * search tail
378          */
379         item = *head;
380         while (item != NULL) {
381                 head = &item->next;
382                 item = item->next;
383         }
384
385         /*
386          * alloc the item
387          */
388         item = malloc(sizeof *item);
389         if (item == NULL) {
390                 ERROR("out of memory");
391                 exit(1);
392         }
393
394         /*
395          * init the item
396          */
397         *head = item;
398         item->value = value;
399         item->next = NULL;
400 }
401
402 /*---------------------------------------------------------
403  |   helpers for argument scanning
404  +--------------------------------------------------------- */
405
406 static const char *name_of_option(int optc)
407 {
408         AFB_options *o = cliOptions;
409         while (o->name && o->val != optc)
410                 o++;
411         return o->name ? : "<unknown-option-name>";
412 }
413
414 static const char *current_argument(int optc)
415 {
416         if (optarg == 0) {
417                 ERROR("option [--%s] needs a value i.e. --%s=xxx",
418                       name_of_option(optc), name_of_option(optc));
419                 exit(1);
420         }
421         return optarg;
422 }
423
424 static char *argvalstr(int optc)
425 {
426         char *result = strdup(current_argument(optc));
427         if (result == NULL) {
428                 ERROR("can't alloc memory");
429                 exit(1);
430         }
431         return result;
432 }
433
434 static int argvalenum(int optc, struct enumdesc *desc)
435 {
436         int i;
437         size_t len;
438         char *list;
439         const char *name = current_argument(optc);
440
441         i = 0;
442         while(desc[i].name && strcmp(desc[i].name, name))
443                 i++;
444         if (!desc[i].name) {
445                 len = 0;
446                 i = 0;
447                 while(desc[i].name)
448                         len += strlen(desc[i++].name);
449                 list = malloc(len + i + i);
450                 if (!i || !list)
451                         ERROR("option [--%s] bad value (found %s)",
452                                 name_of_option(optc), name);
453                 else {
454                         i = 0;
455                         strcpy(list, desc[i].name ? : "");
456                         while(desc[++i].name)
457                                 strcat(strcat(list, ", "), desc[i].name);
458                         ERROR("option [--%s] bad value, only accepts values %s (found %s)",
459                                 name_of_option(optc), list, name);
460                 }
461                 free(list);
462                 exit(1);
463         }
464         return desc[i].value;
465 }
466
467 static int argvalint(int optc, int mini, int maxi, int base)
468 {
469         const char *beg, *end;
470         long int val;
471         beg = current_argument(optc);
472         val = strtol(beg, (char**)&end, base);
473         if (*end || end == beg) {
474                 ERROR("option [--%s] requires a valid integer (found %s)",
475                         name_of_option(optc), beg);
476                 exit(1);
477         }
478         if (val < (long int)mini || val > (long int)maxi) {
479                 ERROR("option [--%s] value out of bounds (not %d<=%ld<=%d)",
480                         name_of_option(optc), mini, val, maxi);
481                 exit(1);
482         }
483         return (int)val;
484 }
485
486 static int argvalintdec(int optc, int mini, int maxi)
487 {
488         return argvalint(optc, mini, maxi, 10);
489 }
490
491 static void noarg(int optc)
492 {
493         if (optarg != 0) {
494                 ERROR("option [--%s] need no value (found %s)", name_of_option(optc), optarg);
495                 exit(1);
496         }
497 }
498
499 static char **make_exec(char **argv)
500 {
501         char **result, *iter;
502         size_t length;
503         int i;
504
505         length = 0;
506         for (i = 0 ; argv[i] ; i++)
507                 length += strlen(argv[i]) + 1;
508
509         result = malloc(length + ((unsigned)(i + 1)) * sizeof *result);
510         if (result == NULL) {
511                 ERROR("can't alloc memory");
512                 exit(1);
513         }
514
515         iter = (char*)&result[i+1];
516         for (i = 0 ; argv[i] ; i++) {
517                 result[i] = iter;
518                 iter = stpcpy(iter, argv[i]) + 1;
519         }
520         result[i] = NULL;
521         return result;
522 }
523
524 /*---------------------------------------------------------
525  |   set the log levels
526  +--------------------------------------------------------- */
527
528 static void set_log(char *args)
529 {
530         char o = 0, s, *p, *i = args;
531         int lvl;
532
533         for(;;) switch (*i) {
534         case 0:
535                 return;
536         case '+':
537         case '-':
538                 o = *i;
539                 /*@fallthrough@*/
540         case ' ':
541         case ',':
542                 i++;
543                 break;
544         default:
545                 p = i;
546                 while (isalpha(*p)) p++;
547                 s = *p;
548                 *p = 0;
549                 lvl = verbose_level_of_name(i);
550                 if (lvl < 0) {
551                         i = strdupa(i);
552                         *p = s;
553                         ERROR("Bad log name '%s' in %s", i, args);
554                         exit(1);
555                 }
556                 *p = s;
557                 i = p;
558                 if (o == '-')
559                         verbose_sub(lvl);
560                 else {
561                         if (!o) {
562                                 verbose_clear();
563                                 o = '+';
564                         }
565                         verbose_add(lvl);
566                 }
567                 break;
568         }
569 }
570
571 /*---------------------------------------------------------
572  |   Parse option and launch action
573  +--------------------------------------------------------- */
574
575 static void parse_arguments(int argc, char **argv, struct afb_config *config)
576 {
577         char *programName = argv[0];
578         int optc, ind;
579         int nbcmd;
580         struct option *gnuOptions;
581
582         // ------------------ Process Command Line -----------------------
583
584         // build GNU getopt info from cliOptions
585         nbcmd = sizeof(cliOptions) / sizeof(AFB_options);
586         gnuOptions = malloc(sizeof(*gnuOptions) * (unsigned)nbcmd);
587         for (ind = 0; ind < nbcmd; ind++) {
588                 gnuOptions[ind].name = cliOptions[ind].name;
589                 gnuOptions[ind].has_arg = cliOptions[ind].has_arg;
590                 gnuOptions[ind].flag = 0;
591                 gnuOptions[ind].val = cliOptions[ind].val;
592         }
593
594         // get all options from command line
595         while ((optc = getopt_long(argc, argv, shortopts, gnuOptions, NULL)) != EOF) {
596                 switch (optc) {
597                 case SET_VERBOSE:
598                         verbose_inc();
599                         break;
600
601                 case SET_QUIET:
602                         verbose_dec();
603                         break;
604
605                 case SET_LOG:
606                         set_log(argvalstr(optc));
607                         break;
608
609                 case SET_TCP_PORT:
610                         config->http_port = argvalintdec(optc, 1024, 32767);
611                         break;
612
613                 case SET_APITIMEOUT:
614                         config->api_timeout = argvalintdec(optc, 0, INT_MAX);
615                         break;
616
617                 case SET_CNTXTIMEOUT:
618                         config->session_timeout = argvalintdec(optc, 0, INT_MAX);
619                         break;
620
621                 case SET_ROOT_DIR:
622                         config->rootdir = argvalstr(optc);
623                         INFO("Forcing Rootdir=%s", config->rootdir);
624                         break;
625
626                 case SET_ROOT_HTTP:
627                         config->roothttp = argvalstr(optc);
628                         INFO("Forcing Root HTTP=%s", config->roothttp);
629                         break;
630
631                 case SET_ROOT_BASE:
632                         config->rootbase = argvalstr(optc);
633                         INFO("Forcing Rootbase=%s", config->rootbase);
634                         break;
635
636                 case SET_ROOT_API:
637                         config->rootapi = argvalstr(optc);
638                         INFO("Forcing Rootapi=%s", config->rootapi);
639                         break;
640
641                 case SET_ALIAS:
642                         list_add(&config->aliases, argvalstr(optc));
643                         break;
644
645                 case SET_AUTH_TOKEN:
646                         config->token = argvalstr(optc);
647                         break;
648
649                 case SET_LDPATH:
650                         list_add(&config->ldpaths, argvalstr(optc));
651                         break;
652
653                 case SET_WEAK_LDPATH:
654                         list_add(&config->weak_ldpaths, argvalstr(optc));
655                         break;
656
657                 case NO_LDPATH:
658                         noarg(optc);
659                         config->no_ldpaths = 1;
660                         break;
661
662                 case ADD_CALL:
663                         list_add(&config->calls, argvalstr(optc));
664                         break;
665
666                 case SET_UPLOAD_DIR:
667                         config->uploaddir = argvalstr(optc);
668                         break;
669
670                 case SET_WORK_DIR:
671                         config->workdir = argvalstr(optc);
672                         break;
673
674                 case SET_CACHE_TIMEOUT:
675                         config->cache_timeout = argvalintdec(optc, 0, INT_MAX);
676                         break;
677
678                 case SET_SESSIONMAX:
679                         config->max_session_count = argvalintdec(optc, 1, INT_MAX);
680                         break;
681
682                 case SET_FORGROUND:
683                         noarg(optc);
684                         config->background = 0;
685                         break;
686
687                 case SET_BACKGROUND:
688                         noarg(optc);
689                         config->background = 1;
690                         break;
691
692                 case SET_NAME:
693                         config->name = argvalstr(optc);
694                         break;
695
696 #if defined(WITH_DBUS_TRANSPARENCY)
697                 case DBUS_CLIENT:
698                         list_add(&config->dbus_clients, argvalstr(optc));
699                         break;
700
701                 case DBUS_SERVICE:
702                         list_add(&config->dbus_servers, argvalstr(optc));
703                         break;
704 #endif
705
706                 case WS_CLIENT:
707                         list_add(&config->ws_clients, argvalstr(optc));
708                         break;
709
710                 case WS_SERVICE:
711                         list_add(&config->ws_servers, argvalstr(optc));
712                         break;
713
714                 case SO_BINDING:
715                         list_add(&config->so_bindings, argvalstr(optc));
716                         break;
717
718                 case AUTO_API:
719                         list_add(&config->auto_api, argvalstr(optc));
720                         break;
721
722                 case SET_TRACEREQ:
723                         config->tracereq = argvalenum(optc, tracereq_desc);
724                         break;
725
726 #if !defined(REMOVE_LEGACY_TRACE)
727                 case SET_TRACEDITF:
728                         config->traceditf = argvalenum(optc, traceditf_desc);
729                         break;
730
731                 case SET_TRACESVC:
732                         config->tracesvc = argvalenum(optc, tracesvc_desc);
733                         break;
734 #endif
735
736                 case SET_TRACEEVT:
737                         config->traceevt = argvalenum(optc, traceevt_desc);
738                         break;
739
740                 case SET_TRACESES:
741                         config->traceses = argvalenum(optc, traceses_desc);
742                         break;
743
744                 case SET_TRACEAPI:
745                         config->traceapi = argvalenum(optc, traceapi_desc);
746                         break;
747
748                 case SET_NO_HTTPD:
749                         noarg(optc);
750                         config->no_httpd = 1;
751                         break;
752
753                 case SET_EXEC:
754                         config->exec = make_exec(&argv[optind]);
755                         optind = argc; /* stop option scanning */
756                         break;
757
758                 case SET_RNDTOKEN:
759                         config->random_token = 1;
760                         break;
761
762 #if defined(WITH_MONITORING_OPTION)
763                 case SET_MONITORING:
764                         config->monitoring = 1;
765                         break;
766 #endif
767
768                 case DISPLAY_VERSION:
769                         noarg(optc);
770                         printVersion(stdout);
771                         exit(0);
772
773                 case DISPLAY_HELP:
774                         printHelp(stdout, programName);
775                         exit(0);
776
777                 default:
778                         exit(1);
779                 }
780         }
781         free(gnuOptions);
782 }
783
784 static void fulfill_config(struct afb_config *config)
785 {
786         // default HTTP port
787         if (config->http_port == 0)
788                 config->http_port = DEFAULT_HTTP_PORT;
789
790         // default binding API timeout
791         if (config->api_timeout == 0)
792                 config->api_timeout = DEFAULT_API_TIMEOUT;
793
794         // default AUTH_TOKEN
795         if (config->random_token)
796                 config->token = NULL;
797
798         // cache timeout default one hour
799         if (config->cache_timeout == 0)
800                 config->cache_timeout = DEFAULT_CACHE_TIMEOUT;
801
802         // cache timeout default one hour
803         if (config->session_timeout == 0)
804                 config->session_timeout = DEFAULT_SESSION_TIMEOUT;
805
806         // max count of sessions
807         if (config->max_session_count == 0)
808                 config->max_session_count = DEFAULT_MAX_SESSION_COUNT;
809
810         /* set directories */
811         if (config->workdir == NULL)
812                 config->workdir = ".";
813
814         if (config->rootdir == NULL)
815                 config->rootdir = ".";
816
817         if (config->uploaddir == NULL)
818                 config->uploaddir = ".";
819
820         // if no Angular/HTML5 rootbase let's try '/' as default
821         if (config->rootbase == NULL)
822                 config->rootbase = "/opa";
823
824         if (config->rootapi == NULL)
825                 config->rootapi = "/api";
826
827         if (config->ldpaths == NULL && config->weak_ldpaths == NULL && !config->no_ldpaths)
828                 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
829
830 #if defined(WITH_MONITORING_OPTION)
831         if (config->monitoring)
832                 list_add(&config->aliases, strdup("/monitoring:"BINDING_INSTALL_DIR"/monitoring"));
833 #endif
834
835         // if no config dir create a default path from uploaddir
836         if (config->console == NULL) {
837                 config->console = malloc(512);
838                 strncpy(config->console, config->uploaddir, 512);
839                 strncat(config->console, "/AFB-console.out", 512);
840         }
841
842 #if !defined(REMOVE_LEGACY_TRACE)
843         config->traceapi |= config->traceditf | config->tracesvc;
844 #endif
845 }
846
847 void afb_config_dump(struct afb_config *config)
848 {
849         struct afb_config_list *l;
850         struct enumdesc *e;
851         char **v;
852
853 #define NN(x)   (x)?:""
854 #define P(...)  fprintf(stderr, __VA_ARGS__)
855 #define PF(x)   P("-- %15s: ", #x)
856 #define PE      P("\n")
857 #define S(x)    PF(x);P("%s",NN(config->x));PE;
858 #define D(x)    PF(x);P("%d",config->x);PE;
859 #define B(x)    PF(x);P("%s",config->x?"yes":"no");PE;
860 #define L(x)    PF(x);l=config->x;if(l){P("%s\n",NN(l->value));for(l=l->next;l;l=l->next)P("-- %15s  %s\n","",NN(l->value));}else PE;
861 #define E(x,d)  for(e=d;e->name&&e->value!=config->x;e++);if(e->name){PF(x);P("%s",e->name);PE;}else{D(x);}
862 #define V(x)    P("-- %15s:", #x);for(v=config->x;v&&*v;v++)P(" %s",*v); PE;
863
864         P("---BEGIN-OF-CONFIG---\n");
865         S(console)
866         S(rootdir)
867         S(roothttp)
868         S(rootbase)
869         S(rootapi)
870         S(workdir)
871         S(uploaddir)
872         S(token)
873         S(name)
874
875         L(aliases)
876 #if defined(WITH_DBUS_TRANSPARENCY)
877         L(dbus_clients)
878         L(dbus_servers)
879 #endif
880         L(ws_clients)
881         L(ws_servers)
882         L(so_bindings)
883         L(auto_api)
884         L(ldpaths)
885         L(weak_ldpaths)
886         L(calls)
887
888         V(exec)
889
890         D(http_port)
891         D(cache_timeout)
892         D(api_timeout)
893         D(session_timeout)
894         D(max_session_count)
895
896         E(tracereq,tracereq_desc)
897 #if !defined(REMOVE_LEGACY_TRACE)
898         E(traceditf,traceditf_desc)
899         E(tracesvc,tracesvc_desc)
900 #endif
901         E(traceevt,traceevt_desc)
902         E(traceses,traceses_desc)
903         E(traceapi,traceapi_desc)
904
905         B(no_ldpaths)
906         B(no_httpd)
907         B(background)
908 #if defined(WITH_MONITORING_OPTION)
909         B(monitoring)
910 #endif
911         B(random_token)
912         P("---END-OF-CONFIG---\n");
913
914 #undef V
915 #undef E
916 #undef L
917 #undef B
918 #undef D
919 #undef S
920 #undef PE
921 #undef PF
922 #undef P
923 #undef NN
924 }
925
926 static void on_environment_list(struct afb_config_list **to, const char *name)
927 {
928         char *value = getenv(name);
929
930         if (value)
931                 list_add(to, value);
932 }
933
934 static void on_environment_enum(int *to, const char *name, struct enumdesc *desc)
935 {
936         char *value = getenv(name);
937
938         if (value) {
939                 while (desc->name) {
940                         if (strcmp(desc->name, value))
941                                 desc++;
942                         else {
943                                 *to = desc->value;
944                                 return;
945                         }
946                 }
947                 WARNING("Unknown value %s for environment variable %s, ignored", value, name);
948         }
949 }
950
951 static void parse_environment(struct afb_config *config)
952 {
953         on_environment_enum(&config->tracereq, "AFB_TRACEREQ", tracereq_desc);
954 #if !defined(REMOVE_LEGACY_TRACE)
955         on_environment_enum(&config->traceditf, "AFB_TRACEDITF", traceditf_desc);
956         on_environment_enum(&config->tracesvc, "AFB_TRACESVC", tracesvc_desc);
957 #endif
958         on_environment_enum(&config->traceevt, "AFB_TRACEEVT", traceevt_desc);
959         on_environment_enum(&config->traceses, "AFB_TRACESES", traceses_desc);
960         on_environment_enum(&config->traceapi, "AFB_TRACEAPI", traceapi_desc);
961         on_environment_list(&config->ldpaths, "AFB_LDPATHS");
962 }
963
964 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
965 {
966         struct afb_config *result;
967
968         result = calloc(1, sizeof *result);
969
970         parse_environment(result);
971         parse_arguments(argc, argv, result);
972         fulfill_config(result);
973         if (verbose_wants(Log_Level_Info))
974                 afb_config_dump(result);
975         return result;
976 }
977
978 struct json_object *afb_config_json(struct afb_config *config)
979 {
980         struct json_object *r, *a;
981         struct afb_config_list *l;
982         struct enumdesc *e;
983         char **v;
984
985 #define XA(t,o)         json_object_array_add(t,o);
986 #define XO(t,x,o)       json_object_object_add(t,x,o);
987 #define YS(s)           ((s)?json_object_new_string(s):NULL)
988
989 #define AO(o)           XA(a,o)
990 #define AS(s)           AO(YS(s))
991 #define RO(x,o)         XO(r,x,o)
992 #define RS(x,s)         RO(x,YS(s))
993 #define RA(x)           RO(x,(a=json_object_new_array()))
994 #define RI(x,i)         RO(x,json_object_new_int(i))
995 #define RB(x,b)         RO(x,json_object_new_boolean(b))
996
997 #define S(x)            RS(#x,config->x)
998 #define V(x)            RA(#x);for(v=config->x;v&&*v;v++)AS(*v);
999 #define L(x)            RA(#x);for(l=config->x;l;l=l->next)AS(l->value);
1000 #define D(x)            RI(#x,config->x)
1001 #define B(x)            RB(#x,config->x)
1002 #define E(x,d)          for(e=d;e->name&&e->value!=config->x;e++);if(e->name){RS(#x,e->name);}else{D(x);}
1003
1004         r = json_object_new_object();
1005         S(console)
1006         S(rootdir)
1007         S(roothttp)
1008         S(rootbase)
1009         S(rootapi)
1010         S(workdir)
1011         S(uploaddir)
1012         S(token)
1013         S(name)
1014
1015         L(aliases)
1016 #if defined(WITH_DBUS_TRANSPARENCY)
1017         L(dbus_clients)
1018         L(dbus_servers)
1019 #endif
1020         L(ws_clients)
1021         L(ws_servers)
1022         L(so_bindings)
1023         L(auto_api)
1024         L(ldpaths)
1025         L(weak_ldpaths)
1026         L(calls)
1027
1028         V(exec)
1029
1030         D(http_port)
1031         D(cache_timeout)
1032         D(api_timeout)
1033         D(session_timeout)
1034         D(max_session_count)
1035
1036         E(tracereq,tracereq_desc)
1037 #if !defined(REMOVE_LEGACY_TRACE)
1038         E(traceditf,traceditf_desc)
1039         E(tracesvc,tracesvc_desc)
1040 #endif
1041         E(traceevt,traceevt_desc)
1042         E(traceses,traceses_desc)
1043         E(traceapi,traceapi_desc)
1044
1045         B(no_ldpaths)
1046         B(no_httpd)
1047         B(background)
1048 #if defined(WITH_MONITORING_OPTION)
1049         B(monitoring)
1050 #endif
1051         B(random_token)
1052
1053 #undef E
1054 #undef B
1055 #undef D
1056 #undef L
1057 #undef V
1058 #undef S
1059
1060 #undef RB
1061 #undef RI
1062 #undef RA
1063 #undef RS
1064 #undef RS
1065 #undef AS
1066 #undef AO
1067
1068 #undef YS
1069 #undef XO
1070 #undef XA
1071
1072         return r;
1073 }
1074