diff --git a/include/fluent-bit/flb_http_client.h b/include/fluent-bit/flb_http_client.h index 9e4bc814087..fd9059640a6 100644 --- a/include/fluent-bit/flb_http_client.h +++ b/include/fluent-bit/flb_http_client.h @@ -138,6 +138,7 @@ struct flb_http_client_response { size_t data_len; size_t data_size; size_t data_size_max; + int buffer_limit_reached; /* Response read failed at the configured limit */ }; /* It hold information about a possible HTTP proxy set by the caller */ diff --git a/plugins/out_loki/loki.c b/plugins/out_loki/loki.c index 04b70e372b3..8a89f992d40 100644 --- a/plugins/out_loki/loki.c +++ b/plugins/out_loki/loki.c @@ -31,6 +31,7 @@ #include #include +#include #include #include "loki.h" @@ -1892,6 +1893,114 @@ static int collect_tenant_groups(struct flb_loki *ctx, return 0; } +static size_t response_body_length(const char *start, const char *end, int base) +{ + unsigned long long length; + const char *digits = base == 10 ? "0123456789" : "0123456789abcdefABCDEF"; + + if (start == end || strspn(start, digits) != (size_t) (end - start)) { + return 0; + } + + errno = 0; + length = strtoull(start, NULL, base); + if (errno == ERANGE || length > SIZE_MAX) { + return 0; + } + + return (size_t) length; +} + +static int oversized_http_400(const struct flb_http_client_response *resp) +{ + const char *line = resp->data; + const char *line_end; + const char *p; + const char *value; + const char *value_end; + size_t name_len; + size_t length = 0; + int chunked = FLB_FALSE; + int http_11; + + if (!resp->buffer_limit_reached || resp->status != 400 || !resp->headers_end) { + return FLB_FALSE; + } + + line_end = strstr(line, "\r\n"); + if (!line_end || line_end - line < 13 || line_end > resp->headers_end - 4 || + memcmp(line, "HTTP/1.", 7) != 0 || (line[7] != '0' && line[7] != '1') || + memcmp(line + 8, " 400 ", 5) != 0) { + return FLB_FALSE; + } + http_11 = line[7] == '1'; + for (p = line + 13; p < line_end; p++) { + if (((unsigned char) *p < 0x20 && *p != '\t') || *p == 0x7f) { + return FLB_FALSE; + } + } + + /* Match complete field names and check for conflicting framing. */ + for (line = line_end + 2; line < resp->headers_end - 2; line = line_end + 2) { + line_end = strstr(line, "\r\n"); + if (!line_end || line_end > resp->headers_end - 4) { + return FLB_FALSE; + } + p = memchr(line, ':', line_end - line); + if (!p || flb_http_header_validate(line, p - line, p + 1, line_end - p - 1) != 0) { + return FLB_FALSE; + } + name_len = p - line; + value = p + 1; + value_end = line_end; + while (value < value_end && (*value == ' ' || *value == '\t')) { + value++; + } + while (value_end > value && (value_end[-1] == ' ' || value_end[-1] == '\t')) { + value_end--; + } + + if (name_len == 14 && strncasecmp(line, "Content-Length", name_len) == 0) { + if (length || chunked) { + return FLB_FALSE; + } + length = response_body_length(value, value_end, 10); + if (length == 0) { + return FLB_FALSE; + } + } + else if (name_len == 17 && strncasecmp(line, "Transfer-Encoding", name_len) == 0) { + if (length || chunked || !http_11 || value_end - value != 7 || + strncasecmp(value, "chunked", 7) != 0) { + return FLB_FALSE; + } + chunked = FLB_TRUE; + } + } + + line = resp->headers_end; + if (chunked) { + /* In the full-response read, a consumed chunk advances this cursor. */ + if (!resp->chunked_encoding || resp->content_length != -1 || + resp->chunk_processed_end != line || resp->chunked_trailer_pending) { + return FLB_FALSE; + } + line_end = strstr(line, "\r\n"); + if (!line_end) { + return FLB_FALSE; + } + length = response_body_length(line, line_end, 16); + line = line_end + 2; + } + else if (resp->chunked_encoding || resp->content_length <= 0 || + length != (size_t) resp->content_length) { + return FLB_FALSE; + } + + /* Exclude the reserved NUL and compare only body bytes. */ + return length > resp->data_size - 1 - (size_t) (line - resp->data); +} + static int send_loki_payload(struct flb_loki *ctx, flb_sds_t payload, flb_sds_t tenant_id, @@ -2076,6 +2185,11 @@ static int send_loki_payload(struct flb_loki *ctx, } } } + else if (oversized_http_400(&c->resp)) { + flb_plg_error(ctx->ins, "%s:%i, HTTP status=400 Not retrying (response buffer limit reached)", + ctx->tcp_host, ctx->tcp_port); + out_ret = FLB_ERROR; + } else { flb_plg_error(ctx->ins, "could not flush records to %s:%i (http_do=%i)", ctx->tcp_host, ctx->tcp_port, ret); diff --git a/src/flb_http_client.c b/src/flb_http_client.c index 8defd40e0b1..64e49f8b8b8 100644 --- a/src/flb_http_client.c +++ b/src/flb_http_client.c @@ -1888,6 +1888,7 @@ int flb_http_do_request(struct flb_http_client *c, size_t *bytes) size_t bytes_body = 0; char *tmp; + c->resp.buffer_limit_reached = FLB_FALSE; if (c->invalid_header) { return FLB_HTTP_ERROR; } @@ -2015,6 +2016,7 @@ int flb_http_get_response_data(struct flb_http_client *c, size_t bytes_consumed) int timeout; int remaining; + c->resp.buffer_limit_reached = FLB_FALSE; #ifdef __EMSCRIPTEN__ flb_error("[http_client] browser streaming responses are unsupported; use flb_http_do"); return FLB_HTTP_ERROR; @@ -2048,6 +2050,15 @@ int flb_http_get_response_data(struct flb_http_client *c, size_t bytes_consumed) ret = flb_http_buffer_increase(c, FLB_HTTP_DATA_CHUNK, &out_size); if (ret == -1) { + if (c->resp.data_size_max != 0 && + c->resp.data_size >= c->resp.data_size_max) { + now = time(NULL); + c->resp.buffer_limit_reached = + (c->u_conn == NULL || c->u_conn->net_error != ETIMEDOUT) && + (c->response_timeout <= 0 || now - c->ts_start < c->response_timeout) && + (c->read_idle_timeout <= 0 || now - c->last_read_ts < c->read_idle_timeout); + } + /* * We could not allocate more space, let the caller handle * this. @@ -2154,6 +2165,7 @@ int flb_http_do(struct flb_http_client *c, size_t *bytes) { int ret; + c->resp.buffer_limit_reached = FLB_FALSE; if (c->test_mode == FLB_TRUE) { return flb_http_stub_response(c); } @@ -2220,6 +2232,7 @@ int flb_http_do_with_oauth2(struct flb_http_client *c, size_t *bytes, { #ifdef __EMSCRIPTEN__ if (oauth2) { + c->resp.buffer_limit_reached = FLB_FALSE; flb_error("[http_client] OAuth2 is not supported by the browser transport"); return -1; } @@ -2230,6 +2243,7 @@ int flb_http_do_with_oauth2(struct flb_http_client *c, size_t *bytes, struct flb_connection *old_conn; struct flb_upstream *u; + c->resp.buffer_limit_reached = FLB_FALSE; if (!oauth2 || oauth2->cfg.enabled == FLB_FALSE) { return flb_http_do(c, bytes); } diff --git a/tests/integration/scenarios/out_loki/tests/test_out_loki_001.py b/tests/integration/scenarios/out_loki/tests/test_out_loki_001.py index 6e5e3de06e9..b3ce68e351d 100644 --- a/tests/integration/scenarios/out_loki/tests/test_out_loki_001.py +++ b/tests/integration/scenarios/out_loki/tests/test_out_loki_001.py @@ -1,7 +1,10 @@ import json import os +from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path import tempfile +import threading +import time import requests import pytest @@ -195,3 +198,141 @@ def test_out_loki_rejects_injected_tenant_header(tenant): headers = {key.lower(): value for key, value in data_storage["requests"][0]["headers"].items()} assert headers["x-scope-orgid"] == "safe-tenant" assert "x-injected-by" not in headers + + +BAD_REQUEST = b"HTTP/1.1 400 Bad Request\r\n" +LENGTH = BAD_REQUEST + b"Content-Length: " +CHUNKED = BAD_REQUEST + b"Transfer-Encoding: chunked\r\n\r\n" +RESPONSE_CAPACITY = 4096 - 1 # The response buffer reserves a NUL byte. +FIT_LENGTH = RESPONSE_CAPACITY - len(LENGTH + b"0000\r\n\r\n") +FIT_CHUNK = RESPONSE_CAPACITY - len(CHUNKED + b"000\r\n") + + +def fixed_response(size): + return LENGTH + f"{size}\r\n\r\n".encode() + b"x" * size + + +def chunked_response(size): + return CHUNKED + f"{size:X}\r\n".encode() + b"x" * size + b"\r\n0\r\n\r\n" + + +@pytest.mark.parametrize(("wire", "split", "outcome"), [ + pytest.param(fixed_response(3), 0, "ordinary", id="ordinary-400"), + pytest.param(fixed_response(8192), 0, "oversized", id="oversized-length"), + pytest.param(fixed_response(FIT_LENGTH - 1), 0, "ordinary", id="length-one-byte-free"), + pytest.param(fixed_response(FIT_LENGTH), RESPONSE_CAPACITY - 1, "exact-fit", id="length-exact-fit"), + pytest.param(fixed_response(FIT_LENGTH + 1), RESPONSE_CAPACITY - 1, + "oversized", id="length-one-byte-over"), + pytest.param(chunked_response(0x2A0B), len(CHUNKED) + 2, "oversized", id="oversized-first-chunk"), + pytest.param(chunked_response(FIT_CHUNK), 0, "retry", id="chunk-body-exact-fit"), + pytest.param(chunked_response(FIT_CHUNK), RESPONSE_CAPACITY - 1, + "retry", id="chunk-body-exact-fit-split"), + pytest.param(chunked_response(FIT_CHUNK + 1), 0, "oversized", id="chunk-body-one-byte-over"), + pytest.param(chunked_response(FIT_CHUNK + 1), RESPONSE_CAPACITY - 1, + "oversized", id="chunk-body-one-byte-over-split"), + pytest.param(CHUNKED + b"2000;foo=bar\r\n" + b"x" * 8192, 0, "retry", id="chunk-extension"), + pytest.param(CHUNKED + b"2000;foo=\r\n" + b"x" * 8192, + 0, "retry", id="chunk-extension-missing-value"), + pytest.param(CHUNKED + b"1\r\na\r\n2000\r\n" + b"x" * 8192, 0, "retry", id="previous-chunk"), + pytest.param(CHUNKED + b" 2000\r\n" + b"x" * 8192, 0, "retry", id="chunk-size-leading-space"), + pytest.param(CHUNKED + b"\t2000\r\n" + b"x" * 8192, 0, "retry", id="chunk-size-leading-tab"), + pytest.param(CHUNKED + b"2000 \t\r\n" + b"x" * 8192, 0, "retry", id="chunk-size-whitespace"), + pytest.param(CHUNKED + b"a" * 4096, 0, "retry", id="incomplete-chunk-size"), + pytest.param(CHUNKED + b"0\r\nTrailer: " + b"x" * 4096, 0, "retry", id="incomplete-trailer"), + pytest.param(LENGTH + b"8192\r\nContent-Length: 8192\r\n\r\n" + b"x" * 8192, + 0, "retry", id="duplicate-length"), + pytest.param(LENGTH + b"8192\r\nTransfer-Encoding: chunked\r\n\r\n" + b"x" * 8192, + 0, "retry", id="conflicting-framing"), + pytest.param(BAD_REQUEST + b"Transfer-Encoding: chunked\r\nTransfer-Encoding: identity\r\n\r\n" + + b"2000\r\n" + b"x" * 8192, 0, "retry", id="duplicate-transfer-encoding"), + pytest.param(LENGTH + b"8192, 8192\r\n\r\n" + b"x" * 8192, 0, "retry", id="length-list"), + pytest.param(LENGTH + b"+8192\r\n\r\n" + b"x" * 8192, 0, "retry", id="signed-length"), + pytest.param(BAD_REQUEST + b"X-Original-Content-Length: 9000\r\n" + + fixed_response(8192)[len(BAD_REQUEST):], 0, "retry", id="legacy-length-mismatch"), + pytest.param(BAD_REQUEST + b"X-Original-Content-Length: 8192\r\n\r\n" + b"x" * 8192, + 0, "retry", id="close-delimited-with-lookalike-field"), + pytest.param(LENGTH + b"8192\r\nUnfinished: " + b"x" * 4096, 0, "retry", id="incomplete-headers"), + pytest.param(fixed_response(8192).replace(b"400 Bad", b"400XBad", 1), + 0, "retry", id="invalid-status-line"), + pytest.param(chunked_response(8192).replace(b"HTTP/1.1", b"HTTP/1.0", 1), + 0, "retry", id="http-1.0-chunked"), + pytest.param(fixed_response(8192).replace(b"400 Bad Request", b"503 Unavailable", 1), + 0, "retry", id="oversized-503"), + pytest.param(b"HTTP/1.1 429 Too Many Requests\r\nContent-Length: 0\r\n\r\n", + 0, "retry", id="ordinary-429"), + pytest.param(b"", 0, "retry", id="connection-closed-without-response"), +]) +def test_out_loki_response_buffer_limit(tmp_path, wire, split, outcome): + payloads = [] + terminal_markers = { + "ordinary": "HTTP status=400 Not retrying.", + "oversized": "response buffer limit reached", + "retry": "cannot be retried", + } + + class LokiReceiver(BaseHTTPRequestHandler): + def do_POST(self): + payloads.append(self.rfile.read(int(self.headers["Content-Length"]))) + self.close_connection = True + try: + if outcome == "exact-fit" and len(payloads) > 1: + # Keep the last byte out of the retry so it reaches the same buffer limit. + self.connection.sendall(wire[:-1]) + return + if split: + self.connection.sendall(wire[:split]) + time.sleep(0.25) + self.connection.sendall(wire[split:]) + except (BrokenPipeError, ConnectionResetError): + pass # A capped read closes the connection before draining the response. + + with HTTPServer(("127.0.0.1", 0), LokiReceiver) as server: + config = { + "service": { + "flush": 0.2, "grace": 1, "scheduler.base": 1, "scheduler.cap": 1, + "http_server": "on", "http_listen": "127.0.0.1", + "http_port": "${FLUENT_BIT_HTTP_MONITORING_PORT}", + }, + "pipeline": { + "inputs": [{"name": "dummy", "samples": 1, "dummy": '{"msg":"synthetic"}'}], + "outputs": [{ + "name": "loki", "match": "*", "host": "127.0.0.1", "port": server.server_port, + "buffer_size": "4096", "retry_limit": 1, "net.io_timeout": 2, + }], + }, + } + config_path = tmp_path / "loki.yaml" + config_path.write_text(yaml.safe_dump(config), encoding="utf-8") + service = FluentBitTestService(str(config_path)) + receiver = threading.Thread(target=server.serve_forever) + receiver.start() + try: + service.start() + + log_path = Path(service.flb.log_file) + + def has_terminal_outcome(): + log = log_path.read_text(encoding="utf-8", errors="replace") + return any(marker in log for marker in terminal_markers.values()) + + service.wait_for_condition( + has_terminal_outcome, timeout=30 if memory_check_enabled() else 10, + interval=0.1, description="terminal Loki output result", + ) + finally: + try: + service.stop() + finally: + server.shutdown() + receiver.join() + + log = log_path.read_text(encoding="utf-8", errors="replace") + observed = [result for result, marker in terminal_markers.items() if marker in log] + if outcome == "exact-fit": + assert observed in (["ordinary"], ["retry"]), log + if observed == ["retry"]: + assert log.count("cannot increase buffer") == 2, log + else: + assert observed == [outcome], log + assert len(payloads) == (2 if observed == ["retry"] else 1), (observed, len(payloads), log) + assert all(payload == payloads[0] for payload in payloads) diff --git a/tests/internal/http_client.c b/tests/internal/http_client.c index f52b20da53a..c92bade7057 100644 --- a/tests/internal/http_client.c +++ b/tests/internal/http_client.c @@ -1,5 +1,7 @@ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +#include + #include #include #include @@ -1114,6 +1116,98 @@ void test_http_timeout_setters_preserve_upstream_io_timeout() test_ctx_destroy(ctx); } +static void test_http_response_buffer_limit(void) +{ + size_t sent = 0; + size_t header_size; + struct test_ctx *ctx; + struct flb_http_client *c; + struct flb_http_client_response *resp; +#ifndef FLB_SYSTEM_WINDOWS + int pair[2]; + const char next_response[] = "HTTP/1.1 204 No Content\r\n\r\n"; +#endif + + ctx = test_ctx_create(); + TEST_ASSERT(ctx != NULL); + c = flb_http_client(ctx->u_conn, FLB_HTTP_POST, "/", NULL, 0, + "127.0.0.1", 80, NULL, 0); + TEST_ASSERT(c != NULL); + resp = &c->resp; + TEST_CHECK(resp->buffer_limit_reached == FLB_FALSE); + + append_response_fragment(c, "HTTP/1.1 400 Bad Request\r\nContent-Length: 8192\r\n\r\n"); + header_size = resp->data_len; + resp->data_len = resp->data_size - 2; + memset(resp->data + header_size, 'x', resp->data_len - header_size); + resp->data[resp->data_len] = '\0'; + TEST_CHECK(flb_http_client_process_response_buffer(c) == FLB_HTTP_MORE); + + ctx->u_conn->net_error = -1; + ctx->u_conn->recycle = FLB_TRUE; + TEST_CHECK(flb_http_get_response_data(c, 0) == FLB_HTTP_ERROR); + TEST_CHECK(resp->buffer_limit_reached == FLB_TRUE); + TEST_CHECK(ctx->u_conn->recycle == FLB_FALSE); + TEST_CHECK(resp->data_len == resp->data_size - 2); + + /* A recorded I/O timeout also excludes an otherwise identical cap failure. */ + ctx->u_conn->net_error = ETIMEDOUT; + ctx->u_conn->recycle = FLB_TRUE; + TEST_CHECK(flb_http_get_response_data(c, 0) == FLB_HTTP_ERROR); + TEST_CHECK(resp->buffer_limit_reached == FLB_FALSE); + TEST_CHECK(ctx->u_conn->recycle == FLB_FALSE); + + ctx->u_conn->net_error = -1; + ctx->u_conn->recycle = FLB_TRUE; + TEST_CHECK(flb_http_get_response_data(c, 0) == FLB_HTTP_ERROR); + TEST_CHECK(resp->buffer_limit_reached == FLB_TRUE); + TEST_CHECK(ctx->u_conn->recycle == FLB_FALSE); + + /* Expired budgets still take precedence for the failure marker. */ + TEST_CHECK(flb_http_set_response_timeout(c, 1) == 0); + c->ts_start = time(NULL) - 1; + TEST_CHECK(flb_http_get_response_data(c, 0) == FLB_HTTP_ERROR); + TEST_CHECK(resp->buffer_limit_reached == FLB_FALSE); + TEST_CHECK(flb_http_set_response_timeout(c, 0) == 0); + TEST_CHECK(flb_http_set_read_idle_timeout(c, 1) == 0); + c->last_read_ts = time(NULL) - 1; + TEST_CHECK(flb_http_get_response_data(c, 0) == FLB_HTTP_ERROR); + TEST_CHECK(resp->buffer_limit_reached == FLB_FALSE); + + /* A timeout with room to read must also leave the marker clear. */ + resp->data_len = header_size; + resp->data[header_size] = '\0'; + TEST_CHECK(flb_http_get_response_data(c, 0) == FLB_HTTP_ERROR); + TEST_CHECK(resp->buffer_limit_reached == FLB_FALSE); + TEST_CHECK(flb_http_set_read_idle_timeout(c, 0) == 0); + + c->invalid_header = FLB_TRUE; + resp->buffer_limit_reached = FLB_TRUE; + TEST_CHECK(flb_http_do_request(c, &sent) == FLB_HTTP_ERROR); + TEST_CHECK(resp->buffer_limit_reached == FLB_FALSE); + c->invalid_header = FLB_FALSE; + +#ifndef FLB_SYSTEM_WINDOWS + /* A new connection can carry the next request on the same client. */ + TEST_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); + ctx->u_conn->fd = pair[0]; + ctx->u_conn->stream = &ctx->u->base; + flb_stream_disable_async_mode(&ctx->u->base); + TEST_ASSERT(send(pair[1], next_response, sizeof(next_response) - 1, 0) == + sizeof(next_response) - 1); + resp->buffer_limit_reached = FLB_TRUE; + TEST_CHECK(flb_http_do(c, &sent) == 0); + TEST_CHECK(sent > 0); + TEST_CHECK(resp->buffer_limit_reached == FLB_FALSE); + TEST_CHECK(resp->status == 204); + flb_socket_close(pair[0]); + flb_socket_close(pair[1]); +#endif + + flb_http_client_destroy(c); + test_ctx_destroy(ctx); +} + static void test_http_request_target_validation(void) { struct test_ctx *ctx; @@ -1328,6 +1422,7 @@ TEST_LIST = { { "https_ipv6_zone_id_default_port_host_header", test_https_ipv6_zone_id_default_port_host_header}, { "https_ipv6_zone_id_non_standard_port_host_header", test_https_ipv6_zone_id_non_standard_port_host_header}, { "response_header_lookup", test_http_response_header_lookup}, + { "response_buffer_limit", test_http_response_buffer_limit}, { "response_chunked_trailers", test_http_response_chunked_trailers}, { "response_chunked_incremental", test_http_response_chunked_incremental}, { "response_chunked_invalid_trailer", test_http_response_chunked_invalid_trailer},