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