1 /*
2 * Functions dedicated to statistics output and the stats socket
3 *
4 * Copyright 2000-2012 Willy Tarreau <w@1wt.eu>
5 * Copyright 2007-2009 Krzysztof Piotr Oledzki <ole@ans.pl>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
12 */
13
14 #include <ctype.h>
15 #include <errno.h>
16 #include <fcntl.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <pwd.h>
21 #include <grp.h>
22
23 #include <sys/socket.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26
27 #include <net/if.h>
28
29 #include <haproxy/activity.h>
30 #include <haproxy/api.h>
31 #include <haproxy/applet-t.h>
32 #include <haproxy/base64.h>
33 #include <haproxy/cfgparse.h>
34 #include <haproxy/channel.h>
35 #include <haproxy/check.h>
36 #include <haproxy/cli.h>
37 #include <haproxy/compression.h>
38 #include <haproxy/dns-t.h>
39 #include <haproxy/errors.h>
40 #include <haproxy/fd.h>
41 #include <haproxy/freq_ctr.h>
42 #include <haproxy/frontend.h>
43 #include <haproxy/global.h>
44 #include <haproxy/list.h>
45 #include <haproxy/listener.h>
46 #include <haproxy/log.h>
47 #include <haproxy/mworker-t.h>
48 #include <haproxy/pattern-t.h>
49 #include <haproxy/peers.h>
50 #include <haproxy/pipe.h>
51 #include <haproxy/protocol.h>
52 #include <haproxy/proxy.h>
53 #include <haproxy/sample-t.h>
54 #include <haproxy/server.h>
55 #include <haproxy/session.h>
56 #include <haproxy/sock.h>
57 #include <haproxy/stats-t.h>
58 #include <haproxy/stream.h>
59 #include <haproxy/stream_interface.h>
60 #include <haproxy/task.h>
61 #include <haproxy/ticks.h>
62 #include <haproxy/time.h>
63 #include <haproxy/tools.h>
64 #include <haproxy/version.h>
65
66 #define PAYLOAD_PATTERN "<<"
67
68 static struct applet cli_applet;
69 static struct applet mcli_applet;
70
71 static const char stats_sock_usage_msg[] =
72 "Unknown command. Please enter one of the following commands only :\n"
73 " help : this message\n"
74 " prompt : toggle interactive mode with prompt\n"
75 " quit : disconnect\n"
76 "";
77
78 static const char stats_permission_denied_msg[] =
79 "Permission denied\n"
80 "";
81
82
83 static THREAD_LOCAL char *dynamic_usage_msg = NULL;
84
85 /* List head of cli keywords */
86 static struct cli_kw_list cli_keywords = {
87 .list = LIST_HEAD_INIT(cli_keywords.list)
88 };
89
90 extern const char *stat_status_codes[];
91
92 struct proxy *mworker_proxy; /* CLI proxy of the master */
93
cli_gen_usage_msg(struct appctx * appctx)94 static char *cli_gen_usage_msg(struct appctx *appctx)
95 {
96 struct cli_kw_list *kw_list;
97 struct cli_kw *kw;
98 struct buffer *tmp = get_trash_chunk();
99 struct buffer out;
100
101 free(dynamic_usage_msg);
102 dynamic_usage_msg = NULL;
103
104 if (LIST_ISEMPTY(&cli_keywords.list))
105 goto end;
106
107 chunk_reset(tmp);
108 chunk_strcat(tmp, stats_sock_usage_msg);
109 list_for_each_entry(kw_list, &cli_keywords.list, list) {
110 kw = &kw_list->kw[0];
111 while (kw->str_kw[0]) {
112
113 /* in a worker or normal process, don't display master only commands */
114 if (appctx->applet == &cli_applet && (kw->level & ACCESS_MASTER_ONLY))
115 goto next_kw;
116
117 /* in master don't displays if we don't have the master bits */
118 if (appctx->applet == &mcli_applet && !(kw->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)))
119 goto next_kw;
120
121 /* only show expert commands in expert mode */
122 if ((kw->level & ~appctx->cli_level) & ACCESS_EXPERT)
123 goto next_kw;
124
125 if (kw->usage)
126 chunk_appendf(tmp, " %s\n", kw->usage);
127
128 next_kw:
129
130 kw++;
131 }
132 }
133 chunk_init(&out, NULL, 0);
134 chunk_dup(&out, tmp);
135 dynamic_usage_msg = out.area;
136
137 end:
138 if (dynamic_usage_msg) {
139 appctx->ctx.cli.severity = LOG_INFO;
140 appctx->ctx.cli.msg = dynamic_usage_msg;
141 }
142 else {
143 appctx->ctx.cli.severity = LOG_INFO;
144 appctx->ctx.cli.msg = stats_sock_usage_msg;
145 }
146 appctx->st0 = CLI_ST_PRINT;
147
148 return dynamic_usage_msg;
149 }
150
cli_find_kw(char ** args)151 struct cli_kw* cli_find_kw(char **args)
152 {
153 struct cli_kw_list *kw_list;
154 struct cli_kw *kw;/* current cli_kw */
155 char **tmp_args;
156 const char **tmp_str_kw;
157 int found = 0;
158
159 if (LIST_ISEMPTY(&cli_keywords.list))
160 return NULL;
161
162 list_for_each_entry(kw_list, &cli_keywords.list, list) {
163 kw = &kw_list->kw[0];
164 while (*kw->str_kw) {
165 tmp_args = args;
166 tmp_str_kw = kw->str_kw;
167 while (*tmp_str_kw) {
168 if (strcmp(*tmp_str_kw, *tmp_args) == 0) {
169 found = 1;
170 } else {
171 found = 0;
172 break;
173 }
174 tmp_args++;
175 tmp_str_kw++;
176 }
177 if (found)
178 return (kw);
179 kw++;
180 }
181 }
182 return NULL;
183 }
184
cli_find_kw_exact(char ** args)185 struct cli_kw* cli_find_kw_exact(char **args)
186 {
187 struct cli_kw_list *kw_list;
188 int found = 0;
189 int i;
190 int j;
191
192 if (LIST_ISEMPTY(&cli_keywords.list))
193 return NULL;
194
195 list_for_each_entry(kw_list, &cli_keywords.list, list) {
196 for (i = 0; kw_list->kw[i].str_kw[0]; i++) {
197 found = 1;
198 for (j = 0; j < CLI_PREFIX_KW_NB; j++) {
199 if (args[j] == NULL && kw_list->kw[i].str_kw[j] == NULL) {
200 break;
201 }
202 if (args[j] == NULL || kw_list->kw[i].str_kw[j] == NULL) {
203 found = 0;
204 break;
205 }
206 if (strcmp(args[j], kw_list->kw[i].str_kw[j]) != 0) {
207 found = 0;
208 break;
209 }
210 }
211 if (found)
212 return &kw_list->kw[i];
213 }
214 }
215 return NULL;
216 }
217
cli_register_kw(struct cli_kw_list * kw_list)218 void cli_register_kw(struct cli_kw_list *kw_list)
219 {
220 LIST_ADDQ(&cli_keywords.list, &kw_list->list);
221 }
222
223
224 /* allocate a new stats frontend named <name>, and return it
225 * (or NULL in case of lack of memory).
226 */
alloc_stats_fe(const char * name,const char * file,int line)227 static struct proxy *alloc_stats_fe(const char *name, const char *file, int line)
228 {
229 struct proxy *fe;
230
231 fe = calloc(1, sizeof(*fe));
232 if (!fe)
233 return NULL;
234
235 init_new_proxy(fe);
236 fe->next = proxies_list;
237 proxies_list = fe;
238 fe->last_change = now.tv_sec;
239 fe->id = strdup("GLOBAL");
240 fe->cap = PR_CAP_FE;
241 fe->maxconn = 10; /* default to 10 concurrent connections */
242 fe->timeout.client = MS_TO_TICKS(10000); /* default timeout of 10 seconds */
243 fe->conf.file = strdup(file);
244 fe->conf.line = line;
245 fe->accept = frontend_accept;
246 fe->default_target = &cli_applet.obj_type;
247
248 /* the stats frontend is the only one able to assign ID #0 */
249 fe->conf.id.key = fe->uuid = 0;
250 eb32_insert(&used_proxy_id, &fe->conf.id);
251 return fe;
252 }
253
254 /* This function parses a "stats" statement in the "global" section. It returns
255 * -1 if there is any error, otherwise zero. If it returns -1, it will write an
256 * error message into the <err> buffer which will be preallocated. The trailing
257 * '\n' must not be written. The function must be called with <args> pointing to
258 * the first word after "stats".
259 */
stats_parse_global(char ** args,int section_type,struct proxy * curpx,struct proxy * defpx,const char * file,int line,char ** err)260 static int stats_parse_global(char **args, int section_type, struct proxy *curpx,
261 struct proxy *defpx, const char *file, int line,
262 char **err)
263 {
264 struct bind_conf *bind_conf;
265 struct listener *l;
266
267 if (!strcmp(args[1], "socket")) {
268 int cur_arg;
269
270 if (*args[2] == 0) {
271 memprintf(err, "'%s %s' in global section expects an address or a path to a UNIX socket", args[0], args[1]);
272 return -1;
273 }
274
275 if (!global.stats_fe) {
276 if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
277 memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
278 return -1;
279 }
280 }
281
282 bind_conf = bind_conf_alloc(global.stats_fe, file, line, args[2], xprt_get(XPRT_RAW));
283 bind_conf->level &= ~ACCESS_LVL_MASK;
284 bind_conf->level |= ACCESS_LVL_OPER; /* default access level */
285
286 if (!str2listener(args[2], global.stats_fe, bind_conf, file, line, err)) {
287 memprintf(err, "parsing [%s:%d] : '%s %s' : %s\n",
288 file, line, args[0], args[1], err && *err ? *err : "error");
289 return -1;
290 }
291
292 cur_arg = 3;
293 while (*args[cur_arg]) {
294 static int bind_dumped;
295 struct bind_kw *kw;
296
297 kw = bind_find_kw(args[cur_arg]);
298 if (kw) {
299 if (!kw->parse) {
300 memprintf(err, "'%s %s' : '%s' option is not implemented in this version (check build options).",
301 args[0], args[1], args[cur_arg]);
302 return -1;
303 }
304
305 if (kw->parse(args, cur_arg, global.stats_fe, bind_conf, err) != 0) {
306 if (err && *err)
307 memprintf(err, "'%s %s' : '%s'", args[0], args[1], *err);
308 else
309 memprintf(err, "'%s %s' : error encountered while processing '%s'",
310 args[0], args[1], args[cur_arg]);
311 return -1;
312 }
313
314 cur_arg += 1 + kw->skip;
315 continue;
316 }
317
318 if (!bind_dumped) {
319 bind_dump_kws(err);
320 indent_msg(err, 4);
321 bind_dumped = 1;
322 }
323
324 memprintf(err, "'%s %s' : unknown keyword '%s'.%s%s",
325 args[0], args[1], args[cur_arg],
326 err && *err ? " Registered keywords :" : "", err && *err ? *err : "");
327 return -1;
328 }
329
330 list_for_each_entry(l, &bind_conf->listeners, by_bind) {
331 l->accept = session_accept_fd;
332 l->default_target = global.stats_fe->default_target;
333 l->options |= LI_O_UNLIMITED; /* don't make the peers subject to global limits */
334 l->nice = -64; /* we want to boost priority for local stats */
335 global.maxsock++; /* for the listening socket */
336 }
337 }
338 else if (!strcmp(args[1], "timeout")) {
339 unsigned timeout;
340 const char *res = parse_time_err(args[2], &timeout, TIME_UNIT_MS);
341
342 if (res == PARSE_TIME_OVER) {
343 memprintf(err, "timer overflow in argument '%s' to '%s %s' (maximum value is 2147483647 ms or ~24.8 days)",
344 args[2], args[0], args[1]);
345 return -1;
346 }
347 else if (res == PARSE_TIME_UNDER) {
348 memprintf(err, "timer underflow in argument '%s' to '%s %s' (minimum non-null value is 1 ms)",
349 args[2], args[0], args[1]);
350 return -1;
351 }
352 else if (res) {
353 memprintf(err, "'%s %s' : unexpected character '%c'", args[0], args[1], *res);
354 return -1;
355 }
356
357 if (!timeout) {
358 memprintf(err, "'%s %s' expects a positive value", args[0], args[1]);
359 return -1;
360 }
361 if (!global.stats_fe) {
362 if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
363 memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
364 return -1;
365 }
366 }
367 global.stats_fe->timeout.client = MS_TO_TICKS(timeout);
368 }
369 else if (!strcmp(args[1], "maxconn")) {
370 int maxconn = atol(args[2]);
371
372 if (maxconn <= 0) {
373 memprintf(err, "'%s %s' expects a positive value", args[0], args[1]);
374 return -1;
375 }
376
377 if (!global.stats_fe) {
378 if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
379 memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
380 return -1;
381 }
382 }
383 global.stats_fe->maxconn = maxconn;
384 }
385 else if (!strcmp(args[1], "bind-process")) { /* enable the socket only on some processes */
386 int cur_arg = 2;
387 unsigned long set = 0;
388
389 if (!global.stats_fe) {
390 if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
391 memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
392 return -1;
393 }
394 }
395
396 while (*args[cur_arg]) {
397 if (strcmp(args[cur_arg], "all") == 0) {
398 set = 0;
399 break;
400 }
401 if (parse_process_number(args[cur_arg], &set, MAX_PROCS, NULL, err)) {
402 memprintf(err, "'%s %s' : %s", args[0], args[1], *err);
403 return -1;
404 }
405 cur_arg++;
406 }
407 global.stats_fe->bind_proc = set;
408 }
409 else {
410 memprintf(err, "'%s' only supports 'socket', 'maxconn', 'bind-process' and 'timeout' (got '%s')", args[0], args[1]);
411 return -1;
412 }
413 return 0;
414 }
415
416 /*
417 * This function exports the bound addresses of a <frontend> in the environment
418 * variable <varname>. Those addresses are separated by semicolons and prefixed
419 * with their type (abns@, unix@, sockpair@ etc)
420 * Return -1 upon error, 0 otherwise
421 */
listeners_setenv(struct proxy * frontend,const char * varname)422 int listeners_setenv(struct proxy *frontend, const char *varname)
423 {
424 struct buffer *trash = get_trash_chunk();
425 struct bind_conf *bind_conf;
426
427 if (frontend) {
428 list_for_each_entry(bind_conf, &frontend->conf.bind, by_fe) {
429 struct listener *l;
430
431 list_for_each_entry(l, &bind_conf->listeners, by_bind) {
432 char addr[46];
433 char port[6];
434
435 /* separate listener by semicolons */
436 if (trash->data)
437 chunk_appendf(trash, ";");
438
439 if (l->rx.addr.ss_family == AF_UNIX) {
440 const struct sockaddr_un *un;
441
442 un = (struct sockaddr_un *)&l->rx.addr;
443 if (un->sun_path[0] == '\0') {
444 chunk_appendf(trash, "abns@%s", un->sun_path+1);
445 } else {
446 chunk_appendf(trash, "unix@%s", un->sun_path);
447 }
448 } else if (l->rx.addr.ss_family == AF_INET) {
449 addr_to_str(&l->rx.addr, addr, sizeof(addr));
450 port_to_str(&l->rx.addr, port, sizeof(port));
451 chunk_appendf(trash, "ipv4@%s:%s", addr, port);
452 } else if (l->rx.addr.ss_family == AF_INET6) {
453 addr_to_str(&l->rx.addr, addr, sizeof(addr));
454 port_to_str(&l->rx.addr, port, sizeof(port));
455 chunk_appendf(trash, "ipv6@[%s]:%s", addr, port);
456 } else if (l->rx.addr.ss_family == AF_CUST_SOCKPAIR) {
457 chunk_appendf(trash, "sockpair@%d", ((struct sockaddr_in *)&l->rx.addr)->sin_addr.s_addr);
458 }
459 }
460 }
461 trash->area[trash->data++] = '\0';
462 if (setenv(varname, trash->area, 1) < 0)
463 return -1;
464 }
465
466 return 0;
467 }
468
cli_socket_setenv()469 int cli_socket_setenv()
470 {
471 if (listeners_setenv(global.stats_fe, "HAPROXY_CLI") < 0)
472 return -1;
473 if (listeners_setenv(mworker_proxy, "HAPROXY_MASTER_CLI") < 0)
474 return -1;
475
476 return 0;
477 }
478
479 REGISTER_CONFIG_POSTPARSER("cli", cli_socket_setenv);
480
481 /* Verifies that the CLI at least has a level at least as high as <level>
482 * (typically ACCESS_LVL_ADMIN). Returns 1 if OK, otherwise 0. In case of
483 * failure, an error message is prepared and the appctx's state is adjusted
484 * to print it so that a return 1 is enough to abort any processing.
485 */
cli_has_level(struct appctx * appctx,int level)486 int cli_has_level(struct appctx *appctx, int level)
487 {
488
489 if ((appctx->cli_level & ACCESS_LVL_MASK) < level) {
490 cli_err(appctx, stats_permission_denied_msg);
491 return 0;
492 }
493 return 1;
494 }
495
496 /* same as cli_has_level but for the CLI proxy and without error message */
pcli_has_level(struct stream * s,int level)497 int pcli_has_level(struct stream *s, int level)
498 {
499 if ((s->pcli_flags & ACCESS_LVL_MASK) < level) {
500 return 0;
501 }
502 return 1;
503 }
504
505 /* Returns severity_output for the current session if set, or default for the socket */
cli_get_severity_output(struct appctx * appctx)506 static int cli_get_severity_output(struct appctx *appctx)
507 {
508 if (appctx->cli_severity_output)
509 return appctx->cli_severity_output;
510 return strm_li(si_strm(appctx->owner))->bind_conf->severity_output;
511 }
512
513 /* Processes the CLI interpreter on the stats socket. This function is called
514 * from the CLI's IO handler running in an appctx context. The function returns 1
515 * if the request was understood, otherwise zero. It is called with appctx->st0
516 * set to CLI_ST_GETREQ and presets ->st2 to 0 so that parsers don't have to do
517 * it. It will possilbly leave st0 to CLI_ST_CALLBACK if the keyword needs to
518 * have its own I/O handler called again. Most of the time, parsers will only
519 * set st0 to CLI_ST_PRINT and put their message to be displayed into cli.msg.
520 * If a keyword parser is NULL and an I/O handler is declared, the I/O handler
521 * will automatically be used.
522 */
cli_parse_request(struct appctx * appctx)523 static int cli_parse_request(struct appctx *appctx)
524 {
525 char *args[MAX_STATS_ARGS + 1], *p, *end, *payload = NULL;
526 int i = 0;
527 struct cli_kw *kw;
528
529 appctx->st2 = 0;
530 memset(&appctx->ctx.cli, 0, sizeof(appctx->ctx.cli));
531
532 p = appctx->chunk->area;
533 end = p + appctx->chunk->data;
534
535 /*
536 * Get pointers on words.
537 * One extra slot is reserved to store a pointer on a null byte.
538 */
539 while (i < MAX_STATS_ARGS && p < end) {
540 int j, k;
541
542 /* skip leading spaces/tabs */
543 p += strspn(p, " \t");
544 if (!*p)
545 break;
546
547 if (strcmp(p, PAYLOAD_PATTERN) == 0) {
548 /* payload pattern recognized here, this is not an arg anymore,
549 * the payload starts at the first byte that follows the zero
550 * after the pattern.
551 */
552 payload = p + strlen(PAYLOAD_PATTERN) + 1;
553 break;
554 }
555
556 args[i] = p;
557 while (1) {
558 p += strcspn(p, " \t\\");
559 /* escaped chars using backlashes (\) */
560 if (*p == '\\') {
561 if (!*++p)
562 break;
563 if (!*++p)
564 break;
565 } else {
566 break;
567 }
568 }
569 *p++ = 0;
570
571 /* unescape backslashes (\) */
572 for (j = 0, k = 0; args[i][k]; k++) {
573 if (args[i][k] == '\\') {
574 if (args[i][k + 1] == '\\')
575 k++;
576 else
577 continue;
578 }
579 args[i][j] = args[i][k];
580 j++;
581 }
582 args[i][j] = 0;
583
584 i++;
585 }
586 /* fill unused slots */
587 p = appctx->chunk->area + appctx->chunk->data;
588 for (; i < MAX_STATS_ARGS + 1; i++)
589 args[i] = p;
590
591 kw = cli_find_kw(args);
592 if (!kw)
593 return 0;
594
595 /* in a worker or normal process, don't display master only commands */
596 if (appctx->applet == &cli_applet && (kw->level & ACCESS_MASTER_ONLY))
597 return 0;
598
599 /* in master don't displays if we don't have the master bits */
600 if (appctx->applet == &mcli_applet && !(kw->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)))
601 return 0;
602
603 /* only accept expert commands in expert mode */
604 if ((kw->level & ~appctx->cli_level) & ACCESS_EXPERT)
605 return 0;
606
607 appctx->io_handler = kw->io_handler;
608 appctx->io_release = kw->io_release;
609
610 if (kw->parse && kw->parse(args, payload, appctx, kw->private) != 0)
611 goto fail;
612
613 /* kw->parse could set its own io_handler or io_release handler */
614 if (!appctx->io_handler)
615 goto fail;
616
617 appctx->st0 = CLI_ST_CALLBACK;
618 return 1;
619 fail:
620 appctx->io_handler = NULL;
621 appctx->io_release = NULL;
622 return 1;
623 }
624
625 /* prepends then outputs the argument msg with a syslog-type severity depending on severity_output value */
cli_output_msg(struct channel * chn,const char * msg,int severity,int severity_output)626 static int cli_output_msg(struct channel *chn, const char *msg, int severity, int severity_output)
627 {
628 struct buffer *tmp;
629
630 if (likely(severity_output == CLI_SEVERITY_NONE))
631 return ci_putblk(chn, msg, strlen(msg));
632
633 tmp = get_trash_chunk();
634 chunk_reset(tmp);
635
636 if (severity < 0 || severity > 7) {
637 ha_warning("socket command feedback with invalid severity %d", severity);
638 chunk_printf(tmp, "[%d]: ", severity);
639 }
640 else {
641 switch (severity_output) {
642 case CLI_SEVERITY_NUMBER:
643 chunk_printf(tmp, "[%d]: ", severity);
644 break;
645 case CLI_SEVERITY_STRING:
646 chunk_printf(tmp, "[%s]: ", log_levels[severity]);
647 break;
648 default:
649 ha_warning("Unrecognized severity output %d", severity_output);
650 }
651 }
652 chunk_appendf(tmp, "%s", msg);
653
654 return ci_putblk(chn, tmp->area, strlen(tmp->area));
655 }
656
657 /* This I/O handler runs as an applet embedded in a stream interface. It is
658 * used to processes I/O from/to the stats unix socket. The system relies on a
659 * state machine handling requests and various responses. We read a request,
660 * then we process it and send the response, and we possibly display a prompt.
661 * Then we can read again. The state is stored in appctx->st0 and is one of the
662 * CLI_ST_* constants. appctx->st1 is used to indicate whether prompt is enabled
663 * or not.
664 */
cli_io_handler(struct appctx * appctx)665 static void cli_io_handler(struct appctx *appctx)
666 {
667 struct stream_interface *si = appctx->owner;
668 struct channel *req = si_oc(si);
669 struct channel *res = si_ic(si);
670 struct bind_conf *bind_conf = strm_li(si_strm(si))->bind_conf;
671 int reql;
672 int len;
673
674 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
675 goto out;
676
677 /* Check if the input buffer is available. */
678 if (res->buf.size == 0) {
679 /* buf.size==0 means we failed to get a buffer and were
680 * already subscribed to a wait list to get a buffer.
681 */
682 goto out;
683 }
684
685 while (1) {
686 if (appctx->st0 == CLI_ST_INIT) {
687 /* Stats output not initialized yet */
688 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
689 /* reset severity to default at init */
690 appctx->cli_severity_output = bind_conf->severity_output;
691 appctx->st0 = CLI_ST_GETREQ;
692 appctx->cli_level = bind_conf->level;
693 }
694 else if (appctx->st0 == CLI_ST_END) {
695 /* Let's close for real now. We just close the request
696 * side, the conditions below will complete if needed.
697 */
698 si_shutw(si);
699 free_trash_chunk(appctx->chunk);
700 appctx->chunk = NULL;
701 break;
702 }
703 else if (appctx->st0 == CLI_ST_GETREQ) {
704 char *str;
705
706 /* use a trash chunk to store received data */
707 if (!appctx->chunk) {
708 appctx->chunk = alloc_trash_chunk();
709 if (!appctx->chunk) {
710 appctx->st0 = CLI_ST_END;
711 continue;
712 }
713 }
714
715 str = appctx->chunk->area + appctx->chunk->data;
716
717 /* ensure we have some output room left in the event we
718 * would want to return some info right after parsing.
719 */
720 if (buffer_almost_full(si_ib(si))) {
721 si_rx_room_blk(si);
722 break;
723 }
724
725 /* '- 1' is to ensure a null byte can always be inserted at the end */
726 reql = co_getline(si_oc(si), str,
727 appctx->chunk->size - appctx->chunk->data - 1);
728 if (reql <= 0) { /* closed or EOL not found */
729 if (reql == 0)
730 break;
731 appctx->st0 = CLI_ST_END;
732 continue;
733 }
734
735 if (!(appctx->st1 & APPCTX_CLI_ST1_PAYLOAD)) {
736 /* seek for a possible unescaped semi-colon. If we find
737 * one, we replace it with an LF and skip only this part.
738 */
739 for (len = 0; len < reql; len++) {
740 if (str[len] == '\\') {
741 len++;
742 continue;
743 }
744 if (str[len] == ';') {
745 str[len] = '\n';
746 reql = len + 1;
747 break;
748 }
749 }
750 }
751
752 /* now it is time to check that we have a full line,
753 * remove the trailing \n and possibly \r, then cut the
754 * line.
755 */
756 len = reql - 1;
757 if (str[len] != '\n') {
758 appctx->st0 = CLI_ST_END;
759 continue;
760 }
761
762 if (len && str[len-1] == '\r')
763 len--;
764
765 str[len] = '\0';
766 appctx->chunk->data += len;
767
768 if (appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) {
769 appctx->chunk->area[appctx->chunk->data] = '\n';
770 appctx->chunk->area[appctx->chunk->data + 1] = 0;
771 appctx->chunk->data++;
772 }
773
774 appctx->st0 = CLI_ST_PROMPT;
775
776 if (appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) {
777 /* empty line */
778 if (!len) {
779 /* remove the last two \n */
780 appctx->chunk->data -= 2;
781 appctx->chunk->area[appctx->chunk->data] = 0;
782
783 if (!cli_parse_request(appctx))
784 cli_gen_usage_msg(appctx);
785
786 chunk_reset(appctx->chunk);
787 /* NB: cli_sock_parse_request() may have put
788 * another CLI_ST_O_* into appctx->st0.
789 */
790
791 appctx->st1 &= ~APPCTX_CLI_ST1_PAYLOAD;
792 }
793 }
794 else {
795 /*
796 * Look for the "payload start" pattern at the end of a line
797 * Its location is not remembered here, this is just to switch
798 * to a gathering mode.
799 */
800 if (strcmp(appctx->chunk->area + appctx->chunk->data - strlen(PAYLOAD_PATTERN), PAYLOAD_PATTERN) == 0) {
801 appctx->st1 |= APPCTX_CLI_ST1_PAYLOAD;
802 appctx->chunk->data++; // keep the trailing \0 after '<<'
803 }
804 else {
805 /* no payload, the command is complete: parse the request */
806 if (!cli_parse_request(appctx))
807 cli_gen_usage_msg(appctx);
808
809 chunk_reset(appctx->chunk);
810 }
811 }
812
813 /* re-adjust req buffer */
814 co_skip(si_oc(si), reql);
815 req->flags |= CF_READ_DONTWAIT; /* we plan to read small requests */
816 }
817 else { /* output functions */
818 const char *msg;
819 int sev;
820
821 switch (appctx->st0) {
822 case CLI_ST_PROMPT:
823 break;
824 case CLI_ST_PRINT: /* print const message in msg */
825 case CLI_ST_PRINT_ERR: /* print const error in msg */
826 case CLI_ST_PRINT_DYN: /* print dyn message in msg, free */
827 case CLI_ST_PRINT_FREE: /* print dyn error in err, free */
828 if (appctx->st0 == CLI_ST_PRINT || appctx->st0 == CLI_ST_PRINT_ERR) {
829 sev = appctx->st0 == CLI_ST_PRINT_ERR ?
830 LOG_ERR : appctx->ctx.cli.severity;
831 msg = appctx->ctx.cli.msg;
832 }
833 else if (appctx->st0 == CLI_ST_PRINT_DYN || appctx->st0 == CLI_ST_PRINT_FREE) {
834 sev = appctx->st0 == CLI_ST_PRINT_FREE ?
835 LOG_ERR : appctx->ctx.cli.severity;
836 msg = appctx->ctx.cli.err;
837 if (!msg) {
838 sev = LOG_ERR;
839 msg = "Out of memory.\n";
840 }
841 }
842 else {
843 sev = LOG_ERR;
844 msg = "Internal error.\n";
845 }
846
847 if (cli_output_msg(res, msg, sev, cli_get_severity_output(appctx)) != -1) {
848 if (appctx->st0 == CLI_ST_PRINT_FREE ||
849 appctx->st0 == CLI_ST_PRINT_DYN) {
850 free(appctx->ctx.cli.err);
851 appctx->ctx.cli.err = NULL;
852 }
853 appctx->st0 = CLI_ST_PROMPT;
854 }
855 else
856 si_rx_room_blk(si);
857 break;
858
859 case CLI_ST_CALLBACK: /* use custom pointer */
860 if (appctx->io_handler)
861 if (appctx->io_handler(appctx)) {
862 appctx->st0 = CLI_ST_PROMPT;
863 if (appctx->io_release) {
864 appctx->io_release(appctx);
865 appctx->io_release = NULL;
866 }
867 }
868 break;
869 default: /* abnormal state */
870 si->flags |= SI_FL_ERR;
871 break;
872 }
873
874 /* The post-command prompt is either LF alone or LF + '> ' in interactive mode */
875 if (appctx->st0 == CLI_ST_PROMPT) {
876 const char *prompt = "";
877
878 if (appctx->st1 & APPCTX_CLI_ST1_PROMPT) {
879 /*
880 * when entering a payload with interactive mode, change the prompt
881 * to emphasize that more data can still be sent
882 */
883 if (appctx->chunk->data && appctx->st1 & APPCTX_CLI_ST1_PAYLOAD)
884 prompt = "+ ";
885 else
886 prompt = "\n> ";
887 }
888 else {
889 if (!(appctx->st1 & (APPCTX_CLI_ST1_PAYLOAD|APPCTX_CLI_ST1_NOLF)))
890 prompt = "\n";
891 }
892
893 if (ci_putstr(si_ic(si), prompt) != -1)
894 appctx->st0 = CLI_ST_GETREQ;
895 else
896 si_rx_room_blk(si);
897 }
898
899 /* If the output functions are still there, it means they require more room. */
900 if (appctx->st0 >= CLI_ST_OUTPUT)
901 break;
902
903 /* Now we close the output if one of the writers did so,
904 * or if we're not in interactive mode and the request
905 * buffer is empty. This still allows pipelined requests
906 * to be sent in non-interactive mode.
907 */
908 if (((res->flags & (CF_SHUTW|CF_SHUTW_NOW))) ||
909 (!(appctx->st1 & APPCTX_CLI_ST1_PROMPT) && !co_data(req) && (!(appctx->st1 & APPCTX_CLI_ST1_PAYLOAD)))) {
910 appctx->st0 = CLI_ST_END;
911 continue;
912 }
913
914 /* switch state back to GETREQ to read next requests */
915 appctx->st0 = CLI_ST_GETREQ;
916 /* reactivate the \n at the end of the response for the next command */
917 appctx->st1 &= ~APPCTX_CLI_ST1_NOLF;
918 }
919 }
920
921 if ((res->flags & CF_SHUTR) && (si->state == SI_ST_EST)) {
922 DPRINTF(stderr, "%s@%d: si to buf closed. req=%08x, res=%08x, st=%d\n",
923 __FUNCTION__, __LINE__, req->flags, res->flags, si->state);
924 /* Other side has closed, let's abort if we have no more processing to do
925 * and nothing more to consume. This is comparable to a broken pipe, so
926 * we forward the close to the request side so that it flows upstream to
927 * the client.
928 */
929 si_shutw(si);
930 }
931
932 if ((req->flags & CF_SHUTW) && (si->state == SI_ST_EST) && (appctx->st0 < CLI_ST_OUTPUT)) {
933 DPRINTF(stderr, "%s@%d: buf to si closed. req=%08x, res=%08x, st=%d\n",
934 __FUNCTION__, __LINE__, req->flags, res->flags, si->state);
935 /* We have no more processing to do, and nothing more to send, and
936 * the client side has closed. So we'll forward this state downstream
937 * on the response buffer.
938 */
939 si_shutr(si);
940 res->flags |= CF_READ_NULL;
941 }
942
943 out:
944 DPRINTF(stderr, "%s@%d: st=%d, rqf=%x, rpf=%x, rqh=%lu, rqs=%lu, rh=%lu, rs=%lu\n",
945 __FUNCTION__, __LINE__,
946 si->state, req->flags, res->flags, ci_data(req), co_data(req), ci_data(res), co_data(res));
947 }
948
949 /* This is called when the stream interface is closed. For instance, upon an
950 * external abort, we won't call the i/o handler anymore so we may need to
951 * remove back references to the stream currently being dumped.
952 */
cli_release_handler(struct appctx * appctx)953 static void cli_release_handler(struct appctx *appctx)
954 {
955 free_trash_chunk(appctx->chunk);
956 appctx->chunk = NULL;
957
958 if (appctx->io_release) {
959 appctx->io_release(appctx);
960 appctx->io_release = NULL;
961 }
962 else if (appctx->st0 == CLI_ST_PRINT_FREE || appctx->st0 == CLI_ST_PRINT_DYN) {
963 free(appctx->ctx.cli.err);
964 appctx->ctx.cli.err = NULL;
965 }
966 }
967
968 /* This function dumps all environmnent variables to the buffer. It returns 0
969 * if the output buffer is full and it needs to be called again, otherwise
970 * non-zero. Dumps only one entry if st2 == STAT_ST_END. It uses cli.p0 as the
971 * pointer to the current variable.
972 */
cli_io_handler_show_env(struct appctx * appctx)973 static int cli_io_handler_show_env(struct appctx *appctx)
974 {
975 struct stream_interface *si = appctx->owner;
976 char **var = appctx->ctx.cli.p0;
977
978 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
979 return 1;
980
981 chunk_reset(&trash);
982
983 /* we have two inner loops here, one for the proxy, the other one for
984 * the buffer.
985 */
986 while (*var) {
987 chunk_printf(&trash, "%s\n", *var);
988
989 if (ci_putchk(si_ic(si), &trash) == -1) {
990 si_rx_room_blk(si);
991 return 0;
992 }
993 if (appctx->st2 == STAT_ST_END)
994 break;
995 var++;
996 appctx->ctx.cli.p0 = var;
997 }
998
999 /* dump complete */
1000 return 1;
1001 }
1002
1003 /* This function dumps all file descriptors states (or the requested one) to
1004 * the buffer. It returns 0 if the output buffer is full and it needs to be
1005 * called again, otherwise non-zero. Dumps only one entry if st2 == STAT_ST_END.
1006 * It uses cli.i0 as the fd number to restart from.
1007 */
cli_io_handler_show_fd(struct appctx * appctx)1008 static int cli_io_handler_show_fd(struct appctx *appctx)
1009 {
1010 struct stream_interface *si = appctx->owner;
1011 int fd = appctx->ctx.cli.i0;
1012 int ret = 1;
1013
1014 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
1015 goto end;
1016
1017 chunk_reset(&trash);
1018
1019 /* isolate the threads once per round. We're limited to a buffer worth
1020 * of output anyway, it cannot last very long.
1021 */
1022 thread_isolate();
1023
1024 /* we have two inner loops here, one for the proxy, the other one for
1025 * the buffer.
1026 */
1027 while (fd >= 0 && fd < global.maxsock) {
1028 struct fdtab fdt;
1029 const struct listener *li = NULL;
1030 const struct server *sv = NULL;
1031 const struct proxy *px = NULL;
1032 const struct connection *conn = NULL;
1033 const struct mux_ops *mux = NULL;
1034 const struct xprt_ops *xprt = NULL;
1035 const void *ctx = NULL;
1036 const void *xprt_ctx = NULL;
1037 uint32_t conn_flags = 0;
1038 int is_back = 0;
1039 int suspicious = 0;
1040
1041 fdt = fdtab[fd];
1042
1043 /* When DEBUG_FD is set, we also report closed FDs that have a
1044 * non-null event count to detect stuck ones.
1045 */
1046 if (!fdt.owner) {
1047 #ifdef DEBUG_FD
1048 if (!fdt.event_count)
1049 #endif
1050 goto skip; // closed
1051 }
1052 else if (fdt.iocb == conn_fd_handler) {
1053 conn = (const struct connection *)fdt.owner;
1054 conn_flags = conn->flags;
1055 mux = conn->mux;
1056 ctx = conn->ctx;
1057 xprt = conn->xprt;
1058 xprt_ctx = conn->xprt_ctx;
1059 li = objt_listener(conn->target);
1060 sv = objt_server(conn->target);
1061 px = objt_proxy(conn->target);
1062 is_back = conn_is_back(conn);
1063 if (atleast2(fdt.thread_mask))
1064 suspicious = 1;
1065 if (conn->handle.fd != fd)
1066 suspicious = 1;
1067 }
1068 else if (fdt.iocb == sock_accept_iocb)
1069 li = fdt.owner;
1070
1071 if (!fdt.thread_mask)
1072 suspicious = 1;
1073
1074 chunk_printf(&trash,
1075 " %5d : st=0x%02x(R:%c%c W:%c%c) ev=0x%02x(%c%c%c%c%c) [%c%c] tmask=0x%lx umask=0x%lx owner=%p iocb=%p(",
1076 fd,
1077 fdt.state,
1078 (fdt.state & FD_EV_READY_R) ? 'R' : 'r',
1079 (fdt.state & FD_EV_ACTIVE_R) ? 'A' : 'a',
1080 (fdt.state & FD_EV_READY_W) ? 'R' : 'r',
1081 (fdt.state & FD_EV_ACTIVE_W) ? 'A' : 'a',
1082 fdt.ev,
1083 (fdt.ev & FD_POLL_HUP) ? 'H' : 'h',
1084 (fdt.ev & FD_POLL_ERR) ? 'E' : 'e',
1085 (fdt.ev & FD_POLL_OUT) ? 'O' : 'o',
1086 (fdt.ev & FD_POLL_PRI) ? 'P' : 'p',
1087 (fdt.ev & FD_POLL_IN) ? 'I' : 'i',
1088 fdt.linger_risk ? 'L' : 'l',
1089 fdt.cloned ? 'C' : 'c',
1090 fdt.thread_mask, fdt.update_mask,
1091 fdt.owner,
1092 fdt.iocb);
1093 resolve_sym_name(&trash, NULL, fdt.iocb);
1094
1095 if (!fdt.owner) {
1096 chunk_appendf(&trash, ")");
1097 }
1098 else if (fdt.iocb == conn_fd_handler) {
1099 chunk_appendf(&trash, ") back=%d cflg=0x%08x", is_back, conn_flags);
1100
1101 if (conn->handle.fd != fd) {
1102 chunk_appendf(&trash, " fd=%d(BOGUS)", conn->handle.fd);
1103 suspicious = 1;
1104 } else {
1105 struct sockaddr_storage sa;
1106 socklen_t salen;
1107
1108 salen = sizeof(sa);
1109 if (getsockname(fd, (struct sockaddr *)&sa, &salen) != -1) {
1110 if (sa.ss_family == AF_INET)
1111 chunk_appendf(&trash, " fam=ipv4 lport=%d", ntohs(((const struct sockaddr_in *)&sa)->sin_port));
1112 else if (sa.ss_family == AF_INET6)
1113 chunk_appendf(&trash, " fam=ipv6 lport=%d", ntohs(((const struct sockaddr_in6 *)&sa)->sin6_port));
1114 else if (sa.ss_family == AF_UNIX)
1115 chunk_appendf(&trash, " fam=unix");
1116 }
1117
1118 salen = sizeof(sa);
1119 if (getpeername(fd, (struct sockaddr *)&sa, &salen) != -1) {
1120 if (sa.ss_family == AF_INET)
1121 chunk_appendf(&trash, " rport=%d", ntohs(((const struct sockaddr_in *)&sa)->sin_port));
1122 else if (sa.ss_family == AF_INET6)
1123 chunk_appendf(&trash, " rport=%d", ntohs(((const struct sockaddr_in6 *)&sa)->sin6_port));
1124 }
1125 }
1126
1127 if (px)
1128 chunk_appendf(&trash, " px=%s", px->id);
1129 else if (sv)
1130 chunk_appendf(&trash, " sv=%s/%s", sv->proxy->id, sv->id);
1131 else if (li)
1132 chunk_appendf(&trash, " fe=%s", li->bind_conf->frontend->id);
1133
1134 if (mux) {
1135 chunk_appendf(&trash, " mux=%s ctx=%p", mux->name, ctx);
1136 if (!ctx)
1137 suspicious = 1;
1138 if (mux->show_fd)
1139 suspicious |= mux->show_fd(&trash, fdt.owner);
1140 }
1141 else
1142 chunk_appendf(&trash, " nomux");
1143
1144 chunk_appendf(&trash, " xprt=%s", xprt ? xprt->name : "");
1145 if (xprt) {
1146 if (xprt_ctx || xprt->show_fd)
1147 chunk_appendf(&trash, " xprt_ctx=%p", xprt_ctx);
1148 if (xprt->show_fd)
1149 suspicious |= xprt->show_fd(&trash, conn, xprt_ctx);
1150 }
1151 }
1152 else if (fdt.iocb == sock_accept_iocb) {
1153 struct sockaddr_storage sa;
1154 socklen_t salen;
1155
1156 chunk_appendf(&trash, ") l.st=%s fe=%s",
1157 listener_state_str(li),
1158 li->bind_conf->frontend->id);
1159
1160 salen = sizeof(sa);
1161 if (getsockname(fd, (struct sockaddr *)&sa, &salen) != -1) {
1162 if (sa.ss_family == AF_INET)
1163 chunk_appendf(&trash, " fam=ipv4 lport=%d", ntohs(((const struct sockaddr_in *)&sa)->sin_port));
1164 else if (sa.ss_family == AF_INET6)
1165 chunk_appendf(&trash, " fam=ipv6 lport=%d", ntohs(((const struct sockaddr_in6 *)&sa)->sin6_port));
1166 else if (sa.ss_family == AF_UNIX)
1167 chunk_appendf(&trash, " fam=unix");
1168 }
1169 }
1170 else
1171 chunk_appendf(&trash, ")");
1172
1173 #ifdef DEBUG_FD
1174 chunk_appendf(&trash, " evcnt=%u", fdtab[fd].event_count);
1175 if (fdtab[fd].event_count >= 1000000)
1176 suspicious = 1;
1177 #endif
1178 chunk_appendf(&trash, "%s\n", suspicious ? " !" : "");
1179
1180 if (ci_putchk(si_ic(si), &trash) == -1) {
1181 si_rx_room_blk(si);
1182 appctx->ctx.cli.i0 = fd;
1183 ret = 0;
1184 break;
1185 }
1186 skip:
1187 if (appctx->st2 == STAT_ST_END)
1188 break;
1189
1190 fd++;
1191 }
1192
1193 end:
1194 /* dump complete */
1195
1196 thread_release();
1197 return ret;
1198 }
1199
1200 /* This function dumps some activity counters used by developers and support to
1201 * rule out some hypothesis during bug reports. It returns 0 if the output
1202 * buffer is full and it needs to be called again, otherwise non-zero. It dumps
1203 * everything at once in the buffer and is not designed to do it in multiple
1204 * passes.
1205 */
cli_io_handler_show_activity(struct appctx * appctx)1206 static int cli_io_handler_show_activity(struct appctx *appctx)
1207 {
1208 struct stream_interface *si = appctx->owner;
1209 int thr;
1210
1211 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
1212 return 1;
1213
1214 chunk_reset(&trash);
1215
1216 #undef SHOW_TOT
1217 #define SHOW_TOT(t, x) \
1218 do { \
1219 unsigned int _v[MAX_THREADS]; \
1220 unsigned int _tot; \
1221 const unsigned int _nbt = global.nbthread; \
1222 for (_tot = t = 0; t < _nbt; t++) \
1223 _tot += _v[t] = (x); \
1224 if (_nbt == 1) { \
1225 chunk_appendf(&trash, " %u\n", _tot); \
1226 break; \
1227 } \
1228 chunk_appendf(&trash, " %u [", _tot); \
1229 for (t = 0; t < _nbt; t++) \
1230 chunk_appendf(&trash, " %u", _v[t]); \
1231 chunk_appendf(&trash, " ]\n"); \
1232 } while (0)
1233
1234 #undef SHOW_AVG
1235 #define SHOW_AVG(t, x) \
1236 do { \
1237 unsigned int _v[MAX_THREADS]; \
1238 unsigned int _tot; \
1239 const unsigned int _nbt = global.nbthread; \
1240 for (_tot = t = 0; t < _nbt; t++) \
1241 _tot += _v[t] = (x); \
1242 if (_nbt == 1) { \
1243 chunk_appendf(&trash, " %u\n", _tot); \
1244 break; \
1245 } \
1246 chunk_appendf(&trash, " %u [", (_tot + _nbt/2) / _nbt); \
1247 for (t = 0; t < _nbt; t++) \
1248 chunk_appendf(&trash, " %u", _v[t]); \
1249 chunk_appendf(&trash, " ]\n"); \
1250 } while (0)
1251
1252 chunk_appendf(&trash, "thread_id: %u (%u..%u)\n", tid + 1, 1, global.nbthread);
1253 chunk_appendf(&trash, "date_now: %lu.%06lu\n", (long)now.tv_sec, (long)now.tv_usec);
1254 chunk_appendf(&trash, "ctxsw:"); SHOW_TOT(thr, activity[thr].ctxsw);
1255 chunk_appendf(&trash, "tasksw:"); SHOW_TOT(thr, activity[thr].tasksw);
1256 chunk_appendf(&trash, "empty_rq:"); SHOW_TOT(thr, activity[thr].empty_rq);
1257 chunk_appendf(&trash, "long_rq:"); SHOW_TOT(thr, activity[thr].long_rq);
1258 chunk_appendf(&trash, "loops:"); SHOW_TOT(thr, activity[thr].loops);
1259 chunk_appendf(&trash, "wake_tasks:"); SHOW_TOT(thr, activity[thr].wake_tasks);
1260 chunk_appendf(&trash, "wake_signal:"); SHOW_TOT(thr, activity[thr].wake_signal);
1261 chunk_appendf(&trash, "poll_io:"); SHOW_TOT(thr, activity[thr].poll_io);
1262 chunk_appendf(&trash, "poll_exp:"); SHOW_TOT(thr, activity[thr].poll_exp);
1263 chunk_appendf(&trash, "poll_drop_fd:"); SHOW_TOT(thr, activity[thr].poll_drop_fd);
1264 chunk_appendf(&trash, "poll_dead_fd:"); SHOW_TOT(thr, activity[thr].poll_dead_fd);
1265 chunk_appendf(&trash, "poll_skip_fd:"); SHOW_TOT(thr, activity[thr].poll_skip_fd);
1266 chunk_appendf(&trash, "conn_dead:"); SHOW_TOT(thr, activity[thr].conn_dead);
1267 chunk_appendf(&trash, "stream_calls:"); SHOW_TOT(thr, activity[thr].stream_calls);
1268 chunk_appendf(&trash, "pool_fail:"); SHOW_TOT(thr, activity[thr].pool_fail);
1269 chunk_appendf(&trash, "buf_wait:"); SHOW_TOT(thr, activity[thr].buf_wait);
1270 chunk_appendf(&trash, "cpust_ms_tot:"); SHOW_TOT(thr, activity[thr].cpust_total / 2);
1271 chunk_appendf(&trash, "cpust_ms_1s:"); SHOW_TOT(thr, read_freq_ctr(&activity[thr].cpust_1s) / 2);
1272 chunk_appendf(&trash, "cpust_ms_15s:"); SHOW_TOT(thr, read_freq_ctr_period(&activity[thr].cpust_15s, 15000) / 2);
1273 chunk_appendf(&trash, "avg_loop_us:"); SHOW_AVG(thr, swrate_avg(activity[thr].avg_loop_us, TIME_STATS_SAMPLES));
1274 chunk_appendf(&trash, "accepted:"); SHOW_TOT(thr, activity[thr].accepted);
1275 chunk_appendf(&trash, "accq_pushed:"); SHOW_TOT(thr, activity[thr].accq_pushed);
1276 chunk_appendf(&trash, "accq_full:"); SHOW_TOT(thr, activity[thr].accq_full);
1277 #ifdef USE_THREAD
1278 chunk_appendf(&trash, "accq_ring:"); SHOW_TOT(thr, (accept_queue_rings[thr].tail - accept_queue_rings[thr].head + ACCEPT_QUEUE_SIZE) % ACCEPT_QUEUE_SIZE);
1279 chunk_appendf(&trash, "fd_takeover:"); SHOW_TOT(thr, activity[thr].fd_takeover);
1280 #endif
1281
1282 #if defined(DEBUG_DEV)
1283 /* keep these ones at the end */
1284 chunk_appendf(&trash, "ctr0:"); SHOW_TOT(thr, activity[thr].ctr0);
1285 chunk_appendf(&trash, "ctr1:"); SHOW_TOT(thr, activity[thr].ctr1);
1286 chunk_appendf(&trash, "ctr2:"); SHOW_TOT(thr, activity[thr].ctr2);
1287 #endif
1288
1289 if (ci_putchk(si_ic(si), &trash) == -1) {
1290 chunk_reset(&trash);
1291 chunk_printf(&trash, "[output too large, cannot dump]\n");
1292 si_rx_room_blk(si);
1293 }
1294
1295 #undef SHOW_AVG
1296 #undef SHOW_TOT
1297 /* dump complete */
1298 return 1;
1299 }
1300
1301 /*
1302 * CLI IO handler for `show cli sockets`.
1303 * Uses ctx.cli.p0 to store the restart pointer.
1304 */
cli_io_handler_show_cli_sock(struct appctx * appctx)1305 static int cli_io_handler_show_cli_sock(struct appctx *appctx)
1306 {
1307 struct bind_conf *bind_conf;
1308 struct stream_interface *si = appctx->owner;
1309
1310 chunk_reset(&trash);
1311
1312 switch (appctx->st2) {
1313 case STAT_ST_INIT:
1314 chunk_printf(&trash, "# socket lvl processes\n");
1315 if (ci_putchk(si_ic(si), &trash) == -1) {
1316 si_rx_room_blk(si);
1317 return 0;
1318 }
1319 appctx->st2 = STAT_ST_LIST;
1320 /* fall through */
1321
1322 case STAT_ST_LIST:
1323 if (global.stats_fe) {
1324 list_for_each_entry(bind_conf, &global.stats_fe->conf.bind, by_fe) {
1325 struct listener *l;
1326
1327 /*
1328 * get the latest dumped node in appctx->ctx.cli.p0
1329 * if the current node is the first of the list
1330 */
1331
1332 if (appctx->ctx.cli.p0 &&
1333 &bind_conf->by_fe == (&global.stats_fe->conf.bind)->n) {
1334 /* change the current node to the latest dumped and continue the loop */
1335 bind_conf = LIST_ELEM(appctx->ctx.cli.p0, typeof(bind_conf), by_fe);
1336 continue;
1337 }
1338
1339 list_for_each_entry(l, &bind_conf->listeners, by_bind) {
1340
1341 char addr[46];
1342 char port[6];
1343
1344 if (l->rx.addr.ss_family == AF_UNIX) {
1345 const struct sockaddr_un *un;
1346
1347 un = (struct sockaddr_un *)&l->rx.addr;
1348 if (un->sun_path[0] == '\0') {
1349 chunk_appendf(&trash, "abns@%s ", un->sun_path+1);
1350 } else {
1351 chunk_appendf(&trash, "unix@%s ", un->sun_path);
1352 }
1353 } else if (l->rx.addr.ss_family == AF_INET) {
1354 addr_to_str(&l->rx.addr, addr, sizeof(addr));
1355 port_to_str(&l->rx.addr, port, sizeof(port));
1356 chunk_appendf(&trash, "ipv4@%s:%s ", addr, port);
1357 } else if (l->rx.addr.ss_family == AF_INET6) {
1358 addr_to_str(&l->rx.addr, addr, sizeof(addr));
1359 port_to_str(&l->rx.addr, port, sizeof(port));
1360 chunk_appendf(&trash, "ipv6@[%s]:%s ", addr, port);
1361 } else if (l->rx.addr.ss_family == AF_CUST_SOCKPAIR) {
1362 chunk_appendf(&trash, "sockpair@%d ", ((struct sockaddr_in *)&l->rx.addr)->sin_addr.s_addr);
1363 } else
1364 chunk_appendf(&trash, "unknown ");
1365
1366 if ((bind_conf->level & ACCESS_LVL_MASK) == ACCESS_LVL_ADMIN)
1367 chunk_appendf(&trash, "admin ");
1368 else if ((bind_conf->level & ACCESS_LVL_MASK) == ACCESS_LVL_OPER)
1369 chunk_appendf(&trash, "operator ");
1370 else if ((bind_conf->level & ACCESS_LVL_MASK) == ACCESS_LVL_USER)
1371 chunk_appendf(&trash, "user ");
1372 else
1373 chunk_appendf(&trash, " ");
1374
1375 if (bind_conf->settings.bind_proc != 0) {
1376 int pos;
1377 for (pos = 0; pos < 8 * sizeof(bind_conf->settings.bind_proc); pos++) {
1378 if (bind_conf->settings.bind_proc & (1UL << pos)) {
1379 chunk_appendf(&trash, "%d,", pos+1);
1380 }
1381 }
1382 /* replace the latest comma by a newline */
1383 trash.area[trash.data-1] = '\n';
1384
1385 } else {
1386 chunk_appendf(&trash, "all\n");
1387 }
1388
1389 if (ci_putchk(si_ic(si), &trash) == -1) {
1390 si_rx_room_blk(si);
1391 return 0;
1392 }
1393 }
1394 appctx->ctx.cli.p0 = &bind_conf->by_fe; /* store the latest list node dumped */
1395 }
1396 }
1397 /* fall through */
1398 default:
1399 appctx->st2 = STAT_ST_FIN;
1400 return 1;
1401 }
1402 }
1403
1404
1405 /* parse a "show env" CLI request. Returns 0 if it needs to continue, 1 if it
1406 * wants to stop here. It puts the variable to be dumped into cli.p0 if a single
1407 * variable is requested otherwise puts environ there.
1408 */
cli_parse_show_env(char ** args,char * payload,struct appctx * appctx,void * private)1409 static int cli_parse_show_env(char **args, char *payload, struct appctx *appctx, void *private)
1410 {
1411 extern char **environ;
1412 char **var;
1413
1414 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
1415 return 1;
1416
1417 var = environ;
1418
1419 if (*args[2]) {
1420 int len = strlen(args[2]);
1421
1422 for (; *var; var++) {
1423 if (strncmp(*var, args[2], len) == 0 &&
1424 (*var)[len] == '=')
1425 break;
1426 }
1427 if (!*var)
1428 return cli_err(appctx, "Variable not found\n");
1429
1430 appctx->st2 = STAT_ST_END;
1431 }
1432 appctx->ctx.cli.p0 = var;
1433 return 0;
1434 }
1435
1436 /* parse a "show fd" CLI request. Returns 0 if it needs to continue, 1 if it
1437 * wants to stop here. It puts the FD number into cli.i0 if a specific FD is
1438 * requested and sets st2 to STAT_ST_END, otherwise leaves 0 in i0.
1439 */
cli_parse_show_fd(char ** args,char * payload,struct appctx * appctx,void * private)1440 static int cli_parse_show_fd(char **args, char *payload, struct appctx *appctx, void *private)
1441 {
1442 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
1443 return 1;
1444
1445 appctx->ctx.cli.i0 = 0;
1446
1447 if (*args[2]) {
1448 appctx->ctx.cli.i0 = atoi(args[2]);
1449 appctx->st2 = STAT_ST_END;
1450 }
1451 return 0;
1452 }
1453
1454 /* parse a "set timeout" CLI request. It always returns 1. */
cli_parse_set_timeout(char ** args,char * payload,struct appctx * appctx,void * private)1455 static int cli_parse_set_timeout(char **args, char *payload, struct appctx *appctx, void *private)
1456 {
1457 struct stream_interface *si = appctx->owner;
1458 struct stream *s = si_strm(si);
1459
1460 if (strcmp(args[2], "cli") == 0) {
1461 unsigned timeout;
1462 const char *res;
1463
1464 if (!*args[3])
1465 return cli_err(appctx, "Expects an integer value.\n");
1466
1467 res = parse_time_err(args[3], &timeout, TIME_UNIT_S);
1468 if (res || timeout < 1)
1469 return cli_err(appctx, "Invalid timeout value.\n");
1470
1471 s->req.rto = s->res.wto = 1 + MS_TO_TICKS(timeout*1000);
1472 task_wakeup(s->task, TASK_WOKEN_MSG); // recompute timeouts
1473 return 1;
1474 }
1475
1476 return cli_err(appctx, "'set timeout' only supports 'cli'.\n");
1477 }
1478
1479 /* parse a "set maxconn global" command. It always returns 1. */
cli_parse_set_maxconn_global(char ** args,char * payload,struct appctx * appctx,void * private)1480 static int cli_parse_set_maxconn_global(char **args, char *payload, struct appctx *appctx, void *private)
1481 {
1482 int v;
1483
1484 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1485 return 1;
1486
1487 if (!*args[3])
1488 return cli_err(appctx, "Expects an integer value.\n");
1489
1490 v = atoi(args[3]);
1491 if (v > global.hardmaxconn)
1492 return cli_err(appctx, "Value out of range.\n");
1493
1494 /* check for unlimited values */
1495 if (v <= 0)
1496 v = global.hardmaxconn;
1497
1498 global.maxconn = v;
1499
1500 /* Dequeues all of the listeners waiting for a resource */
1501 dequeue_all_listeners();
1502
1503 return 1;
1504 }
1505
set_severity_output(int * target,char * argument)1506 static int set_severity_output(int *target, char *argument)
1507 {
1508 if (!strcmp(argument, "none")) {
1509 *target = CLI_SEVERITY_NONE;
1510 return 1;
1511 }
1512 else if (!strcmp(argument, "number")) {
1513 *target = CLI_SEVERITY_NUMBER;
1514 return 1;
1515 }
1516 else if (!strcmp(argument, "string")) {
1517 *target = CLI_SEVERITY_STRING;
1518 return 1;
1519 }
1520 return 0;
1521 }
1522
1523 /* parse a "set severity-output" command. */
cli_parse_set_severity_output(char ** args,char * payload,struct appctx * appctx,void * private)1524 static int cli_parse_set_severity_output(char **args, char *payload, struct appctx *appctx, void *private)
1525 {
1526 if (*args[2] && set_severity_output(&appctx->cli_severity_output, args[2]))
1527 return 0;
1528
1529 return cli_err(appctx, "one of 'none', 'number', 'string' is a required argument\n");
1530 }
1531
1532
1533 /* show the level of the current CLI session */
cli_parse_show_lvl(char ** args,char * payload,struct appctx * appctx,void * private)1534 static int cli_parse_show_lvl(char **args, char *payload, struct appctx *appctx, void *private)
1535 {
1536 if ((appctx->cli_level & ACCESS_LVL_MASK) == ACCESS_LVL_ADMIN)
1537 return cli_msg(appctx, LOG_INFO, "admin\n");
1538 else if ((appctx->cli_level & ACCESS_LVL_MASK) == ACCESS_LVL_OPER)
1539 return cli_msg(appctx, LOG_INFO, "operator\n");
1540 else if ((appctx->cli_level & ACCESS_LVL_MASK) == ACCESS_LVL_USER)
1541 return cli_msg(appctx, LOG_INFO, "user\n");
1542 else
1543 return cli_msg(appctx, LOG_INFO, "unknown\n");
1544 }
1545
1546 /* parse and set the CLI level dynamically */
cli_parse_set_lvl(char ** args,char * payload,struct appctx * appctx,void * private)1547 static int cli_parse_set_lvl(char **args, char *payload, struct appctx *appctx, void *private)
1548 {
1549 /* this will ask the applet to not output a \n after the command */
1550 if (!strcmp(args[1], "-"))
1551 appctx->st1 |= APPCTX_CLI_ST1_NOLF;
1552
1553 if (!strcmp(args[0], "operator")) {
1554 if (!cli_has_level(appctx, ACCESS_LVL_OPER)) {
1555 return 1;
1556 }
1557 appctx->cli_level &= ~ACCESS_LVL_MASK;
1558 appctx->cli_level |= ACCESS_LVL_OPER;
1559
1560 } else if (!strcmp(args[0], "user")) {
1561 if (!cli_has_level(appctx, ACCESS_LVL_USER)) {
1562 return 1;
1563 }
1564 appctx->cli_level &= ~ACCESS_LVL_MASK;
1565 appctx->cli_level |= ACCESS_LVL_USER;
1566 }
1567 appctx->cli_level &= ~ACCESS_EXPERT;
1568 return 1;
1569 }
1570
1571
1572 /* parse and set the CLI expert-mode dynamically */
cli_parse_expert_mode(char ** args,char * payload,struct appctx * appctx,void * private)1573 static int cli_parse_expert_mode(char **args, char *payload, struct appctx *appctx, void *private)
1574 {
1575 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1576 return 1;
1577
1578 if (!*args[1])
1579 return (appctx->cli_level & ACCESS_EXPERT)
1580 ? cli_msg(appctx, LOG_INFO, "expert-mode is ON\n")
1581 : cli_msg(appctx, LOG_INFO, "expert-mode is OFF\n");
1582
1583 appctx->cli_level &= ~ACCESS_EXPERT;
1584 if (strcmp(args[1], "on") == 0)
1585 appctx->cli_level |= ACCESS_EXPERT;
1586 return 1;
1587 }
1588
1589
cli_parse_default(char ** args,char * payload,struct appctx * appctx,void * private)1590 int cli_parse_default(char **args, char *payload, struct appctx *appctx, void *private)
1591 {
1592 return 0;
1593 }
1594
1595 /* parse a "set rate-limit" command. It always returns 1. */
cli_parse_set_ratelimit(char ** args,char * payload,struct appctx * appctx,void * private)1596 static int cli_parse_set_ratelimit(char **args, char *payload, struct appctx *appctx, void *private)
1597 {
1598 int v;
1599 int *res;
1600 int mul = 1;
1601
1602 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1603 return 1;
1604
1605 if (strcmp(args[2], "connections") == 0 && strcmp(args[3], "global") == 0)
1606 res = &global.cps_lim;
1607 else if (strcmp(args[2], "sessions") == 0 && strcmp(args[3], "global") == 0)
1608 res = &global.sps_lim;
1609 #ifdef USE_OPENSSL
1610 else if (strcmp(args[2], "ssl-sessions") == 0 && strcmp(args[3], "global") == 0)
1611 res = &global.ssl_lim;
1612 #endif
1613 else if (strcmp(args[2], "http-compression") == 0 && strcmp(args[3], "global") == 0) {
1614 res = &global.comp_rate_lim;
1615 mul = 1024;
1616 }
1617 else {
1618 return cli_err(appctx,
1619 "'set rate-limit' only supports :\n"
1620 " - 'connections global' to set the per-process maximum connection rate\n"
1621 " - 'sessions global' to set the per-process maximum session rate\n"
1622 #ifdef USE_OPENSSL
1623 " - 'ssl-sessions global' to set the per-process maximum SSL session rate\n"
1624 #endif
1625 " - 'http-compression global' to set the per-process maximum compression speed in kB/s\n");
1626 }
1627
1628 if (!*args[4])
1629 return cli_err(appctx, "Expects an integer value.\n");
1630
1631 v = atoi(args[4]);
1632 if (v < 0)
1633 return cli_err(appctx, "Value out of range.\n");
1634
1635 *res = v * mul;
1636
1637 /* Dequeues all of the listeners waiting for a resource */
1638 dequeue_all_listeners();
1639
1640 return 1;
1641 }
1642
1643 /* parse the "expose-fd" argument on the bind lines */
bind_parse_expose_fd(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1644 static int bind_parse_expose_fd(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1645 {
1646 if (!*args[cur_arg + 1]) {
1647 memprintf(err, "'%s' : missing fd type", args[cur_arg]);
1648 return ERR_ALERT | ERR_FATAL;
1649 }
1650 if (!strcmp(args[cur_arg+1], "listeners")) {
1651 conf->level |= ACCESS_FD_LISTENERS;
1652 } else {
1653 memprintf(err, "'%s' only supports 'listeners' (got '%s')",
1654 args[cur_arg], args[cur_arg+1]);
1655 return ERR_ALERT | ERR_FATAL;
1656 }
1657
1658 return 0;
1659 }
1660
1661 /* parse the "level" argument on the bind lines */
bind_parse_level(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1662 static int bind_parse_level(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1663 {
1664 if (!*args[cur_arg + 1]) {
1665 memprintf(err, "'%s' : missing level", args[cur_arg]);
1666 return ERR_ALERT | ERR_FATAL;
1667 }
1668
1669 if (!strcmp(args[cur_arg+1], "user")) {
1670 conf->level &= ~ACCESS_LVL_MASK;
1671 conf->level |= ACCESS_LVL_USER;
1672 } else if (!strcmp(args[cur_arg+1], "operator")) {
1673 conf->level &= ~ACCESS_LVL_MASK;
1674 conf->level |= ACCESS_LVL_OPER;
1675 } else if (!strcmp(args[cur_arg+1], "admin")) {
1676 conf->level &= ~ACCESS_LVL_MASK;
1677 conf->level |= ACCESS_LVL_ADMIN;
1678 } else {
1679 memprintf(err, "'%s' only supports 'user', 'operator', and 'admin' (got '%s')",
1680 args[cur_arg], args[cur_arg+1]);
1681 return ERR_ALERT | ERR_FATAL;
1682 }
1683
1684 return 0;
1685 }
1686
bind_parse_severity_output(char ** args,int cur_arg,struct proxy * px,struct bind_conf * conf,char ** err)1687 static int bind_parse_severity_output(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
1688 {
1689 if (!*args[cur_arg + 1]) {
1690 memprintf(err, "'%s' : missing severity format", args[cur_arg]);
1691 return ERR_ALERT | ERR_FATAL;
1692 }
1693
1694 if (set_severity_output(&conf->severity_output, args[cur_arg+1]))
1695 return 0;
1696 else {
1697 memprintf(err, "'%s' only supports 'none', 'number', and 'string' (got '%s')",
1698 args[cur_arg], args[cur_arg+1]);
1699 return ERR_ALERT | ERR_FATAL;
1700 }
1701 }
1702
1703 /* Send all the bound sockets, always returns 1 */
_getsocks(char ** args,char * payload,struct appctx * appctx,void * private)1704 static int _getsocks(char **args, char *payload, struct appctx *appctx, void *private)
1705 {
1706 char *cmsgbuf = NULL;
1707 unsigned char *tmpbuf = NULL;
1708 struct cmsghdr *cmsg;
1709 struct stream_interface *si = appctx->owner;
1710 struct stream *s = si_strm(si);
1711 struct connection *remote = cs_conn(objt_cs(si_opposite(si)->end));
1712 struct msghdr msghdr;
1713 struct iovec iov;
1714 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
1715 const char *ns_name, *if_name;
1716 unsigned char ns_nlen, if_nlen;
1717 int nb_queued;
1718 int cur_fd = 0;
1719 int *tmpfd;
1720 int tot_fd_nb = 0;
1721 int fd = -1;
1722 int curoff = 0;
1723 int old_fcntl = -1;
1724 int ret;
1725
1726 if (!remote) {
1727 ha_warning("Only works on real connections\n");
1728 goto out;
1729 }
1730
1731 fd = remote->handle.fd;
1732
1733 /* Temporary set the FD in blocking mode, that will make our life easier */
1734 old_fcntl = fcntl(fd, F_GETFL);
1735 if (old_fcntl < 0) {
1736 ha_warning("Couldn't get the flags for the unix socket\n");
1737 goto out;
1738 }
1739 cmsgbuf = malloc(CMSG_SPACE(sizeof(int) * MAX_SEND_FD));
1740 if (!cmsgbuf) {
1741 ha_warning("Failed to allocate memory to send sockets\n");
1742 goto out;
1743 }
1744 if (fcntl(fd, F_SETFL, old_fcntl &~ O_NONBLOCK) == -1) {
1745 ha_warning("Cannot make the unix socket blocking\n");
1746 goto out;
1747 }
1748 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, sizeof(tv));
1749 iov.iov_base = &tot_fd_nb;
1750 iov.iov_len = sizeof(tot_fd_nb);
1751 if (!(strm_li(s)->bind_conf->level & ACCESS_FD_LISTENERS))
1752 goto out;
1753 memset(&msghdr, 0, sizeof(msghdr));
1754 /*
1755 * First, calculates the total number of FD, so that we can let
1756 * the caller know how much it should expect.
1757 */
1758 for (cur_fd = 0;cur_fd < global.maxsock; cur_fd++)
1759 tot_fd_nb += fdtab[cur_fd].exported;
1760
1761 if (tot_fd_nb == 0)
1762 goto out;
1763
1764 /* First send the total number of file descriptors, so that the
1765 * receiving end knows what to expect.
1766 */
1767 msghdr.msg_iov = &iov;
1768 msghdr.msg_iovlen = 1;
1769 ret = sendmsg(fd, &msghdr, 0);
1770 if (ret != sizeof(tot_fd_nb)) {
1771 ha_warning("Failed to send the number of sockets to send\n");
1772 goto out;
1773 }
1774
1775 /* Now send the fds */
1776 msghdr.msg_control = cmsgbuf;
1777 msghdr.msg_controllen = CMSG_SPACE(sizeof(int) * MAX_SEND_FD);
1778 cmsg = CMSG_FIRSTHDR(&msghdr);
1779 cmsg->cmsg_len = CMSG_LEN(MAX_SEND_FD * sizeof(int));
1780 cmsg->cmsg_level = SOL_SOCKET;
1781 cmsg->cmsg_type = SCM_RIGHTS;
1782 tmpfd = (int *)CMSG_DATA(cmsg);
1783
1784 /* For each socket, e message is sent, containing the following :
1785 * Size of the namespace name (or 0 if none), as an unsigned char.
1786 * The namespace name, if any
1787 * Size of the interface name (or 0 if none), as an unsigned char
1788 * The interface name, if any
1789 * 32 bits of zeroes (used to be listener options).
1790 */
1791 /* We will send sockets MAX_SEND_FD per MAX_SEND_FD, allocate a
1792 * buffer big enough to store the socket information.
1793 */
1794 tmpbuf = malloc(MAX_SEND_FD * (1 + MAXPATHLEN + 1 + IFNAMSIZ + sizeof(int)));
1795 if (tmpbuf == NULL) {
1796 ha_warning("Failed to allocate memory to transfer socket information\n");
1797 goto out;
1798 }
1799
1800 nb_queued = 0;
1801 iov.iov_base = tmpbuf;
1802 for (cur_fd = 0; cur_fd < global.maxsock; cur_fd++) {
1803 if (!(fdtab[cur_fd].exported))
1804 continue;
1805
1806 ns_name = if_name = "";
1807 ns_nlen = if_nlen = 0;
1808
1809 /* for now we can only retrieve namespaces and interfaces from
1810 * pure listeners.
1811 */
1812 if (fdtab[cur_fd].iocb == sock_accept_iocb) {
1813 const struct listener *l = fdtab[cur_fd].owner;
1814
1815 if (l->rx.settings->interface) {
1816 if_name = l->rx.settings->interface;
1817 if_nlen = strlen(if_name);
1818 }
1819
1820 #ifdef USE_NS
1821 if (l->rx.settings->netns) {
1822 ns_name = l->rx.settings->netns->node.key;
1823 ns_nlen = l->rx.settings->netns->name_len;
1824 }
1825 #endif
1826 }
1827
1828 /* put the FD into the CMSG_DATA */
1829 tmpfd[nb_queued++] = cur_fd;
1830
1831 /* first block is <ns_name_len> <ns_name> */
1832 tmpbuf[curoff++] = ns_nlen;
1833 if (ns_nlen)
1834 memcpy(tmpbuf + curoff, ns_name, ns_nlen);
1835 curoff += ns_nlen;
1836
1837 /* second block is <if_name_len> <if_name> */
1838 tmpbuf[curoff++] = if_nlen;
1839 if (if_nlen)
1840 memcpy(tmpbuf + curoff, if_name, if_nlen);
1841 curoff += if_nlen;
1842
1843 /* we used to send the listener options here before 2.3 */
1844 memset(tmpbuf + curoff, 0, sizeof(int));
1845 curoff += sizeof(int);
1846
1847 /* there's a limit to how many FDs may be sent at once */
1848 if (nb_queued == MAX_SEND_FD) {
1849 iov.iov_len = curoff;
1850 if (sendmsg(fd, &msghdr, 0) != curoff) {
1851 ha_warning("Failed to transfer sockets\n");
1852 return -1;
1853 }
1854
1855 /* Wait for an ack */
1856 do {
1857 ret = recv(fd, &tot_fd_nb, sizeof(tot_fd_nb), 0);
1858 } while (ret == -1 && errno == EINTR);
1859
1860 if (ret <= 0) {
1861 ha_warning("Unexpected error while transferring sockets\n");
1862 return -1;
1863 }
1864 curoff = 0;
1865 nb_queued = 0;
1866 }
1867 }
1868
1869 /* flush pending stuff */
1870 if (nb_queued) {
1871 iov.iov_len = curoff;
1872 cmsg->cmsg_len = CMSG_LEN(nb_queued * sizeof(int));
1873 msghdr.msg_controllen = CMSG_SPACE(nb_queued * sizeof(int));
1874 if (sendmsg(fd, &msghdr, 0) != curoff) {
1875 ha_warning("Failed to transfer sockets\n");
1876 goto out;
1877 }
1878 }
1879
1880 out:
1881 if (fd >= 0 && old_fcntl >= 0 && fcntl(fd, F_SETFL, old_fcntl) == -1) {
1882 ha_warning("Cannot make the unix socket non-blocking\n");
1883 goto out;
1884 }
1885 appctx->st0 = CLI_ST_END;
1886 free(cmsgbuf);
1887 free(tmpbuf);
1888 return 1;
1889 }
1890
cli_parse_simple(char ** args,char * payload,struct appctx * appctx,void * private)1891 static int cli_parse_simple(char **args, char *payload, struct appctx *appctx, void *private)
1892 {
1893 if (*args[0] == 'h')
1894 /* help */
1895 cli_gen_usage_msg(appctx);
1896 else if (*args[0] == 'p')
1897 /* prompt */
1898 appctx->st1 ^= APPCTX_CLI_ST1_PROMPT;
1899 else if (*args[0] == 'q')
1900 /* quit */
1901 appctx->st0 = CLI_ST_END;
1902
1903 return 1;
1904 }
1905
pcli_write_prompt(struct stream * s)1906 void pcli_write_prompt(struct stream *s)
1907 {
1908 struct buffer *msg = get_trash_chunk();
1909 struct channel *oc = si_oc(&s->si[0]);
1910
1911 if (!(s->pcli_flags & PCLI_F_PROMPT))
1912 return;
1913
1914 if (s->pcli_flags & PCLI_F_PAYLOAD) {
1915 chunk_appendf(msg, "+ ");
1916 } else {
1917 if (s->pcli_next_pid == 0)
1918 chunk_appendf(msg, "master%s> ",
1919 (global.mode & MODE_MWORKER_WAIT) ? "[ReloadFailed]" : "");
1920 else
1921 chunk_appendf(msg, "%d> ", s->pcli_next_pid);
1922 }
1923 co_inject(oc, msg->area, msg->data);
1924 }
1925
1926
1927 /* The pcli_* functions are used for the CLI proxy in the master */
1928
pcli_reply_and_close(struct stream * s,const char * msg)1929 void pcli_reply_and_close(struct stream *s, const char *msg)
1930 {
1931 struct buffer *buf = get_trash_chunk();
1932
1933 chunk_initstr(buf, msg);
1934 si_retnclose(&s->si[0], buf);
1935 }
1936
pcli_pid_to_server(int proc_pid)1937 static enum obj_type *pcli_pid_to_server(int proc_pid)
1938 {
1939 struct mworker_proc *child;
1940
1941 /* return the mCLI applet of the master */
1942 if (proc_pid == 0)
1943 return &mcli_applet.obj_type;
1944
1945 list_for_each_entry(child, &proc_list, list) {
1946 if (child->pid == proc_pid){
1947 return &child->srv->obj_type;
1948 }
1949 }
1950 return NULL;
1951 }
1952
1953 /* Take a CLI prefix in argument (eg: @!1234 @master @1)
1954 * Return:
1955 * 0: master
1956 * > 0: pid of a worker
1957 * < 0: didn't find a worker
1958 */
pcli_prefix_to_pid(const char * prefix)1959 static int pcli_prefix_to_pid(const char *prefix)
1960 {
1961 int proc_pid;
1962 struct mworker_proc *child;
1963 char *errtol = NULL;
1964
1965 if (*prefix != '@') /* not a prefix, should not happen */
1966 return -1;
1967
1968 prefix++;
1969 if (!*prefix) /* sent @ alone, return the master */
1970 return 0;
1971
1972 if (strcmp("master", prefix) == 0) {
1973 return 0;
1974 } else if (*prefix == '!') {
1975 prefix++;
1976 if (!*prefix)
1977 return -1;
1978
1979 proc_pid = strtol(prefix, &errtol, 10);
1980 if (*errtol != '\0')
1981 return -1;
1982 list_for_each_entry(child, &proc_list, list) {
1983 if (!(child->options & PROC_O_TYPE_WORKER))
1984 continue;
1985 if (child->pid == proc_pid){
1986 return child->pid;
1987 }
1988 }
1989 } else {
1990 struct mworker_proc *chosen = NULL;
1991 /* this is a relative pid */
1992
1993 proc_pid = strtol(prefix, &errtol, 10);
1994 if (*errtol != '\0')
1995 return -1;
1996
1997 if (proc_pid == 0) /* return the master */
1998 return 0;
1999
2000 /* chose the right process, the current one is the one with the
2001 least number of reloads */
2002 list_for_each_entry(child, &proc_list, list) {
2003 if (!(child->options & PROC_O_TYPE_WORKER))
2004 continue;
2005 if (child->relative_pid == proc_pid){
2006 if (child->reloads == 0)
2007 return child->pid;
2008 else if (chosen == NULL || child->reloads < chosen->reloads)
2009 chosen = child;
2010 }
2011 }
2012 if (chosen)
2013 return chosen->pid;
2014 }
2015 return -1;
2016 }
2017
2018 /* Return::
2019 * >= 0 : number of words to escape
2020 * = -1 : error
2021 */
2022
pcli_find_and_exec_kw(struct stream * s,char ** args,int argl,char ** errmsg,int * next_pid)2023 int pcli_find_and_exec_kw(struct stream *s, char **args, int argl, char **errmsg, int *next_pid)
2024 {
2025 if (argl < 1)
2026 return 0;
2027
2028 /* there is a prefix */
2029 if (args[0][0] == '@') {
2030 int target_pid = pcli_prefix_to_pid(args[0]);
2031
2032 if (target_pid == -1) {
2033 memprintf(errmsg, "Can't find the target PID matching the prefix '%s'\n", args[0]);
2034 return -1;
2035 }
2036
2037 /* if the prefix is alone, define a default target */
2038 if (argl == 1)
2039 s->pcli_next_pid = target_pid;
2040 else
2041 *next_pid = target_pid;
2042 return 1;
2043 } else if (!strcmp("prompt", args[0])) {
2044 s->pcli_flags ^= PCLI_F_PROMPT;
2045 return argl; /* return the number of elements in the array */
2046
2047 } else if (!strcmp("quit", args[0])) {
2048 channel_shutr_now(&s->req);
2049 channel_shutw_now(&s->res);
2050 return argl; /* return the number of elements in the array */
2051 } else if (!strcmp(args[0], "operator")) {
2052 if (!pcli_has_level(s, ACCESS_LVL_OPER)) {
2053 memprintf(errmsg, "Permission denied!\n");
2054 return -1;
2055 }
2056 s->pcli_flags &= ~ACCESS_LVL_MASK;
2057 s->pcli_flags |= ACCESS_LVL_OPER;
2058 return argl;
2059
2060 } else if (!strcmp(args[0], "user")) {
2061 if (!pcli_has_level(s, ACCESS_LVL_USER)) {
2062 memprintf(errmsg, "Permission denied!\n");
2063 return -1;
2064 }
2065 s->pcli_flags &= ~ACCESS_LVL_MASK;
2066 s->pcli_flags |= ACCESS_LVL_USER;
2067 return argl;
2068 }
2069
2070 return 0;
2071 }
2072
2073 /*
2074 * Parse the CLI request:
2075 * - It does basically the same as the cli_io_handler, but as a proxy
2076 * - It can exec a command and strip non forwardable commands
2077 *
2078 * Return:
2079 * - the number of characters to forward or
2080 * - 1 if there is an error or not enough data
2081 */
pcli_parse_request(struct stream * s,struct channel * req,char ** errmsg,int * next_pid)2082 int pcli_parse_request(struct stream *s, struct channel *req, char **errmsg, int *next_pid)
2083 {
2084 char *str = (char *)ci_head(req);
2085 char *end = (char *)ci_stop(req);
2086 char *args[MAX_STATS_ARGS + 1]; /* +1 for storing a NULL */
2087 int argl; /* number of args */
2088 char *p;
2089 char *trim = NULL;
2090 char *payload = NULL;
2091 int wtrim = 0; /* number of words to trim */
2092 int reql = 0;
2093 int ret;
2094 int i = 0;
2095
2096 p = str;
2097
2098 if (!(s->pcli_flags & PCLI_F_PAYLOAD)) {
2099
2100 /* Looks for the end of one command */
2101 while (p+reql < end) {
2102 /* handle escaping */
2103 if (p[reql] == '\\') {
2104 reql+=2;
2105 continue;
2106 }
2107 if (p[reql] == ';' || p[reql] == '\n') {
2108 /* found the end of the command */
2109 p[reql] = '\n';
2110 reql++;
2111 break;
2112 }
2113 reql++;
2114 }
2115 } else {
2116 while (p+reql < end) {
2117 if (p[reql] == '\n') {
2118 /* found the end of the line */
2119 reql++;
2120 break;
2121 }
2122 reql++;
2123 }
2124 }
2125
2126 /* set end to first byte after the end of the command */
2127 end = p + reql;
2128
2129 /* there is no end to this command, need more to parse ! */
2130 if (*(end-1) != '\n') {
2131 return -1;
2132 }
2133
2134 if (s->pcli_flags & PCLI_F_PAYLOAD) {
2135 if (reql == 1) /* last line of the payload */
2136 s->pcli_flags &= ~PCLI_F_PAYLOAD;
2137 return reql;
2138 }
2139
2140 *(end-1) = '\0';
2141
2142 /* splits the command in words */
2143 while (i < MAX_STATS_ARGS && p < end) {
2144 /* skip leading spaces/tabs */
2145 p += strspn(p, " \t");
2146 if (!*p)
2147 break;
2148
2149 args[i] = p;
2150 while (1) {
2151 p += strcspn(p, " \t\\");
2152 /* escaped chars using backlashes (\) */
2153 if (*p == '\\') {
2154 if (!*++p)
2155 break;
2156 if (!*++p)
2157 break;
2158 } else {
2159 break;
2160 }
2161 }
2162 *p++ = 0;
2163 i++;
2164 }
2165
2166 argl = i;
2167
2168 for (; i < MAX_STATS_ARGS + 1; i++)
2169 args[i] = NULL;
2170
2171 wtrim = pcli_find_and_exec_kw(s, args, argl, errmsg, next_pid);
2172
2173 /* End of words are ending by \0, we need to replace the \0s by spaces
2174 1 before forwarding them */
2175 p = str;
2176 while (p < end-1) {
2177 if (*p == '\0')
2178 *p = ' ';
2179 p++;
2180 }
2181
2182 payload = strstr(str, PAYLOAD_PATTERN);
2183 if ((end - 1) == (payload + strlen(PAYLOAD_PATTERN))) {
2184 /* if the payload pattern is at the end */
2185 s->pcli_flags |= PCLI_F_PAYLOAD;
2186 ret = reql;
2187 }
2188
2189 *(end-1) = '\n';
2190
2191 if (wtrim > 0) {
2192 trim = &args[wtrim][0];
2193 if (trim == NULL) /* if this was the last word in the table */
2194 trim = end;
2195
2196 b_del(&req->buf, trim - str);
2197
2198 ret = end - trim;
2199 } else if (wtrim < 0) {
2200 /* parsing error */
2201 return -1;
2202 } else {
2203 /* the whole string */
2204 ret = end - str;
2205 }
2206
2207 if (ret > 1) {
2208 if (pcli_has_level(s, ACCESS_LVL_ADMIN)) {
2209 goto end;
2210 } else if (pcli_has_level(s, ACCESS_LVL_OPER)) {
2211 ci_insert_line2(req, 0, "operator -", strlen("operator -"));
2212 ret += strlen("operator -") + 2;
2213 } else if (pcli_has_level(s, ACCESS_LVL_USER)) {
2214 ci_insert_line2(req, 0, "user -", strlen("user -"));
2215 ret += strlen("user -") + 2;
2216 }
2217 }
2218 end:
2219
2220 return ret;
2221 }
2222
pcli_wait_for_request(struct stream * s,struct channel * req,int an_bit)2223 int pcli_wait_for_request(struct stream *s, struct channel *req, int an_bit)
2224 {
2225 int next_pid = -1;
2226 int to_forward;
2227 char *errmsg = NULL;
2228
2229 if ((s->pcli_flags & ACCESS_LVL_MASK) == ACCESS_LVL_NONE)
2230 s->pcli_flags |= strm_li(s)->bind_conf->level & ACCESS_LVL_MASK;
2231
2232 read_again:
2233 /* if the channel is closed for read, we won't receive any more data
2234 from the client, but we don't want to forward this close to the
2235 server */
2236 channel_dont_close(req);
2237
2238 /* We don't know yet to which server we will connect */
2239 channel_dont_connect(req);
2240
2241
2242 /* we are not waiting for a response, there is no more request and we
2243 * receive a close from the client, we can leave */
2244 if (!(ci_data(req)) && req->flags & CF_SHUTR) {
2245 channel_shutw_now(&s->res);
2246 s->req.analysers &= ~AN_REQ_WAIT_CLI;
2247 return 1;
2248 }
2249
2250 req->flags |= CF_READ_DONTWAIT;
2251
2252 /* need more data */
2253 if (!ci_data(req))
2254 return 0;
2255
2256 /* If there is data available for analysis, log the end of the idle time. */
2257 if (c_data(req) && s->logs.t_idle == -1)
2258 s->logs.t_idle = tv_ms_elapsed(&s->logs.tv_accept, &now) - s->logs.t_handshake;
2259
2260 to_forward = pcli_parse_request(s, req, &errmsg, &next_pid);
2261 if (to_forward > 0) {
2262 int target_pid;
2263 /* enough data */
2264
2265 /* forward only 1 command */
2266 channel_forward(req, to_forward);
2267
2268 if (!(s->pcli_flags & PCLI_F_PAYLOAD)) {
2269 /* we send only 1 command per request, and we write close after it */
2270 channel_shutw_now(req);
2271 } else {
2272 pcli_write_prompt(s);
2273 }
2274
2275 s->res.flags |= CF_WAKE_ONCE; /* need to be called again */
2276
2277 /* remove the XFER_DATA analysers, which forwards all
2278 * the data, we don't want to forward the next requests
2279 * We need to add CF_FLT_ANALYZE to abort the forward too.
2280 */
2281 req->analysers &= ~(AN_REQ_FLT_XFER_DATA|AN_REQ_WAIT_CLI);
2282 req->analysers |= AN_REQ_FLT_END|CF_FLT_ANALYZE;
2283 s->res.analysers |= AN_RES_WAIT_CLI;
2284
2285 if (!(s->flags & SF_ASSIGNED)) {
2286 if (next_pid > -1)
2287 target_pid = next_pid;
2288 else
2289 target_pid = s->pcli_next_pid;
2290 /* we can connect now */
2291 s->target = pcli_pid_to_server(target_pid);
2292
2293 s->flags |= (SF_DIRECT | SF_ASSIGNED);
2294 channel_auto_connect(req);
2295 }
2296
2297 } else if (to_forward == 0) {
2298 /* we trimmed things but we might have other commands to consume */
2299 pcli_write_prompt(s);
2300 goto read_again;
2301 } else if (to_forward == -1 && errmsg) {
2302 /* there was an error during the parsing */
2303 pcli_reply_and_close(s, errmsg);
2304 return 0;
2305 } else if (to_forward == -1 && channel_full(req, global.tune.maxrewrite)) {
2306 /* buffer is full and we didn't catch the end of a command */
2307 goto send_help;
2308 }
2309
2310 return 0;
2311
2312 send_help:
2313 b_reset(&req->buf);
2314 b_putblk(&req->buf, "help\n", 5);
2315 goto read_again;
2316 }
2317
pcli_wait_for_response(struct stream * s,struct channel * rep,int an_bit)2318 int pcli_wait_for_response(struct stream *s, struct channel *rep, int an_bit)
2319 {
2320 struct proxy *fe = strm_fe(s);
2321 struct proxy *be = s->be;
2322
2323 if (rep->flags & CF_READ_ERROR) {
2324 pcli_reply_and_close(s, "Can't connect to the target CLI!\n");
2325 s->res.analysers &= ~AN_RES_WAIT_CLI;
2326 return 0;
2327 }
2328 rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */
2329 rep->flags |= CF_NEVER_WAIT;
2330
2331 /* don't forward the close */
2332 channel_dont_close(&s->res);
2333 channel_dont_close(&s->req);
2334
2335 if (s->pcli_flags & PCLI_F_PAYLOAD) {
2336 s->req.analysers |= AN_REQ_WAIT_CLI;
2337 s->res.analysers &= ~AN_RES_WAIT_CLI;
2338 s->req.flags |= CF_WAKE_ONCE; /* need to be called again if there is some command left in the request */
2339 return 0;
2340 }
2341
2342 /* forward the data */
2343 if (ci_data(rep)) {
2344 c_adv(rep, ci_data(rep));
2345 return 0;
2346 }
2347
2348 if ((rep->flags & (CF_SHUTR|CF_READ_NULL))) {
2349 /* stream cleanup */
2350
2351 pcli_write_prompt(s);
2352
2353 s->si[1].flags |= SI_FL_NOLINGER | SI_FL_NOHALF;
2354 si_shutr(&s->si[1]);
2355 si_shutw(&s->si[1]);
2356
2357 /*
2358 * starting from there this the same code as
2359 * http_end_txn_clean_session().
2360 *
2361 * It allows to do frontend keepalive while reconnecting to a
2362 * new server for each request.
2363 */
2364
2365 if (s->flags & SF_BE_ASSIGNED) {
2366 HA_ATOMIC_SUB(&be->beconn, 1);
2367 if (unlikely(s->srv_conn))
2368 sess_change_server(s, NULL);
2369 }
2370
2371 s->logs.t_close = tv_ms_elapsed(&s->logs.tv_accept, &now);
2372 stream_process_counters(s);
2373
2374 /* don't count other requests' data */
2375 s->logs.bytes_in -= ci_data(&s->req);
2376 s->logs.bytes_out -= ci_data(&s->res);
2377
2378 /* we may need to know the position in the queue */
2379 pendconn_free(s);
2380
2381 /* let's do a final log if we need it */
2382 if (!LIST_ISEMPTY(&fe->logformat) && s->logs.logwait &&
2383 !(s->flags & SF_MONITOR) &&
2384 (!(fe->options & PR_O_NULLNOLOG) || s->req.total)) {
2385 s->do_log(s);
2386 }
2387
2388 /* stop tracking content-based counters */
2389 stream_stop_content_counters(s);
2390 stream_update_time_stats(s);
2391
2392 s->logs.accept_date = date; /* user-visible date for logging */
2393 s->logs.tv_accept = now; /* corrected date for internal use */
2394 s->logs.t_handshake = 0; /* There are no handshake in keep alive connection. */
2395 s->logs.t_idle = -1;
2396 tv_zero(&s->logs.tv_request);
2397 s->logs.t_queue = -1;
2398 s->logs.t_connect = -1;
2399 s->logs.t_data = -1;
2400 s->logs.t_close = 0;
2401 s->logs.prx_queue_pos = 0; /* we get the number of pending conns before us */
2402 s->logs.srv_queue_pos = 0; /* we will get this number soon */
2403
2404 s->logs.bytes_in = s->req.total = ci_data(&s->req);
2405 s->logs.bytes_out = s->res.total = ci_data(&s->res);
2406
2407 stream_del_srv_conn(s);
2408 if (objt_server(s->target)) {
2409 if (s->flags & SF_CURR_SESS) {
2410 s->flags &= ~SF_CURR_SESS;
2411 HA_ATOMIC_SUB(&__objt_server(s->target)->cur_sess, 1);
2412 }
2413 if (may_dequeue_tasks(__objt_server(s->target), be))
2414 process_srv_queue(__objt_server(s->target), 0);
2415 }
2416
2417 s->target = NULL;
2418
2419 /* only release our endpoint if we don't intend to reuse the
2420 * connection.
2421 */
2422 if (!si_conn_ready(&s->si[1])) {
2423 si_release_endpoint(&s->si[1]);
2424 s->srv_conn = NULL;
2425 }
2426
2427 sockaddr_free(&s->target_addr);
2428
2429 s->si[1].state = s->si[1].prev_state = SI_ST_INI;
2430 s->si[1].err_type = SI_ET_NONE;
2431 s->si[1].conn_retries = 0; /* used for logging too */
2432 s->si[1].exp = TICK_ETERNITY;
2433 s->si[1].flags &= SI_FL_ISBACK | SI_FL_DONT_WAKE; /* we're in the context of process_stream */
2434 s->req.flags &= ~(CF_SHUTW|CF_SHUTW_NOW|CF_AUTO_CONNECT|CF_WRITE_ERROR|CF_STREAMER|CF_STREAMER_FAST|CF_NEVER_WAIT|CF_WROTE_DATA);
2435 s->res.flags &= ~(CF_SHUTR|CF_SHUTR_NOW|CF_READ_ATTACHED|CF_READ_ERROR|CF_READ_NOEXP|CF_STREAMER|CF_STREAMER_FAST|CF_WRITE_PARTIAL|CF_NEVER_WAIT|CF_WROTE_DATA|CF_READ_NULL);
2436 s->flags &= ~(SF_DIRECT|SF_ASSIGNED|SF_ADDR_SET|SF_BE_ASSIGNED|SF_FORCE_PRST|SF_IGNORE_PRST);
2437 s->flags &= ~(SF_CURR_SESS|SF_REDIRECTABLE|SF_SRV_REUSED);
2438 s->flags &= ~(SF_ERR_MASK|SF_FINST_MASK|SF_REDISP);
2439 /* reinitialise the current rule list pointer to NULL. We are sure that
2440 * any rulelist match the NULL pointer.
2441 */
2442 s->current_rule_list = NULL;
2443
2444 s->be = strm_fe(s);
2445 s->logs.logwait = strm_fe(s)->to_log;
2446 s->logs.level = 0;
2447 stream_del_srv_conn(s);
2448 s->target = NULL;
2449 /* re-init store persistence */
2450 s->store_count = 0;
2451 s->uniq_id = global.req_count++;
2452
2453 s->req.flags |= CF_READ_DONTWAIT; /* one read is usually enough */
2454
2455 s->req.flags |= CF_WAKE_ONCE; /* need to be called again if there is some command left in the request */
2456
2457 s->req.analysers |= AN_REQ_WAIT_CLI;
2458 s->res.analysers &= ~AN_RES_WAIT_CLI;
2459
2460 /* We must trim any excess data from the response buffer, because we
2461 * may have blocked an invalid response from a server that we don't
2462 * want to accidentally forward once we disable the analysers, nor do
2463 * we want those data to come along with next response. A typical
2464 * example of such data would be from a buggy server responding to
2465 * a HEAD with some data, or sending more than the advertised
2466 * content-length.
2467 */
2468 if (unlikely(ci_data(&s->res)))
2469 b_set_data(&s->res.buf, co_data(&s->res));
2470
2471 /* Now we can realign the response buffer */
2472 c_realign_if_empty(&s->res);
2473
2474 s->req.rto = strm_fe(s)->timeout.client;
2475 s->req.wto = TICK_ETERNITY;
2476
2477 s->res.rto = TICK_ETERNITY;
2478 s->res.wto = strm_fe(s)->timeout.client;
2479
2480 s->req.rex = TICK_ETERNITY;
2481 s->req.wex = TICK_ETERNITY;
2482 s->req.analyse_exp = TICK_ETERNITY;
2483 s->res.rex = TICK_ETERNITY;
2484 s->res.wex = TICK_ETERNITY;
2485 s->res.analyse_exp = TICK_ETERNITY;
2486 s->si[1].hcto = TICK_ETERNITY;
2487
2488 /* we're removing the analysers, we MUST re-enable events detection.
2489 * We don't enable close on the response channel since it's either
2490 * already closed, or in keep-alive with an idle connection handler.
2491 */
2492 channel_auto_read(&s->req);
2493 channel_auto_close(&s->req);
2494 channel_auto_read(&s->res);
2495
2496
2497 return 1;
2498 }
2499 return 0;
2500 }
2501
2502 /*
2503 * The mworker functions are used to initialize the CLI in the master process
2504 */
2505
2506 /*
2507 * Stop the mworker proxy
2508 */
mworker_cli_proxy_stop()2509 void mworker_cli_proxy_stop()
2510 {
2511 if (mworker_proxy)
2512 stop_proxy(mworker_proxy);
2513 }
2514
2515 /*
2516 * Create the mworker CLI proxy
2517 */
mworker_cli_proxy_create()2518 int mworker_cli_proxy_create()
2519 {
2520 struct mworker_proc *child;
2521 char *msg = NULL;
2522 char *errmsg = NULL;
2523
2524 mworker_proxy = calloc(1, sizeof(*mworker_proxy));
2525 if (!mworker_proxy)
2526 return -1;
2527
2528 init_new_proxy(mworker_proxy);
2529 mworker_proxy->next = proxies_list;
2530 proxies_list = mworker_proxy;
2531 mworker_proxy->id = strdup("MASTER");
2532 mworker_proxy->mode = PR_MODE_CLI;
2533 mworker_proxy->last_change = now.tv_sec;
2534 mworker_proxy->cap = PR_CAP_LISTEN; /* this is a listen section */
2535 mworker_proxy->maxconn = 10; /* default to 10 concurrent connections */
2536 mworker_proxy->timeout.client = 0; /* no timeout */
2537 mworker_proxy->conf.file = strdup("MASTER");
2538 mworker_proxy->conf.line = 0;
2539 mworker_proxy->accept = frontend_accept;
2540 mworker_proxy-> lbprm.algo = BE_LB_ALGO_NONE;
2541
2542 /* Does not init the default target the CLI applet, but must be done in
2543 * the request parsing code */
2544 mworker_proxy->default_target = NULL;
2545
2546 /* the check_config_validity() will get an ID for the proxy */
2547 mworker_proxy->uuid = -1;
2548
2549 proxy_store_name(mworker_proxy);
2550
2551 /* create all servers using the mworker_proc list */
2552 list_for_each_entry(child, &proc_list, list) {
2553 struct server *newsrv = NULL;
2554 struct sockaddr_storage *sk;
2555 int port1, port2, port;
2556 struct protocol *proto;
2557
2558 /* only the workers support the master CLI */
2559 if (!(child->options & PROC_O_TYPE_WORKER))
2560 continue;
2561
2562 newsrv = new_server(mworker_proxy);
2563 if (!newsrv)
2564 goto error;
2565
2566 /* we don't know the new pid yet */
2567 if (child->pid == -1)
2568 memprintf(&msg, "cur-%d", child->relative_pid);
2569 else
2570 memprintf(&msg, "old-%d", child->pid);
2571
2572 newsrv->next = mworker_proxy->srv;
2573 mworker_proxy->srv = newsrv;
2574 newsrv->conf.file = strdup(msg);
2575 newsrv->id = strdup(msg);
2576 newsrv->conf.line = 0;
2577
2578 memprintf(&msg, "sockpair@%d", child->ipc_fd[0]);
2579 if ((sk = str2sa_range(msg, &port, &port1, &port2, NULL, &proto,
2580 &errmsg, NULL, NULL, PA_O_STREAM)) == 0) {
2581 goto error;
2582 }
2583 free(msg);
2584 msg = NULL;
2585
2586 if (!proto->connect) {
2587 goto error;
2588 }
2589
2590 /* no port specified */
2591 newsrv->flags |= SRV_F_MAPPORTS;
2592 newsrv->addr = *sk;
2593 /* don't let the server participate to load balancing */
2594 newsrv->iweight = 0;
2595 newsrv->uweight = 0;
2596 srv_lb_commit_status(newsrv);
2597
2598 child->srv = newsrv;
2599 }
2600 return 0;
2601
2602 error:
2603 ha_alert("%s\n", errmsg);
2604
2605 list_for_each_entry(child, &proc_list, list) {
2606 free((char *)child->srv->conf.file); /* cast because of const char * */
2607 free(child->srv->id);
2608 free(child->srv);
2609 child->srv = NULL;
2610 }
2611 free(mworker_proxy->id);
2612 free(mworker_proxy->conf.file);
2613 free(mworker_proxy);
2614 mworker_proxy = NULL;
2615 free(errmsg);
2616 free(msg);
2617
2618 return -1;
2619 }
2620
2621 /*
2622 * Create a new listener for the master CLI proxy
2623 */
mworker_cli_proxy_new_listener(char * line)2624 int mworker_cli_proxy_new_listener(char *line)
2625 {
2626 struct bind_conf *bind_conf;
2627 struct listener *l;
2628 char *err = NULL;
2629 char *args[MAX_LINE_ARGS + 1];
2630 int arg;
2631 int cur_arg;
2632
2633 arg = 1;
2634 args[0] = line;
2635
2636 /* args is a bind configuration with spaces replaced by commas */
2637 while (*line && arg < MAX_LINE_ARGS) {
2638
2639 if (*line == ',') {
2640 *line++ = '\0';
2641 while (*line == ',')
2642 line++;
2643 args[arg++] = line;
2644 }
2645 line++;
2646 }
2647
2648 args[arg] = "\0";
2649
2650 bind_conf = bind_conf_alloc(mworker_proxy, "master-socket", 0, "", xprt_get(XPRT_RAW));
2651 if (!bind_conf)
2652 goto err;
2653
2654 bind_conf->level &= ~ACCESS_LVL_MASK;
2655 bind_conf->level |= ACCESS_LVL_ADMIN;
2656
2657 if (!str2listener(args[0], mworker_proxy, bind_conf, "master-socket", 0, &err)) {
2658 ha_alert("Cannot create the listener of the master CLI\n");
2659 goto err;
2660 }
2661
2662 cur_arg = 1;
2663
2664 while (*args[cur_arg]) {
2665 static int bind_dumped;
2666 struct bind_kw *kw;
2667
2668 kw = bind_find_kw(args[cur_arg]);
2669 if (kw) {
2670 if (!kw->parse) {
2671 memprintf(&err, "'%s %s' : '%s' option is not implemented in this version (check build options).",
2672 args[0], args[1], args[cur_arg]);
2673 goto err;
2674 }
2675
2676 if (kw->parse(args, cur_arg, global.stats_fe, bind_conf, &err) != 0) {
2677 if (err)
2678 memprintf(&err, "'%s %s' : '%s'", args[0], args[1], err);
2679 else
2680 memprintf(&err, "'%s %s' : error encountered while processing '%s'",
2681 args[0], args[1], args[cur_arg]);
2682 goto err;
2683 }
2684
2685 cur_arg += 1 + kw->skip;
2686 continue;
2687 }
2688
2689 if (!bind_dumped) {
2690 bind_dump_kws(&err);
2691 indent_msg(&err, 4);
2692 bind_dumped = 1;
2693 }
2694
2695 memprintf(&err, "'%s %s' : unknown keyword '%s'.%s%s",
2696 args[0], args[1], args[cur_arg],
2697 err ? " Registered keywords :" : "", err ? err : "");
2698 goto err;
2699 }
2700
2701
2702 list_for_each_entry(l, &bind_conf->listeners, by_bind) {
2703 l->accept = session_accept_fd;
2704 l->default_target = mworker_proxy->default_target;
2705 /* don't make the peers subject to global limits and don't close it in the master */
2706 l->options |= LI_O_UNLIMITED;
2707 l->rx.flags |= RX_F_MWORKER; /* we are keeping this FD in the master */
2708 l->nice = -64; /* we want to boost priority for local stats */
2709 global.maxsock++; /* for the listening socket */
2710 }
2711 global.maxsock += mworker_proxy->maxconn;
2712
2713 return 0;
2714
2715 err:
2716 ha_alert("%s\n", err);
2717 free(err);
2718 free(bind_conf);
2719 return -1;
2720
2721 }
2722
2723 /*
2724 * Create a new CLI socket using a socketpair for a worker process
2725 * <mworker_proc> is the process structure, and <proc> is the process number
2726 */
mworker_cli_sockpair_new(struct mworker_proc * mworker_proc,int proc)2727 int mworker_cli_sockpair_new(struct mworker_proc *mworker_proc, int proc)
2728 {
2729 struct bind_conf *bind_conf;
2730 struct listener *l;
2731 char *path = NULL;
2732 char *err = NULL;
2733
2734 /* master pipe to ensure the master is still alive */
2735 if (socketpair(AF_UNIX, SOCK_STREAM, 0, mworker_proc->ipc_fd) < 0) {
2736 ha_alert("Cannot create worker socketpair.\n");
2737 return -1;
2738 }
2739
2740 /* XXX: we might want to use a separate frontend at some point */
2741 if (!global.stats_fe) {
2742 if ((global.stats_fe = alloc_stats_fe("GLOBAL", "master-socket", 0)) == NULL) {
2743 ha_alert("out of memory trying to allocate the stats frontend");
2744 goto error;
2745 }
2746 }
2747
2748 bind_conf = bind_conf_alloc(global.stats_fe, "master-socket", 0, "", xprt_get(XPRT_RAW));
2749 if (!bind_conf)
2750 goto error;
2751
2752 bind_conf->level &= ~ACCESS_LVL_MASK;
2753 bind_conf->level |= ACCESS_LVL_ADMIN; /* TODO: need to lower the rights with a CLI keyword*/
2754
2755 bind_conf->settings.bind_proc = 1UL << proc;
2756 global.stats_fe->bind_proc = 0; /* XXX: we should be careful with that, it can be removed by configuration */
2757
2758 if (!memprintf(&path, "sockpair@%d", mworker_proc->ipc_fd[1])) {
2759 ha_alert("Cannot allocate listener.\n");
2760 goto error;
2761 }
2762
2763 if (!str2listener(path, global.stats_fe, bind_conf, "master-socket", 0, &err)) {
2764 free(path);
2765 ha_alert("Cannot create a CLI sockpair listener for process #%d\n", proc);
2766 goto error;
2767 }
2768 free(path);
2769 path = NULL;
2770
2771 list_for_each_entry(l, &bind_conf->listeners, by_bind) {
2772 l->accept = session_accept_fd;
2773 l->default_target = global.stats_fe->default_target;
2774 l->options |= (LI_O_UNLIMITED | LI_O_NOSTOP);
2775 HA_ATOMIC_ADD(&unstoppable_jobs, 1);
2776 /* it's a sockpair but we don't want to keep the fd in the master */
2777 l->rx.flags &= ~RX_F_INHERITED;
2778 l->nice = -64; /* we want to boost priority for local stats */
2779 global.maxsock++; /* for the listening socket */
2780 }
2781
2782 return 0;
2783
2784 error:
2785 close(mworker_proc->ipc_fd[0]);
2786 close(mworker_proc->ipc_fd[1]);
2787 free(err);
2788
2789 return -1;
2790 }
2791
2792 static struct applet cli_applet = {
2793 .obj_type = OBJ_TYPE_APPLET,
2794 .name = "<CLI>", /* used for logging */
2795 .fct = cli_io_handler,
2796 .release = cli_release_handler,
2797 };
2798
2799 /* master CLI */
2800 static struct applet mcli_applet = {
2801 .obj_type = OBJ_TYPE_APPLET,
2802 .name = "<MCLI>", /* used for logging */
2803 .fct = cli_io_handler,
2804 .release = cli_release_handler,
2805 };
2806
2807 /* register cli keywords */
2808 static struct cli_kw_list cli_kws = {{ },{
2809 { { "help", NULL }, NULL, cli_parse_simple, NULL },
2810 { { "prompt", NULL }, NULL, cli_parse_simple, NULL },
2811 { { "quit", NULL }, NULL, cli_parse_simple, NULL },
2812 { { "set", "maxconn", "global", NULL }, "set maxconn global : change the per-process maxconn setting", cli_parse_set_maxconn_global, NULL },
2813 { { "set", "rate-limit", NULL }, "set rate-limit : change a rate limiting value", cli_parse_set_ratelimit, NULL },
2814 { { "set", "severity-output", NULL }, "set severity-output [none|number|string] : set presence of severity level in feedback information", cli_parse_set_severity_output, NULL, NULL },
2815 { { "set", "timeout", NULL }, "set timeout : change a timeout setting", cli_parse_set_timeout, NULL, NULL },
2816 { { "show", "env", NULL }, "show env [var] : dump environment variables known to the process", cli_parse_show_env, cli_io_handler_show_env, NULL },
2817 { { "show", "cli", "sockets", NULL }, "show cli sockets : dump list of cli sockets", cli_parse_default, cli_io_handler_show_cli_sock, NULL, NULL, ACCESS_MASTER },
2818 { { "show", "cli", "level", NULL }, "show cli level : display the level of the current CLI session", cli_parse_show_lvl, NULL, NULL, NULL, ACCESS_MASTER},
2819 { { "show", "fd", NULL }, "show fd [num] : dump list of file descriptors in use", cli_parse_show_fd, cli_io_handler_show_fd, NULL },
2820 { { "show", "activity", NULL }, "show activity : show per-thread activity stats (for support/developers)", cli_parse_default, cli_io_handler_show_activity, NULL },
2821 { { "operator", NULL }, "operator : lower the level of the current CLI session to operator", cli_parse_set_lvl, NULL, NULL, NULL, ACCESS_MASTER},
2822 { { "user", NULL }, "user : lower the level of the current CLI session to user", cli_parse_set_lvl, NULL, NULL, NULL, ACCESS_MASTER},
2823 { { "_getsocks", NULL }, NULL, _getsocks, NULL },
2824 { { "expert-mode", NULL }, NULL, cli_parse_expert_mode, NULL }, // not listed
2825 {{},}
2826 }};
2827
2828 INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2829
2830 static struct cfg_kw_list cfg_kws = {ILH, {
2831 { CFG_GLOBAL, "stats", stats_parse_global },
2832 { 0, NULL, NULL },
2833 }};
2834
2835 INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
2836
2837 static struct bind_kw_list bind_kws = { "STAT", { }, {
2838 { "level", bind_parse_level, 1 }, /* set the unix socket admin level */
2839 { "expose-fd", bind_parse_expose_fd, 1 }, /* set the unix socket expose fd rights */
2840 { "severity-output", bind_parse_severity_output, 1 }, /* set the severity output format */
2841 { NULL, NULL, 0 },
2842 }};
2843
2844 INITCALL1(STG_REGISTER, bind_register_keywords, &bind_kws);
2845
2846 /*
2847 * Local variables:
2848 * c-indent-level: 8
2849 * c-basic-offset: 8
2850 * End:
2851 */
2852