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