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