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