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