adds short option for verbosity
[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 #define NO_BINDING_VERBOSE_MACRO
20
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <getopt.h>
25 #include <limits.h>
26
27 #include "verbose.h"
28 #include "afb-config.h"
29 #include "afb-hook.h"
30
31 #include <afb/afb-binding.h>
32
33 #if !defined(BINDING_INSTALL_DIR)
34 #error "you should define BINDING_INSTALL_DIR"
35 #endif
36
37 #define AFB_VERSION    "0.5"
38
39 // default
40 #define DEFLT_CNTX_TIMEOUT  3600        // default Client Connection
41                                         // Timeout
42 #define DEFLT_API_TIMEOUT   20          // default Plugin API Timeout [0=NoLimit
43                                         // for Debug Only]
44 #define DEFLT_CACHE_TIMEOUT 100000      // default Static File Chache
45                                         // [Client Side Cache
46                                         // 100000~=1day]
47 #define DEFLT_AUTH_TOKEN    NULL        // expect for debug should == NULL
48 #define CTX_NBCLIENTS       10          // allow a default of 10 authenticated
49                                         // clients
50
51
52 // Define command line option
53 #define SET_VERBOSE        'v'
54 #define SET_BACKGROUND     2
55 #define SET_FORGROUND      3
56 #define SET_QUIET          'q'
57
58 #define SET_TCP_PORT       5
59 #define SET_ROOT_DIR       6
60 #define SET_ROOT_BASE      7
61 #define SET_ROOT_API       8
62 #define SET_ALIAS          9
63
64 #define SET_CACHE_TIMEOUT  10
65 #define SET_SESSION_DIR    11
66
67 #define SET_AUTH_TOKEN     12
68 #define SET_LDPATH         13
69 #define SET_APITIMEOUT     14
70 #define SET_CNTXTIMEOUT    15
71
72 #define DISPLAY_VERSION    'V'
73 #define DISPLAY_HELP       'h'
74
75 #define SET_MODE           18
76 #define SET_READYFD        19
77
78 #define DBUS_CLIENT        20
79 #define DBUS_SERVICE       21
80 #define SO_BINDING         22
81
82 #define SET_SESSIONMAX     23
83
84 #define WS_CLIENT          24
85 #define WS_SERVICE         25
86
87 #define SET_ROOT_HTTP      26
88
89 #define SET_TRACEREQ       27
90
91 #define SHORTOPTS       "vqhV"
92
93 // Command line structure hold cli --command + help text
94 typedef struct {
95         int val;                // command number within application
96         int has_arg;            // command number within application
97         char *name;             // command as used in --xxxx cli
98         char *help;             // help text
99 } AFB_options;
100
101 // Supported option
102 static AFB_options cliOptions[] = {
103 /* *INDENT-OFF* */
104         {SET_VERBOSE,       0, "verbose",     "Verbose Mode, repeat to increase verbosity"},
105         {SET_QUIET,         0, "quiet",       "Quiet Mode, repeat to decrease verbosity"},
106
107         {SET_FORGROUND,     0, "foreground",  "Get all in foreground mode"},
108         {SET_BACKGROUND,    0, "daemon",      "Get all in background mode"},
109
110         {SET_TCP_PORT,      1, "port",        "HTTP listening TCP port  [default 1234]"},
111         {SET_ROOT_DIR,      1, "rootdir",     "Root Directory [default $HOME/.AFB]"},
112         {SET_ROOT_HTTP,     1, "roothttp",    "HTTP Root Directory [default rootdir]"},
113         {SET_ROOT_BASE,     1, "rootbase",    "Angular Base Root URL [default /opa]"},
114         {SET_ROOT_API,      1, "rootapi",     "HTML Root API URL [default /api]"},
115         {SET_ALIAS,         1, "alias",       "Muliple url map outside of rootdir [eg: --alias=/icons:/usr/share/icons]"},
116
117         {SET_APITIMEOUT,    1, "apitimeout",  "Binding API timeout in seconds [default 10]"},
118         {SET_CNTXTIMEOUT,   1, "cntxtimeout", "Client Session Context Timeout [default 900]"},
119         {SET_CACHE_TIMEOUT, 1, "cache-eol",   "Client cache end of live [default 3600]"},
120
121         {SET_SESSION_DIR,   1, "sessiondir",  "Sessions file path [default rootdir/sessions]"},
122
123         {SET_LDPATH,        1, "ldpaths",     "Load bindingss from dir1:dir2:... [default = " BINDING_INSTALL_DIR "]"},
124         {SET_AUTH_TOKEN,    1, "token",       "Initial Secret [default=no-session, --token= for session without authentication]"},
125
126         {DISPLAY_VERSION,   0, "version",     "Display version and copyright"},
127         {DISPLAY_HELP,      0, "help",        "Display this help"},
128
129         {SET_MODE,          1, "mode",        "Set the mode: either local, remote or global"},
130         {SET_READYFD,       1, "readyfd",     "Set the #fd to signal when ready"},
131
132         {DBUS_CLIENT,       1, "dbus-client", "Bind to an afb service through dbus"},
133         {DBUS_SERVICE,      1, "dbus-server", "Provides an afb service through dbus"},
134         {WS_CLIENT,         1, "ws-client",   "Bind to an afb service through websocket"},
135         {WS_SERVICE,        1, "ws-server",   "Provides an afb service through websockets"},
136         {SO_BINDING,        1, "binding",     "Load the binding of path"},
137
138         {SET_SESSIONMAX,    1, "session-max", "Max count of session simultaneously [default 10]"},
139
140         {SET_TRACEREQ,      1, "tracereq",    "Log the requests: no, common, extra, all"},
141
142         {0, 0, NULL, NULL}
143 /* *INDENT-ON* */
144 };
145
146
147 struct enumdesc
148 {
149         const char *name;
150         int value;
151 };
152
153 static struct enumdesc tracereq_desc[] = {
154         { "no",     0 },
155         { "common", afb_hook_flags_req_common },
156         { "extra",  afb_hook_flags_req_extra },
157         { "all",    afb_hook_flags_req_all },
158         { NULL, 0 }
159 };
160
161 static struct enumdesc mode_desc[] = {
162         { "local",  AFB_MODE_LOCAL },
163         { "remote", AFB_MODE_REMOTE },
164         { "global", AFB_MODE_GLOBAL },
165         { NULL, 0 }
166 };
167
168 /*----------------------------------------------------------
169  | printversion
170  |   print version and copyright
171  +--------------------------------------------------------- */
172 static void printVersion(FILE * file)
173 {
174         fprintf(file, "\n----------------------------------------- \n");
175         fprintf(file, "  AFB [Application Framework Binder] version=%s |\n",
176                 AFB_VERSION);
177         fprintf(file, " \n");
178         fprintf(file,
179                 "  Copyright (C) 2015, 2016, 2017 \"IoT.bzh\" [fulup -at- iot.bzh]\n");
180         fprintf(file, "  AFB comes with ABSOLUTELY NO WARRANTY.\n");
181         fprintf(file, "  Licence Apache 2\n\n");
182 }
183
184 /*----------------------------------------------------------
185  | printHelp
186  |   print information from long option array
187  +--------------------------------------------------------- */
188
189 static void printHelp(FILE * file, const char *name)
190 {
191         int ind;
192         char command[50];
193
194         fprintf(file, "%s:\nallowed options\n", name);
195         for (ind = 0; cliOptions[ind].name != NULL; ind++) {
196                 strcpy(command, cliOptions[ind].name);
197                 if (cliOptions[ind].has_arg)
198                         strcat(command, "=xxxx");
199                 fprintf(file, "  --%-15s %s\n", command, cliOptions[ind].help);
200         }
201         fprintf(file,
202                 "Example:\n  %s  --verbose --port=1234 --token='azerty' --ldpaths=build/bindings:/usr/lib64/agl/bindings\n",
203                 name);
204 }
205
206 /*----------------------------------------------------------
207  |   adds a string to the list
208  +--------------------------------------------------------- */
209 static void list_add(struct afb_config_list **head, char *value)
210 {
211         struct afb_config_list *item;
212
213         /*
214          * search tail 
215          */
216         item = *head;
217         while (item != NULL) {
218                 head = &item->next;
219                 item = item->next;
220         }
221
222         /*
223          * alloc the item 
224          */
225         item = malloc(sizeof *item);
226         if (item == NULL) {
227                 ERROR("out of memory");
228                 exit(1);
229         }
230
231         /*
232          * init the item 
233          */
234         *head = item;
235         item->value = value;
236         item->next = NULL;
237 }
238
239 /*---------------------------------------------------------
240  |   helpers for argument scanning
241  +--------------------------------------------------------- */
242
243 static char *argvalstr(int index)
244 {
245         if (optarg == 0) {
246                 ERROR("option [--%s] needs a value i.e. --%s=xxx",
247                       cliOptions[index].name, cliOptions[index].name);
248                 exit(1);
249         }
250         return optarg;
251 }
252
253 static int argvalenum(int index, struct enumdesc *desc)
254 {
255         int i;
256         size_t len;
257         char *list, *name = argvalstr(index);
258
259         i = 0;
260         while(desc[i].name && strcmp(desc[i].name, name))
261                 i++;
262         if (!desc[i].name) {
263                 len = 0;
264                 i = 0;
265                 while(desc[i].name)
266                         len += strlen(desc[i++].name);
267                 list = malloc(len + i + i);
268                 if (!i || !list)
269                         ERROR("option [--%s] bad value (found %s)",
270                                 cliOptions[index].name, name);
271                 else {
272                         i = 0;
273                         strcpy(list, desc[i].name ? : "");
274                         while(desc[++i].name)
275                                 strcat(strcat(list, ", "), desc[i].name);
276                         ERROR("option [--%s] bad value, only accepts values %s (found %s)",
277                                 cliOptions[index].name, list, name);
278                 }
279                 free(list);
280                 exit(1);
281         }
282         return desc[i].value;
283 }
284
285 static int argvalint(int index, int mini, int maxi, int base)
286 {
287         char *beg, *end;
288         long int val;
289         beg = argvalstr(index);
290         val = strtol(beg, &end, base);
291         if (*end || end == beg) {
292                 ERROR("option [--%s] requires a valid integer (found %s)",
293                         cliOptions[index].name, beg);
294                 exit(1);
295         }
296         if (val < (long int)mini || val > (long int)maxi) {
297                 ERROR("option [--%s] value out of bounds (not %d<=%ld<=%d)",
298                         cliOptions[index].name, mini, val, maxi);
299                 exit(1);
300         }
301         return (int)val;
302 }
303
304 static int argvalintdec(int index, int mini, int maxi)
305 {
306         return argvalint(index, mini, maxi, 10);
307 }
308
309 static void noarg(int index)
310 {
311         if (optarg != 0) {
312                 ERROR("option [--%s] need no value (found %s)", cliOptions[index].name, optarg);
313                 exit(1);
314         }
315 }
316
317 /*---------------------------------------------------------
318  |   Parse option and launch action
319  +--------------------------------------------------------- */
320
321 static void parse_arguments(int argc, char **argv, struct afb_config *config)
322 {
323         char *programName = argv[0];
324         int optionIndex = 0;
325         int optc, ind;
326         int nbcmd;
327         struct option *gnuOptions;
328
329         // ------------------ Process Command Line -----------------------
330
331         // build GNU getopt info from cliOptions
332         nbcmd = sizeof(cliOptions) / sizeof(AFB_options);
333         gnuOptions = malloc(sizeof(*gnuOptions) * (unsigned)nbcmd);
334         for (ind = 0; ind < nbcmd; ind++) {
335                 gnuOptions[ind].name = cliOptions[ind].name;
336                 gnuOptions[ind].has_arg = cliOptions[ind].has_arg;
337                 gnuOptions[ind].flag = 0;
338                 gnuOptions[ind].val = cliOptions[ind].val;
339         }
340
341         // get all options from command line
342         while ((optc = getopt_long(argc, argv, SHORTOPTS, gnuOptions, &optionIndex)) != EOF) {
343                 switch (optc) {
344                 case SET_VERBOSE:
345                         verbosity++;
346                         break;
347
348                 case SET_QUIET:
349                         verbosity--;
350                         break;
351
352                 case SET_TCP_PORT:
353                         config->httpdPort = argvalintdec(optionIndex, 1024, 32767);
354                         break;
355
356                 case SET_APITIMEOUT:
357                         config->apiTimeout = argvalintdec(optionIndex, 0, INT_MAX);
358                         break;
359
360                 case SET_CNTXTIMEOUT:
361                         config->cntxTimeout = argvalintdec(optionIndex, 0, INT_MAX);
362                         break;
363
364                 case SET_ROOT_DIR:
365                         config->rootdir = argvalstr(optionIndex);
366                         INFO("Forcing Rootdir=%s", config->rootdir);
367                         break;
368
369                 case SET_ROOT_HTTP:
370                         config->roothttp = argvalstr(optionIndex);
371                         INFO("Forcing Root HTTP=%s", config->roothttp);
372                         break;
373
374                 case SET_ROOT_BASE:
375                         config->rootbase = argvalstr(optionIndex);
376                         INFO("Forcing Rootbase=%s", config->rootbase);
377                         break;
378
379                 case SET_ROOT_API:
380                         config->rootapi = argvalstr(optionIndex);
381                         INFO("Forcing Rootapi=%s", config->rootapi);
382                         break;
383
384                 case SET_ALIAS:
385                         list_add(&config->aliases, argvalstr(optionIndex));
386                         break;
387
388                 case SET_AUTH_TOKEN:
389                         config->token = argvalstr(optionIndex);
390                         break;
391
392                 case SET_LDPATH:
393                         list_add(&config->ldpaths, argvalstr(optionIndex));
394                         break;
395
396                 case SET_SESSION_DIR:
397                         config->sessiondir = argvalstr(optionIndex);
398                         break;
399
400                 case SET_CACHE_TIMEOUT:
401                         config->cacheTimeout = argvalintdec(optionIndex, 0, INT_MAX);
402                         break;
403
404                 case SET_SESSIONMAX:
405                         config->nbSessionMax = argvalintdec(optionIndex, 1, INT_MAX);
406                         break;
407
408                 case SET_FORGROUND:
409                         noarg(optionIndex);
410                         config->background = 0;
411                         break;
412
413                 case SET_BACKGROUND:
414                         noarg(optionIndex);
415                         config->background = 1;
416                         break;
417
418                 case SET_MODE:
419                         config->mode = argvalenum(optionIndex, mode_desc);
420                         break;
421
422                 case SET_READYFD:
423                         config->readyfd = argvalintdec(optionIndex, 0, INT_MAX);
424                         break;
425
426                 case DBUS_CLIENT:
427                         list_add(&config->dbus_clients, argvalstr(optionIndex));
428                         break;
429
430                 case DBUS_SERVICE:
431                         list_add(&config->dbus_servers, argvalstr(optionIndex));
432                         break;
433
434                 case WS_CLIENT:
435                         list_add(&config->ws_clients, argvalstr(optionIndex));
436                         break;
437
438                 case WS_SERVICE:
439                         list_add(&config->ws_servers, argvalstr(optionIndex));
440                         break;
441
442                 case SO_BINDING:
443                         list_add(&config->so_bindings, argvalstr(optionIndex));
444                         break;
445
446                 case SET_TRACEREQ:
447                         config->tracereq = argvalenum(optionIndex, tracereq_desc);
448                         break;
449
450                 case DISPLAY_VERSION:
451                         noarg(optionIndex);
452                         printVersion(stdout);
453                         exit(0);
454
455                 case DISPLAY_HELP:
456                         printHelp(stdout, programName);
457                         exit(0);
458
459                 default:
460                         exit(1);
461                 }
462         }
463         free(gnuOptions);
464 }
465
466 // load config from disk and merge with CLI option
467 static void config_set_default(struct afb_config *config)
468 {
469         // default HTTP port
470         if (config->httpdPort == 0)
471                 config->httpdPort = 1234;
472
473         // default binding API timeout
474         if (config->apiTimeout == 0)
475                 config->apiTimeout = DEFLT_API_TIMEOUT;
476
477         // default AUTH_TOKEN
478         if (config->token == NULL)
479                 config->token = DEFLT_AUTH_TOKEN;
480
481         // cache timeout default one hour
482         if (config->cacheTimeout == 0)
483                 config->cacheTimeout = DEFLT_CACHE_TIMEOUT;
484
485         // cache timeout default one hour
486         if (config->cntxTimeout == 0)
487                 config->cntxTimeout = DEFLT_CNTX_TIMEOUT;
488
489         // max count of sessions
490         if (config->nbSessionMax == 0)
491                 config->nbSessionMax = CTX_NBCLIENTS;
492
493         if (config->rootdir == NULL) {
494                 config->rootdir = getenv("AFBDIR");
495                 if (config->rootdir == NULL) {
496                         config->rootdir = malloc(512);
497                         strncpy(config->rootdir, getenv("HOME"), 512);
498                         strncat(config->rootdir, "/.AFB", 512);
499                 }
500         }
501         // if no Angular/HTML5 rootbase let's try '/' as default
502         if (config->rootbase == NULL)
503                 config->rootbase = "/opa";
504
505         if (config->rootapi == NULL)
506                 config->rootapi = "/api";
507
508         if (config->ldpaths == NULL)
509                 list_add(&config->ldpaths, BINDING_INSTALL_DIR);
510
511         // if no session dir create a default path from rootdir
512         if (config->sessiondir == NULL) {
513                 config->sessiondir = malloc(512);
514                 strncpy(config->sessiondir, config->rootdir, 512);
515                 strncat(config->sessiondir, "/sessions", 512);
516         }
517         // if no config dir create a default path from sessiondir
518         if (config->console == NULL) {
519                 config->console = malloc(512);
520                 strncpy(config->console, config->sessiondir, 512);
521                 strncat(config->console, "/AFB-console.out", 512);
522         }
523 }
524
525 void afb_config_dump(struct afb_config *config)
526 {
527         struct afb_config_list *l;
528         struct enumdesc *e;
529
530 #define NN(x)   (x)?:""
531 #define P(...)  fprintf(stderr, __VA_ARGS__)
532 #define PF(x)   P("-- %15s: ", #x)
533 #define PE      P("\n")
534 #define S(x)    PF(x);P("%s",NN(config->x));PE;
535 #define D(x)    PF(x);P("%d",config->x);PE;
536 #define H(x)    PF(x);P("%x",config->x);PE;
537 #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;
538 #define E(x,d)  for(e=d;e->name&&e->value!=config->x;e++);PF(x);if(e->name)P("%s",e->name);else P("%d",config->x);PE;
539
540         P("-- BEGIN OF CONFIG --\n");
541         S(console)
542         S(rootdir)
543         S(roothttp)
544         S(rootbase)
545         S(rootapi)
546         S(sessiondir)
547         S(token)
548
549         L(aliases)
550         L(dbus_clients)
551         L(dbus_servers)
552         L(ws_clients)
553         L(ws_servers)
554         L(so_bindings)
555         L(ldpaths)
556
557         D(httpdPort)
558         D(background)
559         D(readyfd)
560         D(cacheTimeout)
561         D(apiTimeout)
562         D(cntxTimeout)
563         D(nbSessionMax)
564         E(mode,mode_desc)
565         E(tracereq,tracereq_desc)
566         P("-- END OF CONFIG --\n");
567
568 #undef E
569 #undef L
570 #undef H
571 #undef D
572 #undef S
573 #undef PE
574 #undef PF
575 #undef P
576 #undef NN
577 }
578
579 struct afb_config *afb_config_parse_arguments(int argc, char **argv)
580 {
581         struct afb_config *result;
582
583         result = calloc(1, sizeof *result);
584
585         parse_arguments(argc, argv, result);
586         config_set_default(result);
587         if (verbosity >= 3)
588                 afb_config_dump(result);
589         return result;
590 }
591