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