PR #26170 opened by Jun Zhao (mypopydev)
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26170
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26170.patch

An unknown-length HTTP reply has filesize set to UINT64_MAX. Since the 2016 
unsigned conversion dropped the signed-length check, a clean TCP close was 
treated as premature termination against UINT64_MAX and failed with EIO. http.c 
now guards length comparisons with != UINT64_MAX so a clean close yields EOF, 
while truncated replies with a concrete length still fail with EIO.

CurlContext had no "method" AVOption, so -method HEAD -prefer_libcurl 1 
silently fell back to GET. libcurl now accepts the option and sets 
CURLOPT_NOBODY for HEAD, avoiding the CURLE_PARTIAL_FILE retry loop from 
expecting a body. It also suppresses Range headers, parses Content-Length from 
response headers, and returns clean EOF without retry on close.

FATE tests cover both fixes. The mock HTTP server adds close-delimited 
responses without Content-Length that verify clean EOF, while keeping 
declared-length truncation covered. A separate FATE target tests libcurl HEAD 
under CONFIG_LIBCURL_PROTOCOL.


>From 46281605d1282ab065f3d96da85c147bcceaa105 Mon Sep 17 00:00:00 2001
From: Jun Zhao <[email protected]>
Date: Wed, 18 Nov 2026 07:06:55 +0800
Subject: [PATCH 1/3] avformat/http: treat unknown-length clean EOF as EOF, not
 EIO

A reply without Content-Length has filesize == UINT64_MAX.  Since the
2016 unsigned conversion (2a05c8f813) dropped the signed-length guard,
a clean close is reported as "Stream ends prematurely ... should be
18446744073709551615" and fails with AVERROR(EIO).

Guard the three length comparisons in http_buf_read() and
http_read_stream() on != UINT64_MAX.  Replies with a concrete length
still return EIO on truncation, and the HEAD no-body handling of
PR #26102 stays necessary.

An unknown-length stream is no longer treated as permanently premature
in the reconnect loop; reconnect_at_eof and reconnect_streamed are
unaffected.

Signed-off-by: Jun Zhao <[email protected]>
---
 libavformat/http.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/libavformat/http.c b/libavformat/http.c
index 786201c4ae4..3d45498a197 100644
--- a/libavformat/http.c
+++ b/libavformat/http.c
@@ -2020,7 +2020,8 @@ static int http_buf_read(URLContext *h, uint8_t *buf, int 
size)
             return AVERROR(EAGAIN); /* reached end of content range */
         len = ffurl_read(s->hd, buf, size);
         if ((!len || len == AVERROR_EOF) &&
-            (!s->willclose || s->chunksize == UINT64_MAX) && s->off < 
target_end) {
+            (!s->willclose || s->chunksize == UINT64_MAX) &&
+            target_end != UINT64_MAX && s->off < target_end) {
             av_log(h, AV_LOG_ERROR,
                    "Stream ends prematurely at %"PRIu64", should be 
%"PRIu64"\n",
                    s->off, target_end
@@ -2110,8 +2111,11 @@ static int http_read_stream(URLContext *h, uint8_t *buf, 
int size)
     if (!s->is_connected_server && s->method && !av_strcasecmp(s->method, 
"HEAD"))
         return AVERROR_EOF;
 
-    if (!s->hd)
-        return s->off < requested_end(s) ? AVERROR(EIO) : AVERROR_EOF;
+    if (!s->hd) {
+        uint64_t file_end = requested_end(s);
+        return file_end != UINT64_MAX && s->off < file_end
+               ? AVERROR(EIO) : AVERROR_EOF;
+    }
 
 #if CONFIG_ZLIB
     if (s->compressed)
@@ -2123,7 +2127,8 @@ retry:
     while (read_ret < 0) {
         uint64_t target = h->is_streamed ? 0 : s->off;
         uint64_t file_end = requested_end(s);
-        bool is_premature = file_end > 0 && s->off < file_end;
+        bool is_premature = file_end > 0 && file_end != UINT64_MAX &&
+                            s->off < file_end;
 
         if (read_ret == AVERROR_EXIT)
             break;
-- 
2.54.0


>From 67c9d0e07060bc10e015b7c9e6eddf1b7b805a79 Mon Sep 17 00:00:00 2001
From: Jun Zhao <[email protected]>
Date: Wed, 18 Nov 2026 07:08:12 +0800
Subject: [PATCH 2/3] avformat/libcurl: support the HTTP method option and HEAD

CurlContext had no "method" AVOption, so -method HEAD -prefer_libcurl 1
was silently dropped and sent a GET.  Add the option (mirroring http.c)
and use CURLOPT_NOBODY for HEAD; CUSTOMREQUEST="HEAD" alone would still
expect a body and trigger CURLE_PARTIAL_FILE retries.  Other methods
are passed through CURLOPT_CUSTOMREQUEST.

HEAD also suppresses CURLOPT_RANGE and completes with a clean EOF,
without the recoverable-error retry path.  libcurl reports
CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = -1 for a bodyless HEAD, so
header_callback() reads Content-Length from the header line to keep
avio_size()/AVSEEK_SIZE working.

Signed-off-by: Jun Zhao <[email protected]>
---
 libavformat/libcurl.c | 61 +++++++++++++++++++++++++++++++++++++++----
 1 file changed, 56 insertions(+), 5 deletions(-)

diff --git a/libavformat/libcurl.c b/libavformat/libcurl.c
index fc487602db9..739358dfac6 100644
--- a/libavformat/libcurl.c
+++ b/libavformat/libcurl.c
@@ -118,6 +118,7 @@ struct CurlContext {
 
     /* AVOptions. */
     char           *user_agent;
+    char           *method;      /* client HTTP method (GET/HEAD/...), or NULL 
*/
     char           *referer;
     char           *headers;
     char           *http_proxy;
@@ -154,12 +155,14 @@ struct CurlContext {
     int             icy_block_filled;
     uint8_t         icy_block[ICY_MAX_BLOCK + 1];
 
-    /* Producer bookkeeping, touched only by the loop thread. */
+    /* Producer bookkeeping, touched only by the loop thread.  no_body is
+     * set once by setup_curl() before the handle is added, then read-only. */
     int             active;          /* currently added to the multi */
     int64_t         request_start;   /* absolute offset the current request 
began at */
     int64_t         request_received;/* bytes delivered in the current request 
*/
     int64_t         request_end;     /* expected end of request, or -1 if 
unknown */
     int             is_initial;      /* using reduced request size */
+    int             no_body;         /* HEAD request: CURLOPT_NOBODY is set */
     int             seek_queued;     /* soft seeking; drain remaining bytes 
until done */
 
     /* Per-response-block header scratch, loop thread only. */
@@ -522,6 +525,22 @@ static size_t header_callback(char *ptr, size_t size, 
size_t nitems, void *userd
         parse_content_range(c, ptr + 14);
         return len;
     }
+    if (c->no_body && av_strncasecmp(ptr, "Content-Length:", 15) == 0) {
+        /* A HEAD reply has no download body, so libcurl reports
+         * CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = -1.  Keep the declared size
+         * from the header so avio_size()/AVSEEK_SIZE still works. */
+        char line[64], *end;
+        size_t l = FFMIN(len, sizeof(line) - 1);
+        long long v;
+
+        memcpy(line, ptr, l);
+        line[l] = 0;
+        errno = 0;
+        v = strtoll(line + 15, &end, 10);
+        if (!errno && end != line + 15 && v >= 0 && v <= INT64_MAX)
+            c->hdr_content_length = v;
+        return len;
+    }
     if (av_strncasecmp(ptr, "icy-metaint:", 12) == 0) {
         c->hdr_icy_metaint = parse_metaint(ptr + 12, len - 12);
         return len;
@@ -547,8 +566,10 @@ static size_t header_callback(char *ptr, size_t size, 
size_t nitems, void *userd
         return len;
 
     curl_off_t cl = -1;
-    if (curl_easy_getinfo(c->easy, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &cl) == 
CURLE_OK)
-        c->hdr_content_length = cl >= 0 ? cl : -1;
+    /* Do not clobber a size parsed from the headers for a bodyless HEAD. */
+    if (curl_easy_getinfo(c->easy, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &cl) == 
CURLE_OK &&
+        cl >= 0)
+        c->hdr_content_length = cl;
 
     pthread_mutex_lock(&c->mutex);
     if (status >= 200 && status < 300) {
@@ -676,7 +697,7 @@ static void start_request(CurlContext *c)
         return;
     }
 
-    if (!c->probed || c->seekable) {
+    if (!c->no_body && (!c->probed || c->seekable)) {
         int64_t start = c->request_start;
         int64_t request_size = c->request_size;
         if (c->is_initial && c->initial_request_size > 0)
@@ -780,6 +801,24 @@ static void on_done(CurlContext *c, CURLcode code)
     if (aborted)
         return;
 
+    if (c->no_body) {
+        /* A HEAD reply carries no body.  Do not restart the request or
+         * escalate an empty transfer to EIO ("Server sent back no data at
+         * offset"), and do not treat the clean EOF as a recoverable error. */
+        pthread_mutex_lock(&c->mutex);
+        if (code == CURLE_OK && c->stream_ok) {
+            c->status      = AVERROR_EOF;
+            c->curl_status = CURLE_OK;
+        } else if (!c->status) {
+            c->loop->num_errors++;
+            update_status_locked(c, code == CURLE_OK ? AVERROR(EIO)
+                                                     : 
curlcode_to_averror(code), code);
+        }
+        pthread_cond_broadcast(&c->cond);
+        pthread_mutex_unlock(&c->mutex);
+        return;
+    }
+
     if (c->seek_queued) {
         /* previous soft seek drain finished; can start new request now */
         c->seek_queued = 0;
@@ -1296,6 +1335,17 @@ static int setup_curl(CurlContext *c)
 
     if (c->user_agent && c->user_agent[0])
         CURL_SETOPT(CURLOPT_USERAGENT, c->user_agent);
+    if (c->method && c->method[0]) {
+        if (!av_strcasecmp(c->method, "HEAD")) {
+            /* NOBODY issues HEAD and skips the body.  CUSTOMREQUEST="HEAD"
+             * alone would leave curl expecting Content-Length bytes and
+             * raise CURLE_PARTIAL_FILE, which is retryable here. */
+            c->no_body = 1;
+            CURL_SETOPT(CURLOPT_NOBODY, 1L);
+        } else {
+            CURL_SETOPT(CURLOPT_CUSTOMREQUEST, c->method);
+        }
+    }
     if (c->http_proxy && c->http_proxy[0])
         CURL_SETOPT(CURLOPT_PROXY, c->http_proxy);
 
@@ -1600,7 +1650,7 @@ static int libcurl_read(URLContext *h, unsigned char 
*buf, int size)
         }
 
         if (c->status) {
-            if (c->seekable && is_recoverable(c->curl_status))
+            if (c->seekable && !c->no_body && is_recoverable(c->curl_status))
                 return retry_request_locked(h, nonblock);
             if (c->status == AVERROR_EOF && c->icy_block_len >= 0)
                 av_log(h, AV_LOG_WARNING,
@@ -1720,6 +1770,7 @@ static int libcurl_get_short_seek(URLContext *h)
 #define E AV_OPT_FLAG_ENCODING_PARAM
 static const AVOption options[] = {
     { "user_agent", "override User-Agent header", OFFSET(user_agent), 
AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
+    { "method", "Override the HTTP method used for the request", 
OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
     { "referer", "override Referer header", OFFSET(referer), 
AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
     { "headers", "set custom HTTP headers, can override built in default 
headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
     { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), 
AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
-- 
2.54.0


>From fd2f2f5a08a48a5631792fcbf74a27c4207e3bb4 Mon Sep 17 00:00:00 2001
From: Jun Zhao <[email protected]>
Date: Wed, 18 Nov 2026 07:14:58 +0800
Subject: [PATCH 3/3] avformat/tests/http_nobody: cover clean EOF and libcurl
 HEAD

Use MSG_NOSIGNAL in send_all().  Add two close-delimited replies without
Content-Length: before the http.c fix they returned EIO with the
UINT64_MAX diagnostic, now they yield clean EOF (and still deliver the
3-byte body).  get_lie keeps its EIO so declared-length truncation
stays covered.

Add a libcurl HEAD case in its own group, FATE target and ref file,
gated on CONFIG_LIBCURL_PROTOCOL; a shared ref would diverge between
libcurl-enabled and disabled builds.  The FATE CMD sets NO_PROXY so a
host proxy cannot hijack the loopback request.

Signed-off-by: Jun Zhao <[email protected]>
---
 libavformat/Makefile             |  3 ++-
 libavformat/tests/http_nobody.c  | 42 ++++++++++++++++++++++++--------
 tests/fate/libavformat.mak       |  4 +++
 tests/ref/fate/http-curl-head    |  1 +
 tests/ref/fate/http-head-no-body |  3 +++
 5 files changed, 42 insertions(+), 11 deletions(-)
 create mode 100644 tests/ref/fate/http-curl-head

diff --git a/libavformat/Makefile b/libavformat/Makefile
index 8c1b93e12a4..ce9baba41fe 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -791,9 +791,10 @@ FIFO-MUXER-TESTPROGS-$(CONFIG_NETWORK)   += fifo_muxer
 TESTPROGS-$(CONFIG_FIFO_MUXER)           += $(FIFO-MUXER-TESTPROGS-yes)
 TESTPROGS-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += rtmpdh
 TESTPROGS-$(CONFIG_HTTP_PROTOCOL)        += http
-# http_nobody covers both the http and httpproxy read paths.
+# http_nobody covers the http, httpproxy and libcurl read paths.
 HTTP_NOBODY_TESTPROG-$(CONFIG_HTTP_PROTOCOL)      = http_nobody
 HTTP_NOBODY_TESTPROG-$(CONFIG_HTTPPROXY_PROTOCOL) = http_nobody
+HTTP_NOBODY_TESTPROG-$(CONFIG_LIBCURL_PROTOCOL)   = http_nobody
 TESTPROGS                                       += $(HTTP_NOBODY_TESTPROG-yes)
 TESTPROGS-$(CONFIG_NETWORK)              += noproxy
 TESTPROGS-$(CONFIG_SRTP)                 += srtp
diff --git a/libavformat/tests/http_nobody.c b/libavformat/tests/http_nobody.c
index 4bcc9d8bbcc..8054ad7bb4f 100644
--- a/libavformat/tests/http_nobody.c
+++ b/libavformat/tests/http_nobody.c
@@ -1,9 +1,10 @@
 /*
  * Copyright (c) 2026 Jun Zhao
  *
- * Regression tests for HTTP / httpproxy premature-end handling (issue #26071).
- * Expected output lives in tests/ref/fate/http-head-no-body and
- * tests/ref/fate/httpproxy-tunnel-eof.
+ * Regression tests for HTTP / httpproxy premature-end handling (issue #26071),
+ * unknown-length clean EOF and libcurl HEAD.
+ * Expected output lives in tests/ref/fate/http-head-no-body,
+ * tests/ref/fate/httpproxy-tunnel-eof and tests/ref/fate/http-curl-head.
  *
  * This file is part of FFmpeg.
  *
@@ -68,6 +69,18 @@ static const char head_reply[] =
 static const char lie_reply[]     = GET_HEADER;
 static const char connect_reply[] = "HTTP/1.1 200 OK\r\nconnection: 
close\r\n\r\n";
 
+/* Unknown-length replies ending in a clean close: no Content-Length, so
+ * filesize stays UINT64_MAX.  These must yield EOF, not a premature-end EIO. 
*/
+static const char close_reply[] =
+    "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
+static const char close_body_reply[] =
+    "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nABC";
+
+/* HEAD reply for the libcurl protocol: a body-less response with a declared
+ * resource size, used to verify -method HEAD is no longer dropped. */
+static const char curl_head_reply[] =
+    "HTTP/1.1 200 OK\r\nContent-Length: 1150\r\nConnection: close\r\n\r\n";
+
 /* CONNECT 200 header and initial tunnel payload sent together in an attempt
  * to exercise forwarding of bytes buffered during header parsing, while still
  * verifying full payload delivery across short transfers. */
@@ -75,7 +88,7 @@ static const char coalesced_reply[] = "HTTP/1.1 200 
OK\r\n\r\n" MARK;
 
 static char body_reply[sizeof(GET_HEADER) - 1 + BODY_SIZE];
 
-enum { GROUP_HTTP = 1, GROUP_PROXY = 2 };
+enum { GROUP_HTTP = 1, GROUP_PROXY = 2, GROUP_LIBCURL = 4 };
 enum { PRINT_NONE, PRINT_ENDS, PRINT_TEXT };
 
 typedef struct TestCase {
@@ -111,7 +124,7 @@ static void set_timeouts(int fd)
 static int send_all(int fd, const char *buf, int len)
 {
     for (int sent = 0; sent < len;) {
-        int r = send(fd, buf + sent, len - sent, 0);
+        int r = send(fd, buf + sent, len - sent, MSG_NOSIGNAL);
         if (r < 0 && ff_neterrno() == AVERROR(EINTR))
             continue;
         if (r <= 0)
@@ -231,14 +244,16 @@ static void run_case(const TestCase *tc)
     }
 
     snprintf(url, sizeof(url), tc->url_fmt, srv.port);
-    if (tc->group == GROUP_HTTP)
+    if (tc->group != GROUP_PROXY)
         av_dict_set(&opts, "http_proxy", "", 0);
+    if (tc->group == GROUP_LIBCURL)
+        av_dict_set(&opts, "prefer_libcurl", "1", 0);
     av_dict_set_int(&opts, "rw_timeout", TIMEOUT_US, 0);
     if (tc->method)
         av_dict_set(&opts, "method", tc->method, 0);
 
     open_ret = ffurl_open_whitelist(&uc, url, AVIO_FLAG_READ, &int_cb, &opts,
-                                    "http,httpproxy,tcp", NULL, NULL);
+                                    "http,httpproxy,tcp,libcurl", NULL, NULL);
     av_dict_free(&opts);
     if (open_ret >= 0) {
         size_ret = ffurl_seek(uc, 0, AVSEEK_SIZE);
@@ -267,18 +282,25 @@ static const TestCase cases[] = {
       NULL,   body_reply,      sizeof(body_reply),          PRINT_ENDS },
     { "get_lie",       GROUP_HTTP,  "http://127.0.0.1:%d/x";,
       NULL,   lie_reply,       sizeof(lie_reply) - 1,       PRINT_NONE },
+    { "get_close",      GROUP_HTTP,  "http://127.0.0.1:%d/x";,
+      NULL,   close_reply,     sizeof(close_reply) - 1,     PRINT_NONE },
+    { "get_close_body", GROUP_HTTP,  "http://127.0.0.1:%d/x";,
+      NULL,   close_body_reply, sizeof(close_body_reply) - 1, PRINT_TEXT },
     { "proxy_close",   GROUP_PROXY, "httpproxy://127.0.0.1:%d/example.com:443",
       NULL,   connect_reply,   sizeof(connect_reply) - 1,   PRINT_NONE },
     { "proxy_residue", GROUP_PROXY, "httpproxy://127.0.0.1:%d/example.com:443",
       NULL,   coalesced_reply, sizeof(coalesced_reply) - 1, PRINT_TEXT },
+    { "curl_head",     GROUP_LIBCURL, "http://127.0.0.1:%d/x";,
+      "HEAD", curl_head_reply, sizeof(curl_head_reply) - 1, PRINT_NONE },
 };
 
 int main(int argc, char **argv)
 {
     const char *group = argc > 1 ? argv[1] : "all";
-    int mask = !strcmp(group, "all")   ? (GROUP_HTTP | GROUP_PROXY) :
-               !strcmp(group, "http")  ? GROUP_HTTP :
-               !strcmp(group, "proxy") ? GROUP_PROXY : 0;
+    int mask = !strcmp(group, "all")     ? (GROUP_HTTP | GROUP_PROXY) :
+               !strcmp(group, "http")    ? GROUP_HTTP :
+               !strcmp(group, "proxy")   ? GROUP_PROXY :
+               !strcmp(group, "libcurl") ? GROUP_LIBCURL : 0;
 
     if (!mask) {
         fprintf(stderr, "Unknown test group: %s\n", group);
diff --git a/tests/fate/libavformat.mak b/tests/fate/libavformat.mak
index 4beb17dd1ef..42097049129 100644
--- a/tests/fate/libavformat.mak
+++ b/tests/fate/libavformat.mak
@@ -64,6 +64,7 @@ fate-noproxy: CMD = run libavformat/tests/noproxy$(EXESUF)
 # Self-contained loopback test; it needs no samples and no external network.
 FATE_HTTP_NOBODY-$(CONFIG_HTTP_PROTOCOL)      += fate-http-head-no-body
 FATE_HTTP_NOBODY-$(CONFIG_HTTPPROXY_PROTOCOL) += fate-httpproxy-tunnel-eof
+FATE_HTTP_NOBODY-$(CONFIG_LIBCURL_PROTOCOL)   += fate-http-curl-head
 FATE_HTTP_NOBODY_RUN-$(HAVE_LOOPBACK)         += $(FATE_HTTP_NOBODY-yes)
 FATE_LIBAVFORMAT-$(HAVE_PTHREADS)             += $(FATE_HTTP_NOBODY_RUN-yes)
 
@@ -73,6 +74,9 @@ fate-http-head-no-body: CMD = run 
libavformat/tests/http_nobody$(EXESUF) http
 fate-httpproxy-tunnel-eof: libavformat/tests/http_nobody$(EXESUF)
 fate-httpproxy-tunnel-eof: CMD = run libavformat/tests/http_nobody$(EXESUF) 
proxy
 
+fate-http-curl-head: libavformat/tests/http_nobody$(EXESUF)
+fate-http-curl-head: CMD = NO_PROXY=127.0.0.1,localhost run 
libavformat/tests/http_nobody$(EXESUF) libcurl
+
 FATE_LIBAVFORMAT-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += fate-rtmpdh
 fate-rtmpdh: libavformat/tests/rtmpdh$(EXESUF)
 fate-rtmpdh: CMD = run libavformat/tests/rtmpdh$(EXESUF)
diff --git a/tests/ref/fate/http-curl-head b/tests/ref/fate/http-curl-head
new file mode 100644
index 00000000000..316fb43f79d
--- /dev/null
+++ b/tests/ref/fate/http-curl-head
@@ -0,0 +1 @@
+curl_head: open=0 size=1150 read=EOF server_failed=0
diff --git a/tests/ref/fate/http-head-no-body b/tests/ref/fate/http-head-no-body
index 08adc9862ec..3c6f718b320 100644
--- a/tests/ref/fate/http-head-no-body
+++ b/tests/ref/fate/http-head-no-body
@@ -2,3 +2,6 @@ head: open=0 size=1150 read=EOF server_failed=0
 get_body: open=0 size=1150 read=1150 server_failed=0
 body ends: X X
 get_lie: open=0 size=1150 read=EIO server_failed=0
+get_close: open=0 size=ENOSYS read=EOF server_failed=0
+get_close_body: open=0 size=ENOSYS read=3 server_failed=0
+residue: ABC
-- 
2.54.0

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to