forked from haproxy/haproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.c
More file actions
2788 lines (2389 loc) · 78 KB
/
Copy pathcli.c
File metadata and controls
2788 lines (2389 loc) · 78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Functions dedicated to statistics output and the stats socket
*
* Copyright 2000-2012 Willy Tarreau <w@1wt.eu>
* Copyright 2007-2009 Krzysztof Piotr Oledzki <ole@ans.pl>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <net/if.h>
#include <haproxy/activity.h>
#include <haproxy/api.h>
#include <haproxy/applet-t.h>
#include <haproxy/base64.h>
#include <haproxy/cfgparse.h>
#include <haproxy/channel.h>
#include <haproxy/check.h>
#include <haproxy/cli.h>
#include <haproxy/compression.h>
#include <haproxy/dns-t.h>
#include <haproxy/errors.h>
#include <haproxy/fd.h>
#include <haproxy/freq_ctr.h>
#include <haproxy/frontend.h>
#include <haproxy/global.h>
#include <haproxy/list.h>
#include <haproxy/listener.h>
#include <haproxy/log.h>
#include <haproxy/mworker-t.h>
#include <haproxy/pattern-t.h>
#include <haproxy/peers.h>
#include <haproxy/pipe.h>
#include <haproxy/protocol.h>
#include <haproxy/proxy.h>
#include <haproxy/sample-t.h>
#include <haproxy/server.h>
#include <haproxy/session.h>
#include <haproxy/stats-t.h>
#include <haproxy/stream.h>
#include <haproxy/stream_interface.h>
#include <haproxy/task.h>
#include <haproxy/ticks.h>
#include <haproxy/time.h>
#include <haproxy/tools.h>
#include <haproxy/version.h>
#define PAYLOAD_PATTERN "<<"
static struct applet cli_applet;
static const char stats_sock_usage_msg[] =
"Unknown command. Please enter one of the following commands only :\n"
" help : this message\n"
" prompt : toggle interactive mode with prompt\n"
" quit : disconnect\n"
"";
static const char stats_permission_denied_msg[] =
"Permission denied\n"
"";
static THREAD_LOCAL char *dynamic_usage_msg = NULL;
/* List head of cli keywords */
static struct cli_kw_list cli_keywords = {
.list = LIST_HEAD_INIT(cli_keywords.list)
};
extern const char *stat_status_codes[];
static struct proxy *mworker_proxy; /* CLI proxy of the master */
static char *cli_gen_usage_msg(struct appctx *appctx)
{
struct cli_kw_list *kw_list;
struct cli_kw *kw;
struct buffer *tmp = get_trash_chunk();
struct buffer out;
free(dynamic_usage_msg);
dynamic_usage_msg = NULL;
if (LIST_ISEMPTY(&cli_keywords.list))
goto end;
chunk_reset(tmp);
chunk_strcat(tmp, stats_sock_usage_msg);
list_for_each_entry(kw_list, &cli_keywords.list, list) {
kw = &kw_list->kw[0];
while (kw->str_kw[0]) {
/* in a worker or normal process, don't display master only commands */
if (master == 0 && (kw->level & ACCESS_MASTER_ONLY))
goto next_kw;
/* in master don't displays if we don't have the master bits */
if (master == 1 && !(kw->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)))
goto next_kw;
/* only show expert commands in expert mode */
if ((kw->level & ~appctx->cli_level) & ACCESS_EXPERT)
goto next_kw;
if (kw->usage)
chunk_appendf(tmp, " %s\n", kw->usage);
next_kw:
kw++;
}
}
chunk_init(&out, NULL, 0);
chunk_dup(&out, tmp);
dynamic_usage_msg = out.area;
end:
if (dynamic_usage_msg) {
appctx->ctx.cli.severity = LOG_INFO;
appctx->ctx.cli.msg = dynamic_usage_msg;
}
else {
appctx->ctx.cli.severity = LOG_INFO;
appctx->ctx.cli.msg = stats_sock_usage_msg;
}
appctx->st0 = CLI_ST_PRINT;
return dynamic_usage_msg;
}
struct cli_kw* cli_find_kw(char **args)
{
struct cli_kw_list *kw_list;
struct cli_kw *kw;/* current cli_kw */
char **tmp_args;
const char **tmp_str_kw;
int found = 0;
if (LIST_ISEMPTY(&cli_keywords.list))
return NULL;
list_for_each_entry(kw_list, &cli_keywords.list, list) {
kw = &kw_list->kw[0];
while (*kw->str_kw) {
tmp_args = args;
tmp_str_kw = kw->str_kw;
while (*tmp_str_kw) {
if (strcmp(*tmp_str_kw, *tmp_args) == 0) {
found = 1;
} else {
found = 0;
break;
}
tmp_args++;
tmp_str_kw++;
}
if (found)
return (kw);
kw++;
}
}
return NULL;
}
void cli_register_kw(struct cli_kw_list *kw_list)
{
LIST_ADDQ(&cli_keywords.list, &kw_list->list);
}
/* allocate a new stats frontend named <name>, and return it
* (or NULL in case of lack of memory).
*/
static struct proxy *alloc_stats_fe(const char *name, const char *file, int line)
{
struct proxy *fe;
fe = calloc(1, sizeof(*fe));
if (!fe)
return NULL;
init_new_proxy(fe);
fe->next = proxies_list;
proxies_list = fe;
fe->last_change = now.tv_sec;
fe->id = strdup("GLOBAL");
fe->cap = PR_CAP_FE;
fe->maxconn = 10; /* default to 10 concurrent connections */
fe->timeout.client = MS_TO_TICKS(10000); /* default timeout of 10 seconds */
fe->conf.file = strdup(file);
fe->conf.line = line;
fe->accept = frontend_accept;
fe->default_target = &cli_applet.obj_type;
/* the stats frontend is the only one able to assign ID #0 */
fe->conf.id.key = fe->uuid = 0;
eb32_insert(&used_proxy_id, &fe->conf.id);
return fe;
}
/* This function parses a "stats" statement in the "global" section. It returns
* -1 if there is any error, otherwise zero. If it returns -1, it will write an
* error message into the <err> buffer which will be preallocated. The trailing
* '\n' must not be written. The function must be called with <args> pointing to
* the first word after "stats".
*/
static int stats_parse_global(char **args, int section_type, struct proxy *curpx,
struct proxy *defpx, const char *file, int line,
char **err)
{
struct bind_conf *bind_conf;
struct listener *l;
if (!strcmp(args[1], "socket")) {
int cur_arg;
if (*args[2] == 0) {
memprintf(err, "'%s %s' in global section expects an address or a path to a UNIX socket", args[0], args[1]);
return -1;
}
if (!global.stats_fe) {
if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
return -1;
}
}
bind_conf = bind_conf_alloc(global.stats_fe, file, line, args[2], xprt_get(XPRT_RAW));
bind_conf->level &= ~ACCESS_LVL_MASK;
bind_conf->level |= ACCESS_LVL_OPER; /* default access level */
if (!str2listener(args[2], global.stats_fe, bind_conf, file, line, err)) {
memprintf(err, "parsing [%s:%d] : '%s %s' : %s\n",
file, line, args[0], args[1], err && *err ? *err : "error");
return -1;
}
cur_arg = 3;
while (*args[cur_arg]) {
static int bind_dumped;
struct bind_kw *kw;
kw = bind_find_kw(args[cur_arg]);
if (kw) {
if (!kw->parse) {
memprintf(err, "'%s %s' : '%s' option is not implemented in this version (check build options).",
args[0], args[1], args[cur_arg]);
return -1;
}
if (kw->parse(args, cur_arg, global.stats_fe, bind_conf, err) != 0) {
if (err && *err)
memprintf(err, "'%s %s' : '%s'", args[0], args[1], *err);
else
memprintf(err, "'%s %s' : error encountered while processing '%s'",
args[0], args[1], args[cur_arg]);
return -1;
}
cur_arg += 1 + kw->skip;
continue;
}
if (!bind_dumped) {
bind_dump_kws(err);
indent_msg(err, 4);
bind_dumped = 1;
}
memprintf(err, "'%s %s' : unknown keyword '%s'.%s%s",
args[0], args[1], args[cur_arg],
err && *err ? " Registered keywords :" : "", err && *err ? *err : "");
return -1;
}
list_for_each_entry(l, &bind_conf->listeners, by_bind) {
l->accept = session_accept_fd;
l->default_target = global.stats_fe->default_target;
l->options |= LI_O_UNLIMITED; /* don't make the peers subject to global limits */
l->nice = -64; /* we want to boost priority for local stats */
global.maxsock++; /* for the listening socket */
}
}
else if (!strcmp(args[1], "timeout")) {
unsigned timeout;
const char *res = parse_time_err(args[2], &timeout, TIME_UNIT_MS);
if (res == PARSE_TIME_OVER) {
memprintf(err, "timer overflow in argument '%s' to '%s %s' (maximum value is 2147483647 ms or ~24.8 days)",
args[2], args[0], args[1]);
return -1;
}
else if (res == PARSE_TIME_UNDER) {
memprintf(err, "timer underflow in argument '%s' to '%s %s' (minimum non-null value is 1 ms)",
args[2], args[0], args[1]);
return -1;
}
else if (res) {
memprintf(err, "'%s %s' : unexpected character '%c'", args[0], args[1], *res);
return -1;
}
if (!timeout) {
memprintf(err, "'%s %s' expects a positive value", args[0], args[1]);
return -1;
}
if (!global.stats_fe) {
if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
return -1;
}
}
global.stats_fe->timeout.client = MS_TO_TICKS(timeout);
}
else if (!strcmp(args[1], "maxconn")) {
int maxconn = atol(args[2]);
if (maxconn <= 0) {
memprintf(err, "'%s %s' expects a positive value", args[0], args[1]);
return -1;
}
if (!global.stats_fe) {
if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
return -1;
}
}
global.stats_fe->maxconn = maxconn;
}
else if (!strcmp(args[1], "bind-process")) { /* enable the socket only on some processes */
int cur_arg = 2;
unsigned long set = 0;
if (!global.stats_fe) {
if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
return -1;
}
}
while (*args[cur_arg]) {
if (strcmp(args[cur_arg], "all") == 0) {
set = 0;
break;
}
if (parse_process_number(args[cur_arg], &set, MAX_PROCS, NULL, err)) {
memprintf(err, "'%s %s' : %s", args[0], args[1], *err);
return -1;
}
cur_arg++;
}
global.stats_fe->bind_proc = set;
}
else {
memprintf(err, "'%s' only supports 'socket', 'maxconn', 'bind-process' and 'timeout' (got '%s')", args[0], args[1]);
return -1;
}
return 0;
}
/*
* This function exports the bound addresses of a <frontend> in the environment
* variable <varname>. Those addresses are separated by semicolons and prefixed
* with their type (abns@, unix@, sockpair@ etc)
* Return -1 upon error, 0 otherwise
*/
int listeners_setenv(struct proxy *frontend, const char *varname)
{
struct buffer *trash = get_trash_chunk();
struct bind_conf *bind_conf;
if (frontend) {
list_for_each_entry(bind_conf, &frontend->conf.bind, by_fe) {
struct listener *l;
list_for_each_entry(l, &bind_conf->listeners, by_bind) {
char addr[46];
char port[6];
/* separate listener by semicolons */
if (trash->data)
chunk_appendf(trash, ";");
if (l->addr.ss_family == AF_UNIX) {
const struct sockaddr_un *un;
un = (struct sockaddr_un *)&l->addr;
if (un->sun_path[0] == '\0') {
chunk_appendf(trash, "abns@%s", un->sun_path+1);
} else {
chunk_appendf(trash, "unix@%s", un->sun_path);
}
} else if (l->addr.ss_family == AF_INET) {
addr_to_str(&l->addr, addr, sizeof(addr));
port_to_str(&l->addr, port, sizeof(port));
chunk_appendf(trash, "ipv4@%s:%s", addr, port);
} else if (l->addr.ss_family == AF_INET6) {
addr_to_str(&l->addr, addr, sizeof(addr));
port_to_str(&l->addr, port, sizeof(port));
chunk_appendf(trash, "ipv6@[%s]:%s", addr, port);
} else if (l->addr.ss_family == AF_CUST_SOCKPAIR) {
chunk_appendf(trash, "sockpair@%d", ((struct sockaddr_in *)&l->addr)->sin_addr.s_addr);
}
}
}
trash->area[trash->data++] = '\0';
if (setenv(varname, trash->area, 1) < 0)
return -1;
}
return 0;
}
int cli_socket_setenv()
{
if (listeners_setenv(global.stats_fe, "HAPROXY_CLI") < 0)
return -1;
if (listeners_setenv(mworker_proxy, "HAPROXY_MASTER_CLI") < 0)
return -1;
return 0;
}
REGISTER_CONFIG_POSTPARSER("cli", cli_socket_setenv);
/* Verifies that the CLI at least has a level at least as high as <level>
* (typically ACCESS_LVL_ADMIN). Returns 1 if OK, otherwise 0. In case of
* failure, an error message is prepared and the appctx's state is adjusted
* to print it so that a return 1 is enough to abort any processing.
*/
int cli_has_level(struct appctx *appctx, int level)
{
if ((appctx->cli_level & ACCESS_LVL_MASK) < level) {
cli_err(appctx, stats_permission_denied_msg);
return 0;
}
return 1;
}
/* same as cli_has_level but for the CLI proxy and without error message */
int pcli_has_level(struct stream *s, int level)
{
if ((s->pcli_flags & ACCESS_LVL_MASK) < level) {
return 0;
}
return 1;
}
/* Returns severity_output for the current session if set, or default for the socket */
static int cli_get_severity_output(struct appctx *appctx)
{
if (appctx->cli_severity_output)
return appctx->cli_severity_output;
return strm_li(si_strm(appctx->owner))->bind_conf->severity_output;
}
/* Processes the CLI interpreter on the stats socket. This function is called
* from the CLI's IO handler running in an appctx context. The function returns 1
* if the request was understood, otherwise zero. It is called with appctx->st0
* set to CLI_ST_GETREQ and presets ->st2 to 0 so that parsers don't have to do
* it. It will possilbly leave st0 to CLI_ST_CALLBACK if the keyword needs to
* have its own I/O handler called again. Most of the time, parsers will only
* set st0 to CLI_ST_PRINT and put their message to be displayed into cli.msg.
* If a keyword parser is NULL and an I/O handler is declared, the I/O handler
* will automatically be used.
*/
static int cli_parse_request(struct appctx *appctx)
{
char *args[MAX_STATS_ARGS + 1], *p, *end, *payload = NULL;
int i = 0;
struct cli_kw *kw;
appctx->st2 = 0;
memset(&appctx->ctx.cli, 0, sizeof(appctx->ctx.cli));
p = appctx->chunk->area;
end = p + appctx->chunk->data;
/*
* Get the payload start if there is one.
* For the sake of simplicity, the payload pattern is looked up
* everywhere from the start of the input but it can only be found
* at the end of the first line if APPCTX_CLI_ST1_PAYLOAD is set.
*
* The input string was zero terminated so it is safe to use
* the str*() functions throughout the parsing
*/
if (appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) {
payload = strstr(p, PAYLOAD_PATTERN);
end = payload;
/* skip the pattern */
payload += strlen(PAYLOAD_PATTERN);
}
/*
* Get pointers on words.
* One extra slot is reserved to store a pointer on a null byte.
*/
while (i < MAX_STATS_ARGS && p < end) {
int j, k;
/* skip leading spaces/tabs */
p += strspn(p, " \t");
if (!*p)
break;
args[i] = p;
while (1) {
p += strcspn(p, " \t\\");
/* escaped chars using backlashes (\) */
if (*p == '\\') {
if (!*++p)
break;
if (!*++p)
break;
} else {
break;
}
}
*p++ = 0;
/* unescape backslashes (\) */
for (j = 0, k = 0; args[i][k]; k++) {
if (args[i][k] == '\\') {
if (args[i][k + 1] == '\\')
k++;
else
continue;
}
args[i][j] = args[i][k];
j++;
}
args[i][j] = 0;
i++;
}
/* fill unused slots */
p = appctx->chunk->area + appctx->chunk->data;
for (; i < MAX_STATS_ARGS + 1; i++)
args[i] = p;
kw = cli_find_kw(args);
if (!kw)
return 0;
/* in a worker or normal process, don't display master only commands */
if (master == 0 && (kw->level & ACCESS_MASTER_ONLY))
return 0;
/* in master don't displays if we don't have the master bits */
if (master == 1 && !(kw->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)))
return 0;
/* only accept expert commands in expert mode */
if ((kw->level & ~appctx->cli_level) & ACCESS_EXPERT)
return 0;
appctx->io_handler = kw->io_handler;
appctx->io_release = kw->io_release;
if (kw->parse && kw->parse(args, payload, appctx, kw->private) != 0)
goto fail;
/* kw->parse could set its own io_handler or io_release handler */
if (!appctx->io_handler)
goto fail;
appctx->st0 = CLI_ST_CALLBACK;
return 1;
fail:
appctx->io_handler = NULL;
appctx->io_release = NULL;
return 1;
}
/* prepends then outputs the argument msg with a syslog-type severity depending on severity_output value */
static int cli_output_msg(struct channel *chn, const char *msg, int severity, int severity_output)
{
struct buffer *tmp;
if (likely(severity_output == CLI_SEVERITY_NONE))
return ci_putblk(chn, msg, strlen(msg));
tmp = get_trash_chunk();
chunk_reset(tmp);
if (severity < 0 || severity > 7) {
ha_warning("socket command feedback with invalid severity %d", severity);
chunk_printf(tmp, "[%d]: ", severity);
}
else {
switch (severity_output) {
case CLI_SEVERITY_NUMBER:
chunk_printf(tmp, "[%d]: ", severity);
break;
case CLI_SEVERITY_STRING:
chunk_printf(tmp, "[%s]: ", log_levels[severity]);
break;
default:
ha_warning("Unrecognized severity output %d", severity_output);
}
}
chunk_appendf(tmp, "%s", msg);
return ci_putblk(chn, tmp->area, strlen(tmp->area));
}
/* This I/O handler runs as an applet embedded in a stream interface. It is
* used to processes I/O from/to the stats unix socket. The system relies on a
* state machine handling requests and various responses. We read a request,
* then we process it and send the response, and we possibly display a prompt.
* Then we can read again. The state is stored in appctx->st0 and is one of the
* CLI_ST_* constants. appctx->st1 is used to indicate whether prompt is enabled
* or not.
*/
static void cli_io_handler(struct appctx *appctx)
{
struct stream_interface *si = appctx->owner;
struct channel *req = si_oc(si);
struct channel *res = si_ic(si);
struct bind_conf *bind_conf = strm_li(si_strm(si))->bind_conf;
int reql;
int len;
if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
goto out;
/* Check if the input buffer is available. */
if (res->buf.size == 0) {
/* buf.size==0 means we failed to get a buffer and were
* already subscribed to a wait list to get a buffer.
*/
goto out;
}
while (1) {
if (appctx->st0 == CLI_ST_INIT) {
/* Stats output not initialized yet */
memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
/* reset severity to default at init */
appctx->cli_severity_output = bind_conf->severity_output;
appctx->st0 = CLI_ST_GETREQ;
appctx->cli_level = bind_conf->level;
}
else if (appctx->st0 == CLI_ST_END) {
/* Let's close for real now. We just close the request
* side, the conditions below will complete if needed.
*/
si_shutw(si);
free_trash_chunk(appctx->chunk);
break;
}
else if (appctx->st0 == CLI_ST_GETREQ) {
char *str;
/* use a trash chunk to store received data */
if (!appctx->chunk) {
appctx->chunk = alloc_trash_chunk();
if (!appctx->chunk) {
appctx->st0 = CLI_ST_END;
continue;
}
}
str = appctx->chunk->area + appctx->chunk->data;
/* ensure we have some output room left in the event we
* would want to return some info right after parsing.
*/
if (buffer_almost_full(si_ib(si))) {
si_rx_room_blk(si);
break;
}
/* '- 1' is to ensure a null byte can always be inserted at the end */
reql = co_getline(si_oc(si), str,
appctx->chunk->size - appctx->chunk->data - 1);
if (reql <= 0) { /* closed or EOL not found */
if (reql == 0)
break;
appctx->st0 = CLI_ST_END;
continue;
}
if (!(appctx->st1 & APPCTX_CLI_ST1_PAYLOAD)) {
/* seek for a possible unescaped semi-colon. If we find
* one, we replace it with an LF and skip only this part.
*/
for (len = 0; len < reql; len++) {
if (str[len] == '\\') {
len++;
continue;
}
if (str[len] == ';') {
str[len] = '\n';
reql = len + 1;
break;
}
}
}
/* now it is time to check that we have a full line,
* remove the trailing \n and possibly \r, then cut the
* line.
*/
len = reql - 1;
if (str[len] != '\n') {
appctx->st0 = CLI_ST_END;
continue;
}
if (len && str[len-1] == '\r')
len--;
str[len] = '\0';
appctx->chunk->data += len;
if (appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) {
appctx->chunk->area[appctx->chunk->data] = '\n';
appctx->chunk->area[appctx->chunk->data + 1] = 0;
appctx->chunk->data++;
}
appctx->st0 = CLI_ST_PROMPT;
if (appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) {
/* empty line */
if (!len) {
/* remove the last two \n */
appctx->chunk->data -= 2;
appctx->chunk->area[appctx->chunk->data] = 0;
if (!cli_parse_request(appctx))
cli_gen_usage_msg(appctx);
chunk_reset(appctx->chunk);
/* NB: cli_sock_parse_request() may have put
* another CLI_ST_O_* into appctx->st0.
*/
appctx->st1 &= ~APPCTX_CLI_ST1_PAYLOAD;
}
}
else {
/*
* Look for the "payload start" pattern at the end of a line
* Its location is not remembered here, this is just to switch
* to a gathering mode.
*/
if (!strcmp(appctx->chunk->area + appctx->chunk->data - strlen(PAYLOAD_PATTERN), PAYLOAD_PATTERN))
appctx->st1 |= APPCTX_CLI_ST1_PAYLOAD;
else {
/* no payload, the command is complete: parse the request */
if (!cli_parse_request(appctx))
cli_gen_usage_msg(appctx);
chunk_reset(appctx->chunk);
}
}
/* re-adjust req buffer */
co_skip(si_oc(si), reql);
req->flags |= CF_READ_DONTWAIT; /* we plan to read small requests */
}
else { /* output functions */
const char *msg;
int sev;
switch (appctx->st0) {
case CLI_ST_PROMPT:
break;
case CLI_ST_PRINT: /* print const message in msg */
case CLI_ST_PRINT_ERR: /* print const error in msg */
case CLI_ST_PRINT_DYN: /* print dyn message in msg, free */
case CLI_ST_PRINT_FREE: /* print dyn error in err, free */
if (appctx->st0 == CLI_ST_PRINT || appctx->st0 == CLI_ST_PRINT_ERR) {
sev = appctx->st0 == CLI_ST_PRINT_ERR ?
LOG_ERR : appctx->ctx.cli.severity;
msg = appctx->ctx.cli.msg;
}
else if (appctx->st0 == CLI_ST_PRINT_DYN || appctx->st0 == CLI_ST_PRINT_FREE) {
sev = appctx->st0 == CLI_ST_PRINT_FREE ?
LOG_ERR : appctx->ctx.cli.severity;
msg = appctx->ctx.cli.err;
if (!msg) {
sev = LOG_ERR;
msg = "Out of memory.\n";
}
}
else {
sev = LOG_ERR;
msg = "Internal error.\n";
}
if (cli_output_msg(res, msg, sev, cli_get_severity_output(appctx)) != -1) {
if (appctx->st0 == CLI_ST_PRINT_FREE ||
appctx->st0 == CLI_ST_PRINT_DYN) {
free(appctx->ctx.cli.err);
appctx->ctx.cli.err = NULL;
}
appctx->st0 = CLI_ST_PROMPT;
}
else
si_rx_room_blk(si);
break;
case CLI_ST_CALLBACK: /* use custom pointer */
if (appctx->io_handler)
if (appctx->io_handler(appctx)) {
appctx->st0 = CLI_ST_PROMPT;
if (appctx->io_release) {
appctx->io_release(appctx);
appctx->io_release = NULL;
}
}
break;
default: /* abnormal state */
si->flags |= SI_FL_ERR;
break;
}
/* The post-command prompt is either LF alone or LF + '> ' in interactive mode */
if (appctx->st0 == CLI_ST_PROMPT) {
const char *prompt = "";
if (appctx->st1 & APPCTX_CLI_ST1_PROMPT) {
/*
* when entering a payload with interactive mode, change the prompt
* to emphasize that more data can still be sent
*/
if (appctx->chunk->data && appctx->st1 & APPCTX_CLI_ST1_PAYLOAD)
prompt = "+ ";
else
prompt = "\n> ";
}
else {
if (!(appctx->st1 & (APPCTX_CLI_ST1_PAYLOAD|APPCTX_CLI_ST1_NOLF)))
prompt = "\n";
}
if (ci_putstr(si_ic(si), prompt) != -1)
appctx->st0 = CLI_ST_GETREQ;
else
si_rx_room_blk(si);
}
/* If the output functions are still there, it means they require more room. */
if (appctx->st0 >= CLI_ST_OUTPUT)
break;
/* Now we close the output if one of the writers did so,
* or if we're not in interactive mode and the request
* buffer is empty. This still allows pipelined requests
* to be sent in non-interactive mode.
*/
if (((res->flags & (CF_SHUTW|CF_SHUTW_NOW))) ||
(!(appctx->st1 & APPCTX_CLI_ST1_PROMPT) && !co_data(req) && (!(appctx->st1 & APPCTX_CLI_ST1_PAYLOAD)))) {
appctx->st0 = CLI_ST_END;
continue;
}
/* switch state back to GETREQ to read next requests */
appctx->st0 = CLI_ST_GETREQ;
/* reactivate the \n at the end of the response for the next command */
appctx->st1 &= ~APPCTX_CLI_ST1_NOLF;
}
}
if ((res->flags & CF_SHUTR) && (si->state == SI_ST_EST)) {
DPRINTF(stderr, "%s@%d: si to buf closed. req=%08x, res=%08x, st=%d\n",
__FUNCTION__, __LINE__, req->flags, res->flags, si->state);
/* Other side has closed, let's abort if we have no more processing to do
* and nothing more to consume. This is comparable to a broken pipe, so
* we forward the close to the request side so that it flows upstream to
* the client.
*/
si_shutw(si);
}
if ((req->flags & CF_SHUTW) && (si->state == SI_ST_EST) && (appctx->st0 < CLI_ST_OUTPUT)) {
DPRINTF(stderr, "%s@%d: buf to si closed. req=%08x, res=%08x, st=%d\n",
__FUNCTION__, __LINE__, req->flags, res->flags, si->state);
/* We have no more processing to do, and nothing more to send, and
* the client side has closed. So we'll forward this state downstream
* on the response buffer.
*/
si_shutr(si);
res->flags |= CF_READ_NULL;
}
out:
DPRINTF(stderr, "%s@%d: st=%d, rqf=%x, rpf=%x, rqh=%lu, rqs=%lu, rh=%lu, rs=%lu\n",
__FUNCTION__, __LINE__,
si->state, req->flags, res->flags, ci_data(req), co_data(req), ci_data(res), co_data(res));
}
/* This is called when the stream interface is closed. For instance, upon an
* external abort, we won't call the i/o handler anymore so we may need to
* remove back references to the stream currently being dumped.
*/
static void cli_release_handler(struct appctx *appctx)
{
if (appctx->io_release) {
appctx->io_release(appctx);
appctx->io_release = NULL;
}
else if (appctx->st0 == CLI_ST_PRINT_FREE || appctx->st0 == CLI_ST_PRINT_DYN) {
free(appctx->ctx.cli.err);
appctx->ctx.cli.err = NULL;
}
}
/* This function dumps all environmnent variables to the buffer. It returns 0
* if the output buffer is full and it needs to be called again, otherwise
* non-zero. Dumps only one entry if st2 == STAT_ST_END. It uses cli.p0 as the
* pointer to the current variable.
*/
static int cli_io_handler_show_env(struct appctx *appctx)
{
struct stream_interface *si = appctx->owner;
char **var = appctx->ctx.cli.p0;
if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
return 1;
chunk_reset(&trash);
/* we have two inner loops here, one for the proxy, the other one for
* the buffer.
*/
while (*var) {
chunk_printf(&trash, "%s\n", *var);
if (ci_putchk(si_ic(si), &trash) == -1) {
si_rx_room_blk(si);
return 0;
}
if (appctx->st2 == STAT_ST_END)
break;
var++;
appctx->ctx.cli.p0 = var;
}
/* dump complete */
return 1;
}
/* This function dumps all file descriptors states (or the requested one) to
* the buffer. It returns 0 if the output buffer is full and it needs to be
* called again, otherwise non-zero. Dumps only one entry if st2 == STAT_ST_END.
* It uses cli.i0 as the fd number to restart from.
*/
static int cli_io_handler_show_fd(struct appctx *appctx)
{
struct stream_interface *si = appctx->owner;
int fd = appctx->ctx.cli.i0;
int ret = 1;
if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
goto end;
chunk_reset(&trash);
/* isolate the threads once per round. We're limited to a buffer worth
* of output anyway, it cannot last very long.
*/
thread_isolate();
/* we have two inner loops here, one for the proxy, the other one for
* the buffer.
*/
while (fd >= 0 && fd < global.maxsock) {
struct fdtab fdt;
struct listener *li = NULL;
struct server *sv = NULL;
struct proxy *px = NULL;
const struct mux_ops *mux = NULL;
void *ctx = NULL;
uint32_t conn_flags = 0;