[Git][java-team/httpcomponents-client5][upstream] New upstream version 5.6.5
Emmanuel Bourg (@ebourg)
gitlab at salsa.debian.org
Wed Nov 11 00:31:43 GMT 2026
Emmanuel Bourg pushed to branch upstream at Debian Java Maintainers / httpcomponents-client5
Commits:
383de048 by Emmanuel Bourg at 2026-11-10T23:01:53+01:00
New upstream version 5.6.5
- - - - -
26 changed files:
- RELEASE_NOTES.txt
- httpclient5-cache/pom.xml
- httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsyncCachingExec.java
- httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheSupport.java
- httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseCachingPolicy.java
- httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/CacheControlParserTest.java
- httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheSupport.java
- httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseCachingPolicy.java
- httpclient5-fluent/pom.xml
- httpclient5-observation/pom.xml
- httpclient5-testing/pom.xml
- httpclient5-testing/src/test/java/org/apache/hc/client5/testing/TestValidateAfterInactivity.java
- httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncTlsHandshakeTimeout.java
- httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestH2ClientAuthentication.java
- httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionTimeouts.java
- httpclient5/pom.xml
- httpclient5/src/main/java/org/apache/hc/client5/http/async/methods/InflatingBrotliDataConsumer.java
- httpclient5/src/main/java/org/apache/hc/client5/http/async/methods/InflatingZstdDataConsumer.java
- httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncMainClientExec.java
- httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ResponseEntityProxy.java
- httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcher.java
- httpclient5/src/test/java/org/apache/hc/client5/http/async/methods/InflatingBrotliDataConsumerTest.java
- httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientEvictExpiredConnections.java
- httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestResponseEntityProxy.java
- httpclient5/src/test/java/org/apache/hc/client5/http/psl/TestPublicSuffixMatcher.java
- pom.xml
Changes:
=====================================
RELEASE_NOTES.txt
=====================================
@@ -1,3 +1,44 @@
+Release 5.6.5
+------------------
+
+This maintenance release fixes several defects found since the previous release
+including the defect in the async Brotli decompression code that can cause
+the message exchange to hang indefinitely. It also upgrades HttpCore to version 5.4.4.
+
+Change Log
+-------------------
+
+* Upgraded HttpCore to version 5.4.4.
+ Contributed by Oleg Kalnichevski <olegk at apache.org>
+
+* HTTPCLIENT-2433: Prevent concurrent HTTP/2 request body replay.
+ Contributed by Matthias Kurz <m.kurz at irregular.at>
+
+* HTTPCLIENT-2432: Fixed connection-pool leak in ResponseEntityProxy#cleanup() when
+ runtime #disconnectEndpoint throws an exception (#883).
+ Contributed by Victor Alekseev <krocodl at gmail.com>
+
+* Decode punycode public suffixes in PublicSuffixMatcher#verify (#876).
+ Contributed by Javid Khan <dxbjavid at gmail.com>
+
+* Fixed Brotli decompression hang with large input buffers.
+ Contributed by Arturo Bernal <abernal at apache.org>
+
+* HTTP cache to treat malformed delta-seconds as absent.
+ Contributed by Arturo Bernal Javid Khan <dxbjavid at gmail.com>
+
+* Bug-fix: ResponseCachingPolicy incorrectly applies `neverCache1_1ResponsesWithQueryString`
+ config parameter. This config parameter and related functionality will be deprecated
+ in the next feature release and removed in the future.
+ Contributed by Oleg Kalnichevski <olegk at apache.org>
+
+* Removed invalid request version check from ResponseCachingPolicy.
+ Contributed by Oleg Kalnichevski <olegk at apache.org>
+
+* Fixed resource leaking on error in AsyncCachingExec
+ Contributed by Jeremie Bolduc <16137441+Jouramie at users.noreply.github.com>
+
+
Release 5.6.4
------------------
=====================================
httpclient5-cache/pom.xml
=====================================
@@ -28,7 +28,7 @@
<parent>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-parent</artifactId>
- <version>5.6.4</version>
+ <version>5.6.5</version>
</parent>
<artifactId>httpclient5-cache</artifactId>
<name>Apache HttpClient Cache</name>
=====================================
httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/AsyncCachingExec.java
=====================================
@@ -126,8 +126,9 @@ private void triggerResponse(
final SimpleBody body = cacheResponse.getBody();
final byte[] content = body != null ? body.getBodyBytes() : null;
final ContentType contentType = body != null ? body.getContentType() : null;
+ AsyncDataConsumer dataConsumer = null;
try {
- final AsyncDataConsumer dataConsumer = asyncExecCallback.handleResponse(
+ dataConsumer = asyncExecCallback.handleResponse(
cacheResponse,
content != null ? new BasicEntityDetails(content.length, contentType) : null);
if (dataConsumer != null) {
@@ -139,6 +140,10 @@ private void triggerResponse(
asyncExecCallback.completed();
} catch (final HttpException | IOException ex) {
asyncExecCallback.failed(ex);
+ } finally {
+ if (dataConsumer != null) {
+ dataConsumer.releaseResources();
+ }
}
}
=====================================
httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/CacheSupport.java
=====================================
@@ -79,7 +79,9 @@ public static long deltaSeconds(final String s) {
return ageValue;
} catch (final NumberFormatException ignore) {
}
- return 0;
+ // A value that is not a valid delta-seconds token is invalid and must be treated as absent (RFC 9111 4.2.1),
+ // not folded into a usable 0 which would look like a genuine directive.
+ return -1;
}
}
=====================================
httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/ResponseCachingPolicy.java
=====================================
@@ -90,14 +90,6 @@ public ResponseCachingPolicy(
* @return {@code true} if response is cacheable
*/
public boolean isResponseCacheable(final ResponseCacheControl cacheControl, final HttpRequest request, final HttpResponse response) {
- final ProtocolVersion version = request.getVersion() != null ? request.getVersion() : HttpVersion.DEFAULT;
- if (version.compareToVersion(HttpVersion.HTTP_1_1) > 0) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Protocol version {} is non-cacheable", version);
- }
- return false;
- }
-
// Presently only GET and HEAD methods are supported
final String httpMethod = request.getMethod();
if (!Method.GET.isSame(httpMethod) && !Method.HEAD.isSame(httpMethod)) {
@@ -122,10 +114,11 @@ public boolean isResponseCacheable(final ResponseCacheControl cacheControl, fina
}
if (request.getPath().contains("?")) {
- if (neverCache1_0ResponsesWithQueryString && from1_0Origin(response)) {
+ if (neverCache1_0ResponsesWithQueryString && from1_0Origin(response) || neverCache1_1ResponsesWithQueryString) {
LOG.debug("Response is not cacheable as it had a query string");
return false;
- } else if (!neverCache1_1ResponsesWithQueryString && !isExplicitlyCacheable(cacheControl, response)) {
+ }
+ if (!isExplicitlyCacheable(cacheControl, response)) {
LOG.debug("Response is not cacheable as it is missing explicit caching headers");
return false;
}
=====================================
httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/CacheControlParserTest.java
=====================================
@@ -62,7 +62,8 @@ void testParseSMaxAge() {
void testParseInvalidCacheValue() {
final Header header = new BasicHeader("Cache-Control", "max-age=invalid");
final ResponseCacheControl cacheControl = parser.parseResponse(Collections.singletonList(header).iterator());
- assertEquals(0L, cacheControl.getMaxAge());
+ // A malformed delta-seconds value is invalid and must be treated as absent (-1), not a usable 0.
+ assertEquals(-1L, cacheControl.getMaxAge());
}
@Test
=====================================
httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestCacheSupport.java
=====================================
@@ -43,7 +43,7 @@ void testParseDeltaSeconds() {
Assertions.assertEquals(-1L, CacheSupport.deltaSeconds("-100"));
Assertions.assertEquals(-1L, CacheSupport.deltaSeconds(""));
Assertions.assertEquals(-1L, CacheSupport.deltaSeconds(null));
- Assertions.assertEquals(0L, CacheSupport.deltaSeconds("huh?"));
+ Assertions.assertEquals(-1L, CacheSupport.deltaSeconds("huh?"));
Assertions.assertEquals(2147483648L, CacheSupport.deltaSeconds("2147483648"));
Assertions.assertEquals(2147483648L, CacheSupport.deltaSeconds("2147483649"));
Assertions.assertEquals(2147483648L, CacheSupport.deltaSeconds("214748364712"));
=====================================
httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestResponseCachingPolicy.java
=====================================
@@ -899,9 +899,9 @@ void testIsResponseCacheable() {
request = new BasicHttpRequest("GET","/foo?s=bar");
// HTTPbis working group says ok if explicitly indicated by
// response headers
- policy = new ResponseCachingPolicy(true, false, true);
response.setCode(HttpStatus.SC_OK);
response.setHeader("Date", DateUtils.formatStandardDate(now));
+ responseCacheControl = ResponseCacheControl.builder().setMaxAge(3600).build();
assertTrue(policy.isResponseCacheable(responseCacheControl, request, response));
}
@@ -973,6 +973,20 @@ void testSMaxageWithAuthorizationIsCacheable() {
"Response with s-maxage and Authorization header should be cacheable in shared cache.");
}
+ @Test
+ void testMalformedSMaxageWithAuthorizationNotCacheableBySharedCache() {
+ request = new BasicHttpRequest("GET", "/resource");
+ request.setHeader(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpwYXNzd2Q=");
+ response.setHeader("Expires", DateUtils.formatStandardDate(tenSecondsFromNow));
+ response.setHeader("Cache-Control", "s-maxage=invalid");
+ // Parse the actual header so the malformed value is handled the way it is on the wire.
+ responseCacheControl = CacheControlHeaderParser.INSTANCE.parse(response);
+
+ final boolean isCacheable = policy.isResponseCacheable(responseCacheControl, request, response);
+ assertFalse(isCacheable,
+ "Response to an Authorization request with a malformed s-maxage must not be stored by a shared cache.");
+ }
+
@Test
void testNoDirectivesWithAuthorizationNotCacheable() {
request = new BasicHttpRequest("GET", "/resource");
@@ -1000,4 +1014,20 @@ void testMustRevalidateWithAuthorizationIsCacheable() {
"Response with must-revalidate and Authorization header should be cacheable in shared cache.");
}
+ @Test
+ void testHttp2_0HintCacheable() {
+ request = new BasicHttpRequest("GET", "/");
+ request.setVersion(HttpVersion.HTTP_2);
+ response = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
+ Assertions.assertTrue(policy.isResponseCacheable(responseCacheControl, request, response));
+ }
+
+ @Test
+ void testHttp1_0HintCacheable() {
+ request = new BasicHttpRequest("GET", "/");
+ request.setVersion(HttpVersion.HTTP_1_0);
+ response = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
+ Assertions.assertTrue(policy.isResponseCacheable(responseCacheControl, request, response));
+ }
+
}
\ No newline at end of file
=====================================
httpclient5-fluent/pom.xml
=====================================
@@ -28,7 +28,7 @@
<parent>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-parent</artifactId>
- <version>5.6.4</version>
+ <version>5.6.5</version>
</parent>
<artifactId>httpclient5-fluent</artifactId>
<name>Apache HttpClient Fluent</name>
=====================================
httpclient5-observation/pom.xml
=====================================
@@ -28,7 +28,7 @@
<parent>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-parent</artifactId>
- <version>5.6.4</version>
+ <version>5.6.5</version>
</parent>
<artifactId>httpclient5-observation</artifactId>
=====================================
httpclient5-testing/pom.xml
=====================================
@@ -28,7 +28,7 @@
<parent>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-parent</artifactId>
- <version>5.6.4</version>
+ <version>5.6.5</version>
</parent>
<artifactId>httpclient5-testing</artifactId>
<name>Apache HttpClient Integration Tests</name>
=====================================
httpclient5-testing/src/test/java/org/apache/hc/client5/testing/TestValidateAfterInactivity.java
=====================================
@@ -44,6 +44,7 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -144,6 +145,7 @@ void testSyncClientWithValidateAfterInactivity() throws Exception {
}
@Test
+ @Tag("stale-conn")
void testAsyncClientWithStaleConnection() throws Exception {
testAsyncClient(false);
}
=====================================
httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncTlsHandshakeTimeout.java
=====================================
@@ -55,10 +55,10 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
+ at Tag("time-out")
public class TestAsyncTlsHandshakeTimeout {
private static final Duration EXPECTED_TIMEOUT = Duration.ofMillis(500);
- @Tag("slow")
@Timeout(5)
@ParameterizedTest
@ValueSource(strings = { "false", "true" })
=====================================
httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestH2ClientAuthentication.java
=====================================
@@ -26,9 +26,48 @@
*/
package org.apache.hc.client5.testing.async;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.client5.testing.BasicTestAuthenticator;
+import org.apache.hc.client5.testing.auth.BasicAuthenticationHandler;
import org.apache.hc.client5.testing.extension.async.ClientProtocolLevel;
import org.apache.hc.client5.testing.extension.async.ServerProtocolLevel;
+import org.apache.hc.client5.testing.extension.async.TestAsyncClient;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.Message;
+import org.apache.hc.core5.http.Method;
import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.message.BasicHttpResponse;
+import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+import org.apache.hc.core5.http.nio.ResponseChannel;
+import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityConsumer;
+import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer;
+import org.apache.hc.core5.http.nio.entity.FileEntityProducer;
+import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
+import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.http2.H2Error;
+import org.apache.hc.core5.http2.H2StreamResetException;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
abstract class TestH2ClientAuthentication extends AbstractHttpAsyncClientAuthenticationTest {
@@ -36,4 +75,144 @@ public TestH2ClientAuthentication(final URIScheme scheme) {
super(scheme, ClientProtocolLevel.H2_ONLY, ServerProtocolLevel.H2_ONLY);
}
-}
\ No newline at end of file
+ @Test
+ void testBasicAuthenticationReplayWithLargeFile(@TempDir final Path tempDir) throws Exception {
+ final byte[] expected = new byte[2_000_000];
+ for (int i = 0; i < expected.length; i++) {
+ expected[i] = (byte) (i * 31 + 7);
+ }
+ final Path source = tempDir.resolve("request.bin");
+ Files.write(source, expected);
+
+ configureServerWithBasicAuth(bootstrap -> bootstrap.register("*", AsyncEchoHandler::new));
+ final HttpHost target = startServer();
+
+ final TestAsyncClient client = startClient();
+ final HttpClientContext context = HttpClientContext.create();
+ context.setCredentialsProvider(CredentialsProviderBuilder.create()
+ .add(target, "test", "test".toCharArray())
+ .build());
+
+ final Future<Message<HttpResponse, byte[]>> future = client.execute(
+ new BasicRequestProducer(Method.PUT, target, "/", new FileEntityProducer(source.toFile())),
+ new BasicResponseConsumer<>(new BasicAsyncEntityConsumer()), context, null);
+ final Message<HttpResponse, byte[]> response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+
+ Assertions.assertEquals(HttpStatus.SC_OK, response.getHead().getCode());
+ Assertions.assertArrayEquals(expected, response.getBody());
+ }
+
+ @Test
+ void testBasicAuthenticationReplayAfterNoErrorReset() throws Exception {
+ final byte[] expected = new byte[2_000_000];
+ for (int i = 0; i < expected.length; i++) {
+ expected[i] = (byte) (i * 31 + 7);
+ }
+
+ final AtomicBoolean resetSent = new AtomicBoolean();
+ configureServer(bootstrap -> bootstrap.register("*",
+ () -> new ResettingBasicAuthHandler(new AsyncEchoHandler(), resetSent)));
+ final HttpHost target = startServer();
+
+ final TestAsyncClient client = startClient();
+ final HttpClientContext context = HttpClientContext.create();
+ context.setCredentialsProvider(CredentialsProviderBuilder.create()
+ .add(target, "test", "test".toCharArray())
+ .build());
+
+ final Future<Message<HttpResponse, byte[]>> future = client.execute(
+ new BasicRequestProducer(Method.PUT, target, "/", new BasicAsyncEntityProducer(expected)),
+ new BasicResponseConsumer<>(new BasicAsyncEntityConsumer()), context, null);
+ final Message<HttpResponse, byte[]> response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+
+ Assertions.assertTrue(resetSent.get());
+ Assertions.assertEquals(HttpStatus.SC_OK, response.getHead().getCode());
+ Assertions.assertArrayEquals(expected, response.getBody());
+ }
+
+ private static final class ResettingBasicAuthHandler implements AsyncServerExchangeHandler {
+
+ private final AsyncServerExchangeHandler exchangeHandler;
+ private final AtomicBoolean resetSent;
+ private final BasicAuthenticationHandler authenticationHandler;
+ private final BasicTestAuthenticator authenticator;
+ private boolean authenticated;
+
+ ResettingBasicAuthHandler(final AsyncServerExchangeHandler exchangeHandler, final AtomicBoolean resetSent) {
+ this.exchangeHandler = exchangeHandler;
+ this.resetSent = resetSent;
+ this.authenticationHandler = new BasicAuthenticationHandler();
+ this.authenticator = new BasicTestAuthenticator("test:test", "test realm");
+ }
+
+ @Override
+ public void handleRequest(
+ final HttpRequest request,
+ final EntityDetails entityDetails,
+ final ResponseChannel responseChannel,
+ final HttpContext context) throws HttpException, IOException {
+ final Header authorization = request.getFirstHeader(HttpHeaders.AUTHORIZATION);
+ final String credentials = authorization != null
+ ? authenticationHandler.extractAuthToken(authorization.getValue())
+ : null;
+ authenticated = authenticator.authenticate(request.getAuthority(), request.getRequestUri(), credentials);
+ if (authenticated) {
+ exchangeHandler.handleRequest(request, entityDetails, responseChannel, context);
+ } else {
+ final HttpResponse unauthorized = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
+ unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test realm\"");
+ responseChannel.sendResponse(unauthorized, null, context);
+ }
+ }
+
+ @Override
+ public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
+ if (authenticated) {
+ exchangeHandler.updateCapacity(capacityChannel);
+ } else {
+ capacityChannel.update(Integer.MAX_VALUE);
+ }
+ }
+
+ @Override
+ public void consume(final ByteBuffer src) throws IOException {
+ if (authenticated) {
+ exchangeHandler.consume(src);
+ } else {
+ resetSent.set(true);
+ throw new H2StreamResetException(H2Error.NO_ERROR, "Stop upload after authentication challenge");
+ }
+ }
+
+ @Override
+ public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
+ if (authenticated) {
+ exchangeHandler.streamEnd(trailers);
+ }
+ }
+
+ @Override
+ public int available() {
+ return authenticated ? exchangeHandler.available() : 0;
+ }
+
+ @Override
+ public void produce(final DataStreamChannel channel) throws IOException {
+ if (authenticated) {
+ exchangeHandler.produce(channel);
+ }
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ exchangeHandler.failed(cause);
+ }
+
+ @Override
+ public void releaseResources() {
+ exchangeHandler.releaseResources();
+ }
+
+ }
+
+}
=====================================
httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionTimeouts.java
=====================================
@@ -39,6 +39,7 @@
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.core5.http.ClassicHttpRequest;
+import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -51,6 +52,7 @@
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+ at Tag("time-out")
class TestConnectionTimeouts {
private static final Duration EXPECTED_TIMEOUT = Duration.ofMillis(500);
=====================================
httpclient5/pom.xml
=====================================
@@ -28,7 +28,7 @@
<parent>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-parent</artifactId>
- <version>5.6.4</version>
+ <version>5.6.5</version>
</parent>
<artifactId>httpclient5</artifactId>
<name>Apache HttpClient</name>
=====================================
httpclient5/src/main/java/org/apache/hc/client5/http/async/methods/InflatingBrotliDataConsumer.java
=====================================
@@ -89,12 +89,9 @@ public void updateCapacity(final CapacityChannel capacityChannel) throws IOExcep
public void consume(final ByteBuffer src) throws IOException {
while (src.hasRemaining()) {
final ByteBuffer in = decoder.getInputBuffer();
+ in.clear();
+
final int xfer = Math.min(src.remaining(), in.remaining());
- if (xfer == 0) {
- decoder.push(0);
- pump();
- continue;
- }
final int lim = src.limit();
src.limit(src.position() + xfer);
in.put(src);
=====================================
httpclient5/src/main/java/org/apache/hc/client5/http/async/methods/InflatingZstdDataConsumer.java
=====================================
@@ -130,7 +130,9 @@ public void streamEnd(final List<? extends Header> trailers) throws HttpExceptio
@Override
public void releaseResources() {
- dctx.close();
+ if (closed.compareAndSet(false, true)) {
+ dctx.close();
+ }
downstream.releaseResources();
}
}
\ No newline at end of file
=====================================
httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncMainClientExec.java
=====================================
@@ -30,6 +30,7 @@
import java.io.InterruptedIOException;
import java.nio.ByteBuffer;
import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.hc.client5.http.HttpRoute;
@@ -95,16 +96,26 @@ public void execute(
LOG.debug("{} executing {} {}", exchangeId, request.getMethod(), request.getRequestUri());
}
+ final AtomicInteger messageCountDown = new AtomicInteger(2);
final AsyncClientExchangeHandler internalExchangeHandler = new AsyncClientExchangeHandler() {
private final AtomicReference<AsyncDataConsumer> entityConsumerRef = new AtomicReference<>();
+ private void messageCompleted() {
+ if (messageCountDown.decrementAndGet() == 0) {
+ asyncExecCallback.completed();
+ }
+ }
+
@Override
public void releaseResources() {
final AsyncDataConsumer entityConsumer = entityConsumerRef.getAndSet(null);
if (entityConsumer != null) {
entityConsumer.releaseResources();
}
+ if (messageCountDown.get() > 0) {
+ messageCompleted();
+ }
}
@Override
@@ -114,12 +125,16 @@ public void failed(final Exception cause) {
entityConsumer.releaseResources();
}
execRuntime.markConnectionNonReusable();
- asyncExecCallback.failed(cause);
+ if (messageCountDown.getAndSet(0) > 0) {
+ asyncExecCallback.failed(cause);
+ }
}
@Override
public void cancel() {
- failed(new InterruptedIOException());
+ if (messageCountDown.get() > 0) {
+ failed(new InterruptedIOException());
+ }
}
@Override
@@ -129,6 +144,9 @@ public void produceRequest(final RequestChannel channel, final HttpContext conte
httpProcessor.process(request, entityProducer, clientContext);
channel.sendRequest(request, entityProducer, context);
+ if (entityProducer == null) {
+ messageCompleted();
+ }
}
@Override
@@ -138,7 +156,31 @@ public int available() {
@Override
public void produce(final DataStreamChannel channel) throws IOException {
- entityProducer.produce(channel);
+ entityProducer.produce(new DataStreamChannel() {
+
+ @Override
+ public void requestOutput() {
+ channel.requestOutput();
+ }
+
+ @Override
+ public int write(final ByteBuffer src) throws IOException {
+ return channel.write(src);
+ }
+
+ @Override
+ public void endStream(final List<? extends Header> trailers) throws IOException {
+ channel.endStream(trailers);
+ messageCompleted();
+ }
+
+ @Override
+ public void endStream() throws IOException {
+ channel.endStream();
+ messageCompleted();
+ }
+
+ });
}
@Override
@@ -157,7 +199,7 @@ public void consumeResponse(
entityConsumerRef.set(asyncExecCallback.handleResponse(response, entityDetails));
if (entityDetails == null) {
execRuntime.validateConnection();
- asyncExecCallback.completed();
+ messageCompleted();
}
}
@@ -187,7 +229,7 @@ public void streamEnd(final List<? extends Header> trailers) throws HttpExceptio
} else {
execRuntime.validateConnection();
}
- asyncExecCallback.completed();
+ messageCompleted();
}
};
=====================================
httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ResponseEntityProxy.java
=====================================
@@ -62,10 +62,17 @@ public static void enhance(final ClassicHttpResponse response, final ExecRuntime
private void cleanup() throws IOException {
if (this.execRuntime != null) {
- if (this.execRuntime.isEndpointConnected()) {
- this.execRuntime.disconnectEndpoint();
+ try {
+ if (this.execRuntime.isEndpointConnected()) {
+ this.execRuntime.disconnectEndpoint();
+ }
+ } finally {
+ // discardEndpoint() is the only path that returns the lease to the
+ // pool (its manager.release(...) runs inside a finally). Guard it so
+ // an IOException from disconnectEndpoint() on a dead socket cannot
+ // strand the connection as permanently leased.
+ this.execRuntime.discardEndpoint();
}
- this.execRuntime.discardEndpoint();
}
}
=====================================
httpclient5/src/main/java/org/apache/hc/client5/http/psl/PublicSuffixMatcher.java
=====================================
@@ -249,7 +249,12 @@ public boolean verify(final String domain) {
if (domain == null) {
return false;
}
- return verifyInternal(domain.startsWith(".") ? domain.substring(1) : domain);
+ // Normalise here so that verifyInternal can assume its input is already lowercase and in
+ // Unicode form. The rules are held that way, so an ACE-encoded (xn--) or mixed-case public
+ // suffix has to be decoded first; otherwise it fails to match a rule and is mistaken for a
+ // registrable domain.
+ final String normalized = DnsUtils.normalizeUnicode(domain.startsWith(".") ? domain.substring(1) : domain);
+ return verifyInternal(normalized);
}
@Internal
=====================================
httpclient5/src/test/java/org/apache/hc/client5/http/async/methods/InflatingBrotliDataConsumerTest.java
=====================================
@@ -26,18 +26,23 @@
*/
package org.apache.hc.client5.http.async.methods;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
+import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -198,4 +203,52 @@ void registerInExec() {
final ContentCompressionAsyncExec exec = new ContentCompressionAsyncExec(map);
assertNotNull(exec);
}
+
+ @Test
+ void inflateBrotliLargerThanInputBuffer() {
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
+ final byte[] original = new byte[64 * 1024];
+ new Random(42).nextBytes(original);
+
+ final byte[] compressed = Encoder.compress(
+ original,
+ new Encoder.Parameters()
+ .setQuality(6)
+ .setWindow(22));
+
+ assertTrue(compressed.length > 8 * 1024);
+
+ final ByteArrayOutputStream output = new ByteArrayOutputStream();
+
+ final AsyncDataConsumer downstream = new AsyncDataConsumer() {
+
+ @Override
+ public void updateCapacity(final CapacityChannel capacityChannel) {
+ }
+
+ @Override
+ public void consume(final ByteBuffer src) {
+ final byte[] buf = new byte[src.remaining()];
+ src.get(buf);
+ output.write(buf, 0, buf.length);
+ }
+
+ @Override
+ public void streamEnd(final List<? extends Header> trailers) {
+ }
+
+ @Override
+ public void releaseResources() {
+ }
+ };
+
+ final InflatingBrotliDataConsumer inflating =
+ new InflatingBrotliDataConsumer(downstream);
+
+ inflating.consume(ByteBuffer.wrap(compressed));
+ inflating.streamEnd(Collections.emptyList());
+
+ assertArrayEquals(original, output.toByteArray());
+ });
+ }
}
=====================================
httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientEvictExpiredConnections.java
=====================================
@@ -27,27 +27,34 @@
package org.apache.hc.client5.http.examples;
import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.pool.PoolStats;
import org.apache.hc.core5.util.TimeValue;
/**
- * Example demonstrating how to evict expired and idle connections
+ * Example demonstrating how to make sure connections connections expire
+ * after 5 seconds of inactivity and how to proactively evict expired connections
* from the connection pool.
*/
public class ClientEvictExpiredConnections {
public static void main(final String[] args) throws Exception {
- final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
- cm.setMaxTotal(100);
+ final PoolingHttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
+ .setMaxConnTotal(100)
+ .build();
try (final CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
+ // Lazily evict expired connections every minute
.evictExpiredConnections()
- .evictIdleConnections(TimeValue.ofSeconds(5))
+ .setDefaultRequestConfig(RequestConfig.custom()
+ .setConnectionKeepAlive(TimeValue.ofSeconds(5))
+ .build())
.build()) {
// create an array of URIs to perform GETs on
final String[] urisToGet = {
@@ -72,9 +79,12 @@ public static void main(final String[] args) throws Exception {
final PoolStats stats1 = cm.getTotalStats();
System.out.println("Connections kept alive: " + stats1.getAvailable());
- // Sleep 10 sec and let the connection evictor do its job
+ // Sleep 10 sec
Thread.sleep(10000);
+ // Manually force eviction of expired connections
+ cm.closeExpired();
+
final PoolStats stats2 = cm.getTotalStats();
System.out.println("Connections kept alive: " + stats2.getAvailable());
=====================================
httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestResponseEntityProxy.java
=====================================
@@ -28,19 +28,33 @@
package org.apache.hc.client5.http.impl.classic;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.classic.ExecRuntime;
+import org.apache.hc.client5.http.io.ConnectionEndpoint;
+import org.apache.hc.client5.http.io.HttpClientConnectionManager;
+import org.apache.hc.client5.http.io.LeaseRequest;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.function.Supplier;
+import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.impl.io.ChunkedInputStream;
+import org.apache.hc.core5.http.impl.io.HttpRequestExecutor;
import org.apache.hc.core5.http.impl.io.SessionInputBufferImpl;
import org.apache.hc.core5.http.io.SessionInputBuffer;
import org.apache.hc.core5.http.io.entity.BasicHttpEntity;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.util.TimeValue;
+import org.apache.hc.core5.util.Timeout;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -48,6 +62,7 @@
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.slf4j.LoggerFactory;
class TestResponseEntityProxy {
@@ -137,4 +152,118 @@ void testWriteToNullDrainsAndReleasesStream() throws Exception {
}
+
+ @Test
+ void testCleanupDiscardsEndpointWhenDisconnectEndpointThrows() throws Exception {
+ // Simulate a dead socket: disconnectEndpoint() throws (endpoint.close() on
+ // a broken connection). Without the fix, discardEndpoint() would be skipped
+ // and the connection would remain permanently leased in the pool.
+ Mockito.when(execRuntime.isEndpointConnected()).thenReturn(Boolean.TRUE);
+ Mockito.doThrow(new IOException("simulated dead socket"))
+ .when(execRuntime).disconnectEndpoint();
+
+ final ArgumentCaptor<HttpEntity> captor = ArgumentCaptor.forClass(HttpEntity.class);
+ ResponseEntityProxy.enhance(response, execRuntime);
+ Mockito.verify(response).setEntity(captor.capture());
+ final HttpEntity wrappedEntity = captor.getValue();
+
+ Assertions.assertThrows(IOException.class, wrappedEntity::close);
+
+ Mockito.verify(execRuntime).disconnectEndpoint();
+ Mockito.verify(execRuntime).discardEndpoint();
+ }
+
+ /**
+ * Regression test for HTTPCLIENT-2432.
+ * <p>
+ * On paths that reach {@code cleanup()} while the endpoint is still leased
+ * (e.g. {@code streamAbort()}, or {@code streamClosed()} swallowing a
+ * {@code SocketException}), {@code disconnectEndpoint()} is invoked on a
+ * connection whose socket may be in a broken state. Prior to the fix, an
+ * {@code IOException} from {@code endpoint.close()} propagated out and
+ * skipped {@code discardEndpoint()} - the only path that calls
+ * {@code manager.release(...)} and returns the lease to the pool. Under
+ * load this exhausted the pool.
+ * <p>
+ * The test wires a real {@link InternalExecRuntime} to a fake connection
+ * manager whose leased endpoint throws from {@code close()}, then triggers
+ * {@code cleanup()} via {@code streamAbort()} and asserts the manager
+ * received exactly one {@code release()} call.
+ */
+ @Test
+ void testPoolLeaseReturnedWhenDisconnectEndpointThrows() throws Exception {
+ final AtomicInteger releaseCount = new AtomicInteger();
+ @SuppressWarnings("deprecation")
+ final ConnectionEndpoint brokenEndpoint = new ConnectionEndpoint() {
+ @Override
+ public ClassicHttpResponse execute(final String id, final ClassicHttpRequest request,
+ final HttpRequestExecutor executor, final HttpContext context) {
+ throw new UnsupportedOperationException();
+ }
+ @Override
+ public boolean isConnected() {
+ return true;
+ }
+ @Override
+ public void setSocketTimeout(final Timeout timeout) {
+ }
+ @Override
+ public void close(final CloseMode closeMode) {
+ }
+ @Override
+ public void close() throws IOException {
+ throw new IOException("simulated dead socket");
+ }
+ };
+
+ final HttpClientConnectionManager fakeManager = new HttpClientConnectionManager() {
+ @Override
+ public LeaseRequest lease(final String id, final HttpRoute route,
+ final Timeout requestTimeout, final Object state) {
+ return new LeaseRequest() {
+ @Override
+ public ConnectionEndpoint get(final Timeout timeout) {
+ return brokenEndpoint;
+ }
+ @Override
+ public boolean cancel() {
+ return false;
+ }
+ };
+ }
+ @Override
+ public void release(final ConnectionEndpoint endpoint, final Object newState,
+ final TimeValue validDuration) {
+ releaseCount.incrementAndGet();
+ }
+ @Override
+ public void connect(final ConnectionEndpoint endpoint, final TimeValue connectTimeout,
+ final HttpContext context) {
+ }
+ @Override
+ public void upgrade(final ConnectionEndpoint endpoint, final HttpContext context) {
+ }
+ @Override
+ public void close() {
+ }
+ @Override
+ public void close(final CloseMode closeMode) {
+ }
+ };
+
+ final InternalExecRuntime runtime = new InternalExecRuntime(
+ LoggerFactory.getLogger(TestResponseEntityProxy.class),
+ fakeManager,
+ new HttpRequestExecutor(),
+ null);
+ runtime.acquireEndpoint("id1", new HttpRoute(new HttpHost("localhost", 80)),
+ null, HttpClientContext.create());
+
+ final ResponseEntityProxy proxy = new ResponseEntityProxy(entity, runtime);
+
+ Assertions.assertThrows(IOException.class, () -> proxy.streamAbort(null));
+
+ Assertions.assertEquals(1, releaseCount.get(),
+ "connection lease must be returned to the pool even when disconnectEndpoint() throws");
+ }
}
\ No newline at end of file
=====================================
httpclient5/src/test/java/org/apache/hc/client5/http/psl/TestPublicSuffixMatcher.java
=====================================
@@ -191,6 +191,18 @@ void testMatchUnicode() {
Assertions.assertTrue(matcher.matches(".xn--h-2fa.no"));
}
+ @Test
+ void testVerifyUnicode() {
+ // A public suffix must be rejected by verify() whether it is given in Unicode or in its
+ // ACE (xn--) form; matches() already recognises both, so verify() must agree.
+ Assertions.assertTrue(matcher.matches(".xn--h-2fa.no"));
+ Assertions.assertFalse(matcher.verify("hå.no")); // å is <aring>
+ Assertions.assertFalse(matcher.verify("xn--h-2fa.no"));
+ // A genuine registrable domain under the IDN suffix is still allowed, in either form.
+ Assertions.assertTrue(matcher.verify("foo.hå.no"));
+ Assertions.assertTrue(matcher.verify("foo.xn--h-2fa.no"));
+ }
+
private void checkPublicSuffix(final String input, final String expected) {
Assertions.assertEquals(expected, pslMatcher.getDomainRoot(input));
}
=====================================
pom.xml
=====================================
@@ -33,7 +33,7 @@
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-parent</artifactId>
<name>Apache HttpComponents Client</name>
- <version>5.6.4</version>
+ <version>5.6.5</version>
<description>Apache HttpComponents Client is a library of components for building client side HTTP services</description>
<url>https://hc.apache.org/httpcomponents-client-5.6.x/${project.version}/</url>
<inceptionYear>1999</inceptionYear>
@@ -48,7 +48,7 @@
<connection>scm:git:https://gitbox.apache.org/repos/asf/httpcomponents-client.git</connection>
<developerConnection>scm:git:https://gitbox.apache.org/repos/asf/httpcomponents-client.git</developerConnection>
<url>https://github.com/apache/httpcomponents-client/tree/${project.scm.tag}</url>
- <tag>5.6.4</tag>
+ <tag>5.6.5</tag>
</scm>
<distributionManagement>
@@ -62,7 +62,7 @@
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
- <httpcore.version>5.4.3</httpcore.version>
+ <httpcore.version>5.4.4</httpcore.version>
<log4j.version>2.25.0</log4j.version>
<brotli4j.version>1.20.0</brotli4j.version>
<conscrypt.version>2.5.2</conscrypt.version>
@@ -398,7 +398,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>${hc.surefire.version}</version>
<configuration>
- <excludedGroups>slow</excludedGroups>
+ <excludedGroups>slow,time-out,stale-conn</excludedGroups>
</configuration>
</plugin>
</plugins>
@@ -422,6 +422,23 @@
</plugins>
</build>
</profile>
+ <profile>
+ <id>pre-release-tests</id>
+ <build>
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>${hc.surefire.version}</version>
+ <configuration combine.self="override">
+ <excludedGroups>slow</excludedGroups>
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </build>
+ </profile>
</profiles>
View it on GitLab: https://salsa.debian.org/java-team/httpcomponents-client5/-/commit/383de048c3ccea997ab0f6e5a0d9a8d2916fbf16
--
View it on GitLab: https://salsa.debian.org/java-team/httpcomponents-client5/-/commit/383de048c3ccea997ab0f6e5a0d9a8d2916fbf16
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-java-commits/attachments/20261111/61353b7d/attachment.htm>
More information about the pkg-java-commits
mailing list