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