/* * Functions dedicated to statistics output and the stats socket * * Copyright 2000-2012 Willy Tarreau * Copyright 2007-2009 Krzysztof Piotr Oledzki * * 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define PAYLOAD_PATTERN "<<" static struct applet cli_applet; static struct applet mcli_applet; static const char cli_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[]; struct proxy *mworker_proxy; /* CLI proxy of the master */ struct bind_conf *mcli_reload_bind_conf; /* CLI context for the "show env" command */ struct show_env_ctx { char **var; /* first variable to show */ int show_one; /* stop after showing the first one */ }; /* CLI context for the "show fd" command */ /* flags for show_fd_ctx->show_mask */ #define CLI_SHOWFD_F_PI 0x00000001 /* pipes */ #define CLI_SHOWFD_F_LI 0x00000002 /* listeners */ #define CLI_SHOWFD_F_FE 0x00000004 /* frontend conns */ #define CLI_SHOWFD_F_SV 0x00000010 /* server-only conns */ #define CLI_SHOWFD_F_PX 0x00000020 /* proxy-only conns */ #define CLI_SHOWFD_F_BE 0x00000030 /* backend: srv+px */ #define CLI_SHOWFD_F_CO 0x00000034 /* conn: be+fe */ #define CLI_SHOWFD_F_ANY 0x0000003f /* any type */ struct show_fd_ctx { int fd; /* first FD to show */ int show_one; /* stop after showing one FD */ uint show_mask; /* CLI_SHOWFD_F_xxx */ }; /* CLI context for the "show cli sockets" command */ struct show_sock_ctx { struct bind_conf *bind_conf; struct listener *listener; }; static int cmp_kw_entries(const void *a, const void *b) { const struct cli_kw *l = *(const struct cli_kw **)a; const struct cli_kw *r = *(const struct cli_kw **)b; return strcmp(l->usage ? l->usage : "", r->usage ? r->usage : ""); } /* This will show the help message and list the commands supported at the * current level that match all of the first words of if args is not * NULL, or all args if none matches or if args is null. */ static char *cli_gen_usage_msg(struct appctx *appctx, char * const *args) { struct cli_kw *entries[CLI_MAX_HELP_ENTRIES]; struct cli_kw_list *kw_list; struct cli_kw *kw; struct buffer *tmp = get_trash_chunk(); struct buffer out; struct { struct cli_kw *kw; int dist; } matches[CLI_MAX_MATCHES], swp; int idx; int ishelp = 0; int length = 0; int help_entries = 0; ha_free(&dynamic_usage_msg); if (args && *args && strcmp(*args, "help") == 0) { args++; ishelp = 1; } /* first, let's measure the longest match */ list_for_each_entry(kw_list, &cli_keywords.list, list) { for (kw = &kw_list->kw[0]; kw->str_kw[0]; kw++) { if (kw->level & ~appctx->cli_level & (ACCESS_MASTER_ONLY|ACCESS_EXPERT|ACCESS_EXPERIMENTAL)) continue; if (!(appctx->cli_level & ACCESS_MCLI_DEBUG) && (appctx->cli_level & ~kw->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)) == (ACCESS_MASTER_ONLY|ACCESS_MASTER)) continue; /* OK this command is visible */ for (idx = 0; idx < CLI_PREFIX_KW_NB; idx++) { if (!kw->str_kw[idx]) break; // end of keyword if (!args || !args[idx] || !*args[idx]) break; // end of command line if (strcmp(kw->str_kw[idx], args[idx]) != 0) break; if (idx + 1 > length) length = idx + 1; } } } /* now equals the number of exactly matching words */ chunk_reset(tmp); if (ishelp) // this is the help message. chunk_strcat(tmp, "The following commands are valid at this level:\n"); else { chunk_strcat(tmp, "Unknown command: '"); if (args && *args) chunk_strcat(tmp, *args); chunk_strcat(tmp, "'"); if (!length && (!args || !*args || !**args)) // no match chunk_strcat(tmp, ". Please enter one of the following commands only:\n"); else // partial match chunk_strcat(tmp, ", but maybe one of the following ones is a better match:\n"); } for (idx = 0; idx < CLI_MAX_MATCHES; idx++) { matches[idx].kw = NULL; matches[idx].dist = INT_MAX; } /* In case of partial match we'll look for the best matching entries * starting from position */ if (args && args[length] && *args[length]) { list_for_each_entry(kw_list, &cli_keywords.list, list) { for (kw = &kw_list->kw[0]; kw->str_kw[0]; kw++) { if (kw->level & ~appctx->cli_level & (ACCESS_MASTER_ONLY|ACCESS_EXPERT|ACCESS_EXPERIMENTAL)) continue; if (!(appctx->cli_level & ACCESS_MCLI_DEBUG) && ((appctx->cli_level & ~kw->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)) == (ACCESS_MASTER_ONLY|ACCESS_MASTER))) continue; for (idx = 0; idx < length; idx++) { if (!kw->str_kw[idx]) break; // end of keyword if (!args || !args[idx] || !*args[idx]) break; // end of command line if (strcmp(kw->str_kw[idx], args[idx]) != 0) break; } /* extra non-matching words are fuzzy-matched */ if (kw->usage && idx == length && args[idx] && *args[idx]) { uint8_t word_sig[1024]; uint8_t list_sig[1024]; int dist = 0; int totlen = 0; int i; /* this one matches, let's compute the distance between the two * on the remaining words. For this we're computing the signature * of everything that remains and the cumulated length of the * strings. */ memset(word_sig, 0, sizeof(word_sig)); for (i = idx; i < CLI_PREFIX_KW_NB && args[i] && *args[i]; i++) { update_word_fingerprint(word_sig, args[i]); totlen += strlen(args[i]); } memset(list_sig, 0, sizeof(list_sig)); for (i = idx; i < CLI_PREFIX_KW_NB && kw->str_kw[i]; i++) { update_word_fingerprint(list_sig, kw->str_kw[i]); totlen += strlen(kw->str_kw[i]); } dist = word_fingerprint_distance(word_sig, list_sig); /* insert this one at its place if relevant, in order to keep only * the best matches. */ swp.kw = kw; swp.dist = dist; if (dist < 5*totlen/2 && dist < matches[CLI_MAX_MATCHES-1].dist) { matches[CLI_MAX_MATCHES-1] = swp; for (idx = CLI_MAX_MATCHES - 1; --idx >= 0;) { if (matches[idx+1].dist >= matches[idx].dist) break; matches[idx+1] = matches[idx]; matches[idx] = swp; } } } } } } if (matches[0].kw) { /* we have fuzzy matches, let's propose them */ for (idx = 0; idx < CLI_MAX_MATCHES; idx++) { kw = matches[idx].kw; if (!kw) break; /* stop the dump if some words look very unlikely candidates */ if (matches[idx].dist > 5*matches[0].dist/2) break; if (help_entries < CLI_MAX_HELP_ENTRIES) entries[help_entries++] = kw; } } list_for_each_entry(kw_list, &cli_keywords.list, list) { /* no full dump if we've already found nice candidates */ if (matches[0].kw) break; for (kw = &kw_list->kw[0]; kw->str_kw[0]; kw++) { /* in a worker or normal process, don't display master-only commands * nor expert/experimental mode commands if not in this mode. */ if (kw->level & ~appctx->cli_level & (ACCESS_MASTER_ONLY|ACCESS_EXPERT|ACCESS_EXPERIMENTAL)) continue; /* in master, if the CLI don't have the * ACCESS_MCLI_DEBUG don't display commands that have * neither the master bit nor the master-only bit. */ if (!(appctx->cli_level & ACCESS_MCLI_DEBUG) && ((appctx->cli_level & ~kw->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)) == (ACCESS_MASTER_ONLY|ACCESS_MASTER))) continue; for (idx = 0; idx < length; idx++) { if (!kw->str_kw[idx]) break; // end of keyword if (!args || !args[idx] || !*args[idx]) break; // end of command line if (strcmp(kw->str_kw[idx], args[idx]) != 0) break; } if (kw->usage && idx == length && help_entries < CLI_MAX_HELP_ENTRIES) entries[help_entries++] = kw; } } qsort(entries, help_entries, sizeof(*entries), cmp_kw_entries); for (idx = 0; idx < help_entries; idx++) chunk_appendf(tmp, " %s\n", entries[idx]->usage); /* always show the prompt/help/quit commands */ chunk_strcat(tmp, " help [] : list matching or all commands\n" " prompt [timed] : toggle interactive mode with prompt\n" " quit : disconnect\n"); chunk_init(&out, NULL, 0); chunk_dup(&out, tmp); dynamic_usage_msg = out.area; cli_msg(appctx, LOG_INFO, dynamic_usage_msg); 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; } struct cli_kw* cli_find_kw_exact(char **args) { struct cli_kw_list *kw_list; int found = 0; int i; int j; if (LIST_ISEMPTY(&cli_keywords.list)) return NULL; list_for_each_entry(kw_list, &cli_keywords.list, list) { for (i = 0; kw_list->kw[i].str_kw[0]; i++) { found = 1; for (j = 0; j < CLI_PREFIX_KW_NB; j++) { if (args[j] == NULL && kw_list->kw[i].str_kw[j] == NULL) { break; } if (args[j] == NULL || kw_list->kw[i].str_kw[j] == NULL) { found = 0; break; } if (strcmp(args[j], kw_list->kw[i].str_kw[j]) != 0) { found = 0; break; } } if (found) return &kw_list->kw[i]; } } return NULL; } void cli_register_kw(struct cli_kw_list *kw_list) { LIST_APPEND(&cli_keywords.list, &kw_list->list); } /* list all known keywords on stdout, one per line */ void cli_list_keywords(void) { struct cli_kw_list *kw_list; struct cli_kw *kwp, *kwn, *kw; int idx; for (kwn = kwp = NULL;; kwp = kwn) { list_for_each_entry(kw_list, &cli_keywords.list, list) { /* note: we sort based on the usage message when available, * otherwise we fall back to the first keyword. */ for (kw = &kw_list->kw[0]; kw->str_kw[0]; kw++) { if (strordered(kwp ? kwp->usage ? kwp->usage : kwp->str_kw[0] : NULL, kw->usage ? kw->usage : kw->str_kw[0], kwn != kwp ? kwn->usage ? kwn->usage : kwn->str_kw[0] : NULL)) kwn = kw; } } if (kwn == kwp) break; for (idx = 0; kwn->str_kw[idx]; idx++) { printf("%s ", kwn->str_kw[idx]); } if (kwn->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)) printf("[MASTER] "); if (!(kwn->level & ACCESS_MASTER_ONLY)) printf("[WORKER] "); if (kwn->level & ACCESS_EXPERT) printf("[EXPERT] "); if (kwn->level & ACCESS_EXPERIMENTAL) printf("[EXPERIM] "); printf("\n"); } } /* allocate a new stats frontend named , and return it * (or NULL in case of lack of memory). */ static struct proxy *cli_alloc_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->fe_counters.last_change = ns_to_sec(now_ns); fe->id = strdup("GLOBAL"); fe->cap = PR_CAP_FE|PR_CAP_INT; 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 buffer which will be preallocated. The trailing * '\n' must not be written. The function must be called with pointing to * the first word after "stats". */ static int cli_parse_global(char **args, int section_type, struct proxy *curpx, const struct proxy *defpx, const char *file, int line, char **err) { struct bind_conf *bind_conf; struct listener *l; if (strcmp(args[1], "socket") == 0) { 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.cli_fe) { if ((global.cli_fe = cli_alloc_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.cli_fe, file, line, args[2], xprt_get(XPRT_RAW)); if (!bind_conf) { memprintf(err, "'%s %s' : out of memory trying to allocate a bind_conf", args[0], args[1]); return -1; } bind_conf->level &= ~ACCESS_LVL_MASK; bind_conf->level |= ACCESS_LVL_OPER; /* default access level */ if (!str2listener(args[2], global.cli_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]) { struct bind_kw *kw; const char *best; int code; 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; } code = kw->parse(args, cur_arg, global.cli_fe, bind_conf, err); /* FIXME: this is ugly, we don't have a way to collect warnings, * yet some important bind keywords may report warnings that we * must display. */ if (((code & (ERR_WARN|ERR_FATAL|ERR_ALERT)) == ERR_WARN) && err && *err) { indent_msg(err, 2); ha_warning("parsing [%s:%d] : '%s %s' : %s\n", file, line, args[0], args[1], *err); ha_free(err); } if (code & ~ERR_WARN) { 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; } best = bind_find_best_kw(args[cur_arg]); if (best) memprintf(err, "'%s %s' : unknown keyword '%s'. Did you mean '%s' maybe ?", args[0], args[1], args[cur_arg], best); else memprintf(err, "'%s %s' : unknown keyword '%s'.", args[0], args[1], args[cur_arg]); return -1; } bind_conf->accept = session_accept_fd; bind_conf->nice = -64; /* we want to boost priority for local stats */ bind_conf->options |= BC_O_UNLIMITED; /* don't make the peers subject to global limits */ list_for_each_entry(l, &bind_conf->listeners, by_bind) { global.maxsock++; /* for the listening socket */ } } else if (strcmp(args[1], "timeout") == 0) { 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.cli_fe) { if ((global.cli_fe = cli_alloc_fe("GLOBAL", file, line)) == NULL) { memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]); return -1; } } global.cli_fe->timeout.client = MS_TO_TICKS(timeout); } else if (strcmp(args[1], "maxconn") == 0) { int maxconn = atol(args[2]); if (maxconn <= 0) { memprintf(err, "'%s %s' expects a positive value", args[0], args[1]); return -1; } if (!global.cli_fe) { if ((global.cli_fe = cli_alloc_fe("GLOBAL", file, line)) == NULL) { memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]); return -1; } } global.cli_fe->maxconn = maxconn; } else if (strcmp(args[1], "bind-process") == 0) { memprintf(err, "'%s %s' is not supported anymore.", args[0], args[1]); return -1; } 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 in the environment * variable . 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->rx.addr.ss_family == AF_UNIX) { const struct sockaddr_un *un; un = (struct sockaddr_un *)&l->rx.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->rx.addr.ss_family == AF_INET) { addr_to_str(&l->rx.addr, addr, sizeof(addr)); port_to_str(&l->rx.addr, port, sizeof(port)); chunk_appendf(trash, "ipv4@%s:%s", addr, port); } else if (l->rx.addr.ss_family == AF_INET6) { addr_to_str(&l->rx.addr, addr, sizeof(addr)); port_to_str(&l->rx.addr, port, sizeof(port)); chunk_appendf(trash, "ipv6@[%s]:%s", addr, port); } else if (l->rx.addr.ss_family == AF_CUST_SOCKPAIR) { chunk_appendf(trash, "sockpair@%d", ((struct sockaddr_in *)&l->rx.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.cli_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 * (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, cli_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(appctx_strm(appctx))->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 (in which case an error * message will be displayed). 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_CLI_ARGS + 1], *p, *end, *payload = NULL; int i = 0; struct cli_kw *kw; p = b_head(&appctx->inbuf); end = b_tail(&appctx->inbuf); /* * Get pointers on words. * One extra slot is reserved to store a pointer on a null byte. */ while (i < MAX_CLI_ARGS && p < end) { int j, k; /* skip leading spaces/tabs */ p += strspn(p, " \t"); if (!*p) break; /* first check if the '<<' is present, but this is not enough * because we don't know if this is the end of the string */ if (strncmp(p, PAYLOAD_PATTERN, strlen(PAYLOAD_PATTERN)) == 0) { int pat_len = strlen(appctx->cli_payload_pat); /* then if the customized pattern is empty, check if the next character is '\0' */ if (pat_len == 0 && p[strlen(PAYLOAD_PATTERN)] == '\0') { payload = p + strlen(PAYLOAD_PATTERN) + 1; break; } /* else if we found the customized pattern at the end of the string */ if (strcmp(p + strlen(PAYLOAD_PATTERN), appctx->cli_payload_pat) == 0) { payload = p + strlen(PAYLOAD_PATTERN) + pat_len + 1; 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 = b_tail(&appctx->inbuf); for (; i < MAX_CLI_ARGS + 1; i++) args[i] = p; if (!**args) return 0; kw = cli_find_kw(args); if (!kw || (kw->level & ~appctx->cli_level & ACCESS_MASTER_ONLY) || (!(appctx->cli_level & ACCESS_MCLI_DEBUG) && (appctx->cli_level & ~kw->level & (ACCESS_MASTER_ONLY|ACCESS_MASTER)) == (ACCESS_MASTER_ONLY|ACCESS_MASTER))) { /* keyword not found in this mode */ cli_gen_usage_msg(appctx, args); return 0; } /* don't handle expert mode commands if not in this mode. */ if (kw->level & ~appctx->cli_level & ACCESS_EXPERT) { cli_err(appctx, "This command is restricted to expert mode only.\n"); return 0; } if (kw->level & ~appctx->cli_level & ACCESS_EXPERIMENTAL) { cli_err(appctx, "This command is restricted to experimental mode only.\n"); return 0; } if (kw->level == ACCESS_EXPERT) mark_tainted(TAINTED_CLI_EXPERT_MODE); else if (kw->level == ACCESS_EXPERIMENTAL) mark_tainted(TAINTED_CLI_EXPERIMENTAL_MODE); 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 appctx *appctx, const char *msg, int severity, int severity_output) { struct buffer *tmp; struct ist imsg; tmp = get_trash_chunk(); chunk_reset(tmp); if (likely(severity_output == CLI_SEVERITY_NONE)) goto send_it; 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); } } send_it: /* the vast majority of messages have their trailing LF but a few are * still missing it, and very rare ones might even have two. For this * reason, we'll first delete the trailing LFs if present, then * systematically append one. */ for (imsg = ist(msg); imsg.len > 0 && imsg.ptr[imsg.len - 1] == '\n'; imsg.len--) ; chunk_istcat(tmp, imsg); chunk_istcat(tmp, ist("\n")); return applet_putchk(appctx, tmp); } int cli_init(struct appctx *appctx) { struct stconn *sc = appctx_sc(appctx); struct bind_conf *bind_conf = strm_li(__sc_strm(sc))->bind_conf; appctx->cli_severity_output = bind_conf->severity_output; applet_reset_svcctx(appctx); appctx->st0 = CLI_ST_GETREQ; appctx->cli_level = bind_conf->level; /* Wakeup the applet ASAP. */ applet_need_more_data(appctx); return 0; } size_t cli_snd_buf(struct appctx *appctx, struct buffer *buf, size_t count, unsigned flags) { char *str; size_t len, ret = 0; int lf = 0; if (appctx->st0 == CLI_ST_INIT) cli_init(appctx); else if (appctx->st0 != CLI_ST_GETREQ) goto end; if (b_space_wraps(&appctx->inbuf)) b_slow_realign(&appctx->inbuf, trash.area, b_data(&appctx->inbuf)); while (1) { /* payload doesn't take escapes nor does it end on semi-colons, * so we use the regular getline. Normal mode however must stop * on LFs and semi-colons that are not prefixed by a backslash. * Note we reserve one byte at the end to insert a trailing nul * byte. */ str = b_tail(&appctx->inbuf); if (!(appctx->st1 & APPCTX_CLI_ST1_PAYLOAD)) len = b_getdelim(buf, ret, count, str, b_room(&appctx->inbuf) - 1, "\n;", '\\'); else len = b_getline(buf, ret, count, str, b_room(&appctx->inbuf) - 1); if (!len) { if (!b_room(buf) || (count > b_room(&appctx->inbuf) - 1)) { cli_err(appctx, "The command is too big for the buffer size. Please change tune.bufsize in the configuration to use a bigger command.\n"); applet_set_error(appctx); b_reset(&appctx->inbuf); } else if (flags & CO_SFL_LAST_DATA) { applet_set_eos(appctx); applet_set_error(appctx); b_reset(&appctx->inbuf); } break; } ret += len; count -= len; if (str[len-1] == '\n') lf = 1; /* Remove the trailing \r, if any and add a null byte at the * end. For normal mode, the trailing \n is removed, but we * conserve if for payload mode. */ len--; if (len && str[len-1] == '\r') len--; if (appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) { str[len+1] = '\0'; b_add(&appctx->inbuf, len+1); } else { str[len] = '\0'; b_add(&appctx->inbuf, len); } if (appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) { /* look for a pattern */ if (len == strlen(appctx->cli_payload_pat)) { /* here use 'len' because str still contains the \n */ if (strncmp(str, appctx->cli_payload_pat, len) == 0) { /* remove the last two \n */ b_sub(&appctx->inbuf, strlen(appctx->cli_payload_pat) + 2); *b_tail(&appctx->inbuf) = '\0'; appctx->st1 &= ~APPCTX_CLI_ST1_PAYLOAD; if (!(appctx->st1 & APPCTX_CLI_ST1_PROMPT) && lf) appctx->st1 |= APPCTX_CLI_ST1_LASTCMD; } } } else { char *last_arg; /* * 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. * * The pattern must start by << followed by 0 to 7 * characters, and finished by the end of the command * (\n or ;). */ /* look for the first space starting by the end of the line */ for (last_arg = b_tail(&appctx->inbuf); last_arg != b_head(&appctx->inbuf); last_arg--) { if (*last_arg == ' ' || *last_arg == '\t') { last_arg++; break; } } if (strncmp(last_arg, PAYLOAD_PATTERN, strlen(PAYLOAD_PATTERN)) == 0) { ssize_t pat_len = strlen(last_arg + strlen(PAYLOAD_PATTERN)); /* A customized pattern can't be more than 7 characters * if it's more, don't make it a payload */ if (pat_len < sizeof(appctx->cli_payload_pat)) { appctx->st1 |= APPCTX_CLI_ST1_PAYLOAD; /* copy the customized pattern, don't store the << */ strncpy(appctx->cli_payload_pat, last_arg + strlen(PAYLOAD_PATTERN), sizeof(appctx->cli_payload_pat)-1); appctx->cli_payload_pat[sizeof(appctx->cli_payload_pat)-1] = '\0'; b_add(&appctx->inbuf, 1); // keep the trailing \0 after the pattern } } else { if (!(appctx->st1 & APPCTX_CLI_ST1_PROMPT) && lf) appctx->st1 |= APPCTX_CLI_ST1_LASTCMD; } } if (!(appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) || (appctx->st1 & APPCTX_CLI_ST1_PROMPT)) { appctx->st0 = CLI_ST_PARSEREQ; break; } } b_del(buf, ret); end: return ret; } /* This I/O handler runs as an applet embedded in a stream connector. 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) { if (applet_fl_test(appctx, APPCTX_FL_OUTBLK_ALLOC|APPCTX_FL_OUTBLK_FULL)) goto out; if (!appctx_get_buf(appctx, &appctx->outbuf)) { goto out; } if (unlikely(applet_fl_test(appctx, APPCTX_FL_EOS|APPCTX_FL_ERROR))) { appctx->st0 = CLI_ST_END; goto out; } while (1) { if (appctx->st0 == CLI_ST_INIT) { /* reset severity to default at init */ cli_init(appctx); break; } else if (appctx->st0 == CLI_ST_END) { applet_set_eos(appctx); break; } else if (appctx->st0 == CLI_ST_GETREQ) { /* Now we close the output 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 (se_fl_test(appctx->sedesc, SE_FL_SHW)) { appctx->st0 = CLI_ST_END; continue; } break; } else if (appctx->st0 == CLI_ST_PARSEREQ) { /* ensure we have some output room left in the event we * would want to return some info right after parsing. */ if (buffer_almost_full(&appctx->outbuf)) { applet_fl_set(appctx, APPCTX_FL_OUTBLK_FULL); break; } appctx->t->expire = TICK_ETERNITY; appctx->st0 = CLI_ST_PROMPT; if (!(appctx->st1 & APPCTX_CLI_ST1_PAYLOAD)) { cli_parse_request(appctx); b_reset(&appctx->inbuf); } } else { /* output functions */ struct cli_print_ctx *ctx; const char *msg; int sev; cli_output: 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_DYNERR: /* print dyn error in err, free */ case CLI_ST_PRINT_UMSG: /* print usermsgs_ctx and reset it */ case CLI_ST_PRINT_UMSGERR: /* print usermsgs_ctx as error and reset it */ /* the message is in the svcctx */ ctx = applet_reserve_svcctx(appctx, sizeof(*ctx)); if (appctx->st0 == CLI_ST_PRINT || appctx->st0 == CLI_ST_PRINT_ERR) { sev = appctx->st0 == CLI_ST_PRINT_ERR ? LOG_ERR : ctx->severity; msg = ctx->msg; } else if (appctx->st0 == CLI_ST_PRINT_DYN || appctx->st0 == CLI_ST_PRINT_DYNERR) { sev = appctx->st0 == CLI_ST_PRINT_DYNERR ? LOG_ERR : ctx->severity; msg = ctx->err; if (!msg) { sev = LOG_ERR; msg = "Out of memory.\n"; } } else if (appctx->st0 == CLI_ST_PRINT_UMSG || appctx->st0 == CLI_ST_PRINT_UMSGERR) { sev = appctx->st0 == CLI_ST_PRINT_UMSGERR ? LOG_ERR : ctx->severity; msg = usermsgs_str(); } else { sev = LOG_ERR; msg = "Internal error.\n"; } if (cli_output_msg(appctx, msg, sev, cli_get_severity_output(appctx)) != -1) { if (appctx->st0 == CLI_ST_PRINT_DYN || appctx->st0 == CLI_ST_PRINT_DYNERR) { ha_free(&ctx->err); } else if (appctx->st0 == CLI_ST_PRINT_UMSG || appctx->st0 == CLI_ST_PRINT_UMSGERR) { usermsgs_clr(NULL); } appctx->t->expire = TICK_ETERNITY; appctx->st0 = CLI_ST_PROMPT; } if (applet_fl_test(appctx, APPCTX_FL_ERR_PENDING)) { appctx->st0 = CLI_ST_END; continue; } break; case CLI_ST_CALLBACK: /* use custom pointer */ if (appctx->io_handler) if (appctx->io_handler(appctx)) { appctx->t->expire = TICK_ETERNITY; appctx->st0 = CLI_ST_PROMPT; if (appctx->io_release) { appctx->io_release(appctx); appctx->io_release = NULL; /* some release handlers might have * pending output to print. */ continue; } } break; default: /* abnormal state */ se_fl_set(appctx->sedesc, SE_FL_ERROR); break; } /* The post-command prompt is either LF alone or LF + '> ' in interactive mode */ if (appctx->st0 == CLI_ST_PROMPT) { char prompt_buf[20]; 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 (b_data(&appctx->inbuf) && appctx->st1 & APPCTX_CLI_ST1_PAYLOAD) prompt = "+ "; else if (appctx->st1 & APPCTX_CLI_ST1_TIMED) { uint up = ns_to_sec(now_ns - start_time_ns); snprintf(prompt_buf, sizeof(prompt_buf), "\n[%u:%02u:%02u:%02u]> ", (up / 86400), (up / 3600) % 24, (up / 60) % 60, up % 60); prompt = prompt_buf; } else prompt = "\n> "; } else { if (!(appctx->st1 & (APPCTX_CLI_ST1_PAYLOAD|APPCTX_CLI_ST1_NOLF))) prompt = "\n"; } if (applet_putstr(appctx, prompt) != -1) { applet_reset_svcctx(appctx); appctx->st0 = CLI_ST_GETREQ; } } /* If the output functions are still there, it means they require more room. */ if (appctx->st0 >= CLI_ST_OUTPUT) { applet_wont_consume(appctx); break; } /* Now we close the output 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 ((appctx->st1 & (APPCTX_CLI_ST1_PROMPT|APPCTX_CLI_ST1_PAYLOAD|APPCTX_CLI_ST1_LASTCMD)) == APPCTX_CLI_ST1_LASTCMD) { applet_set_eoi(appctx); appctx->st0 = CLI_ST_END; continue; } /* switch state back to GETREQ to read next requests */ applet_reset_svcctx(appctx); appctx->st0 = CLI_ST_GETREQ; applet_will_consume(appctx); applet_expect_data(appctx); /* reactivate the \n at the end of the response for the next command */ appctx->st1 &= ~APPCTX_CLI_ST1_NOLF; /* this forces us to yield between pipelined commands and * avoid extremely long latencies (e.g. "del map" etc). In * addition this increases the likelihood that the stream * refills the buffer with new bytes in non-interactive * mode, avoiding to close on apparently empty commands. */ break; } } out: if (appctx->st0 == CLI_ST_END) { /* eat the whole request */ b_reset(&appctx->inbuf); applet_fl_clr(appctx, APPCTX_FL_INBLK_FULL); } return; } /* This is called when the stream connector 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_DYN || appctx->st0 == CLI_ST_PRINT_DYNERR) { struct cli_print_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx)); ha_free(&ctx->err); } else if (appctx->st0 == CLI_ST_PRINT_UMSG || appctx->st0 == CLI_ST_PRINT_UMSGERR) { usermsgs_clr(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. It takes its context from the show_env_ctx in svcctx, and will * start from ->var and dump only one variable if ->show_one is set. */ static int cli_io_handler_show_env(struct appctx *appctx) { struct show_env_ctx *ctx = appctx->svcctx; char **var = ctx->var; 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 (applet_putchk(appctx, &trash) == -1) return 0; if (ctx->show_one) break; var++; ctx->var = 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. It takes its context from the show_fd_ctx * in svcctx, only dumps one entry if ->show_one is non-zero, and (re)starts * from ->fd. */ static int cli_io_handler_show_fd(struct appctx *appctx) { struct show_fd_ctx *fdctx = appctx->svcctx; uint match = fdctx->show_mask; int fd = fdctx->fd; int ret = 1; 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; const struct listener *li = NULL; const struct server *sv = NULL; const struct proxy *px = NULL; const struct connection *conn = NULL; const struct mux_ops *mux = NULL; const struct xprt_ops *xprt = NULL; const void *ctx = NULL; const void *xprt_ctx = NULL; const struct quic_conn *qc = NULL; uint32_t conn_flags = 0; uint8_t conn_err = 0; int is_back = 0; int suspicious = 0; fdt = fdtab[fd]; /* When DEBUG_FD is set, we also report closed FDs that have a * non-null event count to detect stuck ones. */ if (!fdt.owner) { #ifdef DEBUG_FD if (!fdt.event_count) #endif goto skip; // closed } else if (fdt.iocb == sock_conn_iocb) { conn = (const struct connection *)fdt.owner; conn_flags = conn->flags; conn_err = conn->err_code; mux = conn->mux; ctx = conn->ctx; xprt = conn->xprt; xprt_ctx = conn->xprt_ctx; li = objt_listener(conn->target); sv = objt_server(conn->target); px = objt_proxy(conn->target); is_back = conn_is_back(conn); if (atleast2(fdt.thread_mask)) suspicious = 1; if (conn->handle.fd != fd) suspicious = 1; } #if defined(USE_QUIC) else if (fdt.iocb == quic_conn_sock_fd_iocb) { qc = fdtab[fd].owner; li = qc ? qc->li : NULL; xprt_ctx = qc ? qc->xprt_ctx : NULL; conn = qc ? qc->conn : NULL; xprt = conn ? conn->xprt : NULL; // in fact it's &ssl_quic mux = conn ? conn->mux : NULL; /* quic_conns don't always have a connection but they * always have an xprt_ctx. */ } else if (fdt.iocb == quic_lstnr_sock_fd_iocb) { li = objt_listener(fdtab[fd].owner); } #endif else if (fdt.iocb == sock_accept_iocb) li = fdt.owner; if (!(((conn || xprt_ctx) && ((match & CLI_SHOWFD_F_SV && sv) || (match & CLI_SHOWFD_F_PX && px) || (match & CLI_SHOWFD_F_FE && li))) || (!conn && ((match & CLI_SHOWFD_F_LI && li) || (match & CLI_SHOWFD_F_PI && !li /* only pipes match this */))))) { /* not a desired type */ goto skip; } if (!fdt.thread_mask) suspicious = 1; chunk_printf(&trash, " %5d : st=0x%06x(%c%c %c%c%c%c%c W:%c%c%c R:%c%c%c) ref=%#x gid=%d tmask=0x%lx umask=0x%lx prmsk=0x%lx pwmsk=0x%lx owner=%p iocb=%p(", fd, fdt.state, (fdt.state & FD_CLONED) ? 'C' : 'c', (fdt.state & FD_LINGER_RISK) ? 'L' : 'l', (fdt.state & FD_POLL_HUP) ? 'H' : 'h', (fdt.state & FD_POLL_ERR) ? 'E' : 'e', (fdt.state & FD_POLL_OUT) ? 'O' : 'o', (fdt.state & FD_POLL_PRI) ? 'P' : 'p', (fdt.state & FD_POLL_IN) ? 'I' : 'i', (fdt.state & FD_EV_SHUT_W) ? 'S' : 's', (fdt.state & FD_EV_READY_W) ? 'R' : 'r', (fdt.state & FD_EV_ACTIVE_W) ? 'A' : 'a', (fdt.state & FD_EV_SHUT_R) ? 'S' : 's', (fdt.state & FD_EV_READY_R) ? 'R' : 'r', (fdt.state & FD_EV_ACTIVE_R) ? 'A' : 'a', (fdt.refc_tgid >> 4) & 0xffff, (fdt.refc_tgid) & 0xffff, fdt.thread_mask, fdt.update_mask, polled_mask[fd].poll_recv, polled_mask[fd].poll_send, fdt.owner, fdt.iocb); resolve_sym_name(&trash, NULL, fdt.iocb); if (!fdt.owner) { chunk_appendf(&trash, ")"); } else if (conn) { chunk_appendf(&trash, ") back=%d cflg=0x%08x cerr=%d", is_back, conn_flags, conn_err); if (!(conn->flags & CO_FL_FDLESS) && conn->handle.fd != fd) { chunk_appendf(&trash, " fd=%d(BOGUS)", conn->handle.fd); suspicious = 1; } else if ((conn->flags & CO_FL_FDLESS) && (qc != conn->handle.qc)) { chunk_appendf(&trash, " qc=%p(BOGUS)", conn->handle.qc); suspicious = 1; } else { struct sockaddr_storage sa; socklen_t salen; salen = sizeof(sa); if (getsockname(fd, (struct sockaddr *)&sa, &salen) != -1) { if (sa.ss_family == AF_INET) chunk_appendf(&trash, " fam=ipv4 lport=%d", ntohs(((const struct sockaddr_in *)&sa)->sin_port)); else if (sa.ss_family == AF_INET6) chunk_appendf(&trash, " fam=ipv6 lport=%d", ntohs(((const struct sockaddr_in6 *)&sa)->sin6_port)); else if (sa.ss_family == AF_UNIX) chunk_appendf(&trash, " fam=unix"); } salen = sizeof(sa); if (getpeername(fd, (struct sockaddr *)&sa, &salen) != -1) { if (sa.ss_family == AF_INET) chunk_appendf(&trash, " rport=%d", ntohs(((const struct sockaddr_in *)&sa)->sin_port)); else if (sa.ss_family == AF_INET6) chunk_appendf(&trash, " rport=%d", ntohs(((const struct sockaddr_in6 *)&sa)->sin6_port)); } } if (px) chunk_appendf(&trash, " px=%s", px->id); else if (sv) chunk_appendf(&trash, " sv=%s/%s", sv->proxy->id, sv->id); else if (li) chunk_appendf(&trash, " fe=%s", li->bind_conf->frontend->id); if (mux) { chunk_appendf(&trash, " mux=%s ctx=%p", mux->name, ctx); if (!ctx && !qc) suspicious = 1; if (mux->show_fd) suspicious |= mux->show_fd(&trash, fdt.owner); } else chunk_appendf(&trash, " nomux"); chunk_appendf(&trash, " xprt=%s", xprt ? xprt->name : ""); if (xprt) { if (xprt_ctx || xprt->show_fd) chunk_appendf(&trash, " xprt_ctx=%p", xprt_ctx); if (xprt->show_fd) suspicious |= xprt->show_fd(&trash, conn, xprt_ctx); } } else if (li && !xprt_ctx) { struct sockaddr_storage sa; socklen_t salen; chunk_appendf(&trash, ") l.st=%s fe=%s", listener_state_str(li), li->bind_conf->frontend->id); salen = sizeof(sa); if (getsockname(fd, (struct sockaddr *)&sa, &salen) != -1) { if (sa.ss_family == AF_INET) chunk_appendf(&trash, " fam=ipv4 lport=%d", ntohs(((const struct sockaddr_in *)&sa)->sin_port)); else if (sa.ss_family == AF_INET6) chunk_appendf(&trash, " fam=ipv6 lport=%d", ntohs(((const struct sockaddr_in6 *)&sa)->sin6_port)); else if (sa.ss_family == AF_UNIX) chunk_appendf(&trash, " fam=unix"); } } else chunk_appendf(&trash, ")"); #ifdef DEBUG_FD chunk_appendf(&trash, " evcnt=%u", fdtab[fd].event_count); if (fdtab[fd].event_count >= 1000000) suspicious = 1; #endif chunk_appendf(&trash, "%s\n", suspicious ? " !" : ""); if (applet_putchk(appctx, &trash) == -1) { fdctx->fd = fd; ret = 0; break; } skip: if (fdctx->show_one) break; fd++; } end: /* dump complete */ thread_release(); return ret; } /* * CLI IO handler for `show cli sockets`. * Uses the svcctx as a show_sock_ctx to store/retrieve the bind_conf and the * listener pointers. */ static int cli_io_handler_show_cli_sock(struct appctx *appctx) { struct show_sock_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx)); struct bind_conf *bind_conf = ctx->bind_conf; if (!global.cli_fe) goto done; chunk_reset(&trash); if (!bind_conf) { /* first call */ if (applet_putstr(appctx, "# socket lvl processes\n") == -1) goto full; bind_conf = LIST_ELEM(global.cli_fe->conf.bind.n, typeof(bind_conf), by_fe); } list_for_each_entry_from(bind_conf, &global.cli_fe->conf.bind, by_fe) { struct listener *l = ctx->listener; if (!l) l = LIST_ELEM(bind_conf->listeners.n, typeof(l), by_bind); list_for_each_entry_from(l, &bind_conf->listeners, by_bind) { char addr[46]; char port[6]; if (l->rx.addr.ss_family == AF_UNIX) { const struct sockaddr_un *un; un = (struct sockaddr_un *)&l->rx.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->rx.addr.ss_family == AF_INET) { addr_to_str(&l->rx.addr, addr, sizeof(addr)); port_to_str(&l->rx.addr, port, sizeof(port)); chunk_appendf(&trash, "ipv4@%s:%s ", addr, port); } else if (l->rx.addr.ss_family == AF_INET6) { addr_to_str(&l->rx.addr, addr, sizeof(addr)); port_to_str(&l->rx.addr, port, sizeof(port)); chunk_appendf(&trash, "ipv6@[%s]:%s ", addr, port); } else if (l->rx.addr.ss_family == AF_CUST_SOCKPAIR) { chunk_appendf(&trash, "sockpair@%d ", ((struct sockaddr_in *)&l->rx.addr)->sin_addr.s_addr); } else chunk_appendf(&trash, "unknown "); if ((bind_conf->level & ACCESS_LVL_MASK) == ACCESS_LVL_ADMIN) chunk_appendf(&trash, "admin "); else if ((bind_conf->level & ACCESS_LVL_MASK) == ACCESS_LVL_OPER) chunk_appendf(&trash, "operator "); else if ((bind_conf->level & ACCESS_LVL_MASK) == ACCESS_LVL_USER) chunk_appendf(&trash, "user "); else chunk_appendf(&trash, " "); chunk_appendf(&trash, "all\n"); if (applet_putchk(appctx, &trash) == -1) { ctx->bind_conf = bind_conf; ctx->listener = l; goto full; } } } done: return 1; full: return 0; } /* parse a "show env" CLI request. Returns 0 if it needs to continue, 1 if it * wants to stop here. It reserves a sohw_env_ctx where it puts the variable to * be dumped as well as a flag if a single variable is requested, otherwise puts * environ there. */ static int cli_parse_show_env(char **args, char *payload, struct appctx *appctx, void *private) { struct show_env_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx)); extern char **environ; char **var; if (!cli_has_level(appctx, ACCESS_LVL_OPER)) return 1; var = environ; if (*args[2]) { int len = strlen(args[2]); for (; *var; var++) { if (strncmp(*var, args[2], len) == 0 && (*var)[len] == '=') break; } if (!*var) return cli_err(appctx, "Variable not found\n"); ctx->show_one = 1; } ctx->var = var; return 0; } /* parse a "show fd" CLI request. Returns 0 if it needs to continue, 1 if it * wants to stop here. It sets a show_fd_ctx context where, if a specific fd is * requested, it puts the FD number into ->fd and sets ->show_one to 1. */ static int cli_parse_show_fd(char **args, char *payload, struct appctx *appctx, void *private) { struct show_fd_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx)); const char *c; int arg; if (!cli_has_level(appctx, ACCESS_LVL_OPER)) return 1; arg = 2; /* when starting with an inversion we preset every flag */ if (*args[arg] == '!' || *args[arg] == '-') ctx->show_mask = CLI_SHOWFD_F_ANY; while (*args[arg] && !isdigit((uchar)*args[arg])) { uint flag = 0, inv = 0; c = args[arg]; while (*c) { switch (*c) { case '!': inv = !inv; break; case '-': inv = !inv; break; case 'p': flag = CLI_SHOWFD_F_PI; break; case 'l': flag = CLI_SHOWFD_F_LI; break; case 'c': flag = CLI_SHOWFD_F_CO; break; case 'f': flag = CLI_SHOWFD_F_FE; break; case 'b': flag = CLI_SHOWFD_F_BE; break; case 's': flag = CLI_SHOWFD_F_SV; break; case 'd': flag = CLI_SHOWFD_F_PX; break; default: return cli_err(appctx, "Invalid FD type\n"); } c++; if (!inv) ctx->show_mask |= flag; else ctx->show_mask &= ~flag; } arg++; } /* default mask is to show everything */ if (!ctx->show_mask) ctx->show_mask = CLI_SHOWFD_F_ANY; if (*args[arg]) { ctx->fd = atoi(args[2]); ctx->show_one = 1; } return 0; } /* parse a "set timeout" CLI request. It always returns 1. */ static int cli_parse_set_timeout(char **args, char *payload, struct appctx *appctx, void *private) { struct stream *s = appctx_strm(appctx); if (strcmp(args[2], "cli") == 0) { unsigned timeout; const char *res; if (!*args[3]) return cli_err(appctx, "Expects an integer value.\n"); res = parse_time_err(args[3], &timeout, TIME_UNIT_S); if (res || timeout < 1) return cli_err(appctx, "Invalid timeout value.\n"); s->scf->ioto = 1 + MS_TO_TICKS(timeout*1000); task_wakeup(s->task, TASK_WOKEN_MSG); // recompute timeouts return 1; } return cli_err(appctx, "'set timeout' only supports 'cli'.\n"); } /* parse a "set maxconn global" command. It always returns 1. */ static int cli_parse_set_maxconn_global(char **args, char *payload, struct appctx *appctx, void *private) { int v; if (!cli_has_level(appctx, ACCESS_LVL_ADMIN)) return 1; if (!*args[3]) return cli_err(appctx, "Expects an integer value.\n"); v = atoi(args[3]); if (v > global.hardmaxconn) return cli_err(appctx, "Value out of range.\n"); /* check for unlimited values */ if (v <= 0) v = global.hardmaxconn; global.maxconn = v; /* Dequeues all of the listeners waiting for a resource */ dequeue_all_listeners(); return 1; } static int set_severity_output(int *target, char *argument) { if (strcmp(argument, "none") == 0) { *target = CLI_SEVERITY_NONE; return 1; } else if (strcmp(argument, "number") == 0) { *target = CLI_SEVERITY_NUMBER; return 1; } else if (strcmp(argument, "string") == 0) { *target = CLI_SEVERITY_STRING; return 1; } return 0; } /* parse a "set severity-output" command. */ static int cli_parse_set_severity_output(char **args, char *payload, struct appctx *appctx, void *private) { /* this will ask the applet to not output a \n after the command */ if (strcmp(args[3], "-") == 0) appctx->st1 |= APPCTX_CLI_ST1_NOLF; if (*args[2] && set_severity_output(&appctx->cli_severity_output, args[2])) return 0; return cli_err(appctx, "one of 'none', 'number', 'string' is a required argument\n"); } /* show the level of the current CLI session */ static int cli_parse_show_lvl(char **args, char *payload, struct appctx *appctx, void *private) { if ((appctx->cli_level & ACCESS_LVL_MASK) == ACCESS_LVL_ADMIN) return cli_msg(appctx, LOG_INFO, "admin\n"); else if ((appctx->cli_level & ACCESS_LVL_MASK) == ACCESS_LVL_OPER) return cli_msg(appctx, LOG_INFO, "operator\n"); else if ((appctx->cli_level & ACCESS_LVL_MASK) == ACCESS_LVL_USER) return cli_msg(appctx, LOG_INFO, "user\n"); else return cli_msg(appctx, LOG_INFO, "unknown\n"); } /* parse and set the CLI level dynamically */ static int cli_parse_set_lvl(char **args, char *payload, struct appctx *appctx, void *private) { /* this will ask the applet to not output a \n after the command */ if (strcmp(args[1], "-") == 0) appctx->st1 |= APPCTX_CLI_ST1_NOLF; if (strcmp(args[0], "operator") == 0) { if (!cli_has_level(appctx, ACCESS_LVL_OPER)) { return 1; } appctx->cli_level &= ~ACCESS_LVL_MASK; appctx->cli_level |= ACCESS_LVL_OPER; } else if (strcmp(args[0], "user") == 0) { if (!cli_has_level(appctx, ACCESS_LVL_USER)) { return 1; } appctx->cli_level &= ~ACCESS_LVL_MASK; appctx->cli_level |= ACCESS_LVL_USER; } appctx->cli_level &= ~(ACCESS_EXPERT|ACCESS_EXPERIMENTAL); return 1; } /* parse and set the CLI expert/experimental-mode dynamically */ static int cli_parse_expert_experimental_mode(char **args, char *payload, struct appctx *appctx, void *private) { int level; char *level_str; char *output = NULL; /* this will ask the applet to not output a \n after the command */ if (*args[1] && *args[2] && strcmp(args[2], "-") == 0) appctx->st1 |= APPCTX_CLI_ST1_NOLF; if (!cli_has_level(appctx, ACCESS_LVL_ADMIN)) return 1; if (strcmp(args[0], "expert-mode") == 0) { level = ACCESS_EXPERT; level_str = "expert-mode"; } else if (strcmp(args[0], "experimental-mode") == 0) { level = ACCESS_EXPERIMENTAL; level_str = "experimental-mode"; } else if (strcmp(args[0], "mcli-debug-mode") == 0) { level = ACCESS_MCLI_DEBUG; level_str = "mcli-debug-mode"; } else { return 1; } if (!*args[1]) { memprintf(&output, "%s is %s\n", level_str, (appctx->cli_level & level) ? "ON" : "OFF"); return cli_dynmsg(appctx, LOG_INFO, output); } appctx->cli_level &= ~level; if (strcmp(args[1], "on") == 0) appctx->cli_level |= level; return 1; } /* shows HAProxy version */ static int cli_parse_show_version(char **args, char *payload, struct appctx *appctx, void *private) { char *msg = NULL; return cli_dynmsg(appctx, LOG_INFO, memprintf(&msg, "%s\n", haproxy_version)); } int cli_parse_default(char **args, char *payload, struct appctx *appctx, void *private) { return 0; } /* enable or disable the anonymized mode, it returns 1 when it works or displays an error message if it doesn't. */ static int cli_parse_set_anon(char **args, char *payload, struct appctx *appctx, void *private) { uint32_t tmp; long long key; if (strcmp(args[2], "on") == 0) { if (*args[3]) { key = atoll(args[3]); if (key < 1 || key > UINT_MAX) return cli_err(appctx, "Value out of range (1 to 4294967295 expected).\n"); appctx->cli_anon_key = key; } else { tmp = HA_ATOMIC_LOAD(&global.anon_key); if (tmp != 0) appctx->cli_anon_key = tmp; else appctx->cli_anon_key = ha_random32(); } } else if (strcmp(args[2], "off") == 0) { if (*args[3]) { return cli_err(appctx, "Key can't be added while disabling anonymized mode\n"); } else { appctx->cli_anon_key = 0; } } else { return cli_err(appctx, "'set anon' only supports :\n" " - 'on' [key] to enable the anonymized mode\n" " - 'off' to disable the anonymized mode"); } return 1; } /* This function set the global anonyzing key, restricted to level 'admin' */ static int cli_parse_set_global_key(char **args, char *payload, struct appctx *appctx, void *private) { long long key; if (!cli_has_level(appctx, ACCESS_LVL_ADMIN)) return cli_err(appctx, "Permission denied\n"); if (!*args[2]) return cli_err(appctx, "Expects an integer value.\n"); key = atoll(args[2]); if (key < 0 || key > UINT_MAX) return cli_err(appctx, "Value out of range (0 to 4294967295 expected).\n"); HA_ATOMIC_STORE(&global.anon_key, key); return 1; } /* shows the anonymized mode state to everyone, and the key except for users, it always returns 1. */ static int cli_parse_show_anon(char **args, char *payload, struct appctx *appctx, void *private) { char *msg = NULL; char *anon_mode = NULL; uint32_t c_key = appctx->cli_anon_key; if (!c_key) anon_mode = "Anonymized mode disabled"; else anon_mode = "Anonymized mode enabled"; if ( !((appctx->cli_level & ACCESS_LVL_MASK) < ACCESS_LVL_OPER) && c_key != 0) { cli_dynmsg(appctx, LOG_INFO, memprintf(&msg, "%s\nKey : %u\n", anon_mode, c_key)); } else { cli_dynmsg(appctx, LOG_INFO, memprintf(&msg, "%s\n", anon_mode)); } return 1; } /* parse a "set rate-limit" command. It always returns 1. */ static int cli_parse_set_ratelimit(char **args, char *payload, struct appctx *appctx, void *private) { int v; int *res; int mul = 1; if (!cli_has_level(appctx, ACCESS_LVL_ADMIN)) return 1; if (strcmp(args[2], "connections") == 0 && strcmp(args[3], "global") == 0) res = &global.cps_lim; else if (strcmp(args[2], "sessions") == 0 && strcmp(args[3], "global") == 0) res = &global.sps_lim; #ifdef USE_OPENSSL else if (strcmp(args[2], "ssl-sessions") == 0 && strcmp(args[3], "global") == 0) res = &global.ssl_lim; #endif else if (strcmp(args[2], "http-compression") == 0 && strcmp(args[3], "global") == 0) { res = &global.comp_rate_lim; mul = 1024; } else { return cli_err(appctx, "'set rate-limit' only supports :\n" " - 'connections global' to set the per-process maximum connection rate\n" " - 'sessions global' to set the per-process maximum session rate\n" #ifdef USE_OPENSSL " - 'ssl-sessions global' to set the per-process maximum SSL session rate\n" #endif " - 'http-compression global' to set the per-process maximum compression speed in kB/s\n"); } if (!*args[4]) return cli_err(appctx, "Expects an integer value.\n"); v = atoi(args[4]); if (v < 0) return cli_err(appctx, "Value out of range.\n"); *res = v * mul; /* Dequeues all of the listeners waiting for a resource */ dequeue_all_listeners(); return 1; } /* Parse a "wait