View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.transport.jdk;
20  
21  import javax.net.ssl.SSLContext;
22  import javax.net.ssl.SSLEngine;
23  import javax.net.ssl.SSLException;
24  import javax.net.ssl.SSLParameters;
25  import javax.net.ssl.X509ExtendedTrustManager;
26  import javax.net.ssl.X509TrustManager;
27  
28  import java.io.BufferedInputStream;
29  import java.io.IOException;
30  import java.io.InputStream;
31  import java.io.InterruptedIOException;
32  import java.io.UncheckedIOException;
33  import java.lang.reflect.InvocationTargetException;
34  import java.lang.reflect.Method;
35  import java.net.Authenticator;
36  import java.net.ConnectException;
37  import java.net.InetAddress;
38  import java.net.InetSocketAddress;
39  import java.net.NoRouteToHostException;
40  import java.net.PasswordAuthentication;
41  import java.net.ProxySelector;
42  import java.net.Socket;
43  import java.net.URI;
44  import java.net.URISyntaxException;
45  import java.net.UnknownHostException;
46  import java.net.http.HttpClient;
47  import java.net.http.HttpClient.Version;
48  import java.net.http.HttpRequest;
49  import java.net.http.HttpResponse;
50  import java.nio.file.Files;
51  import java.nio.file.Path;
52  import java.nio.file.StandardCopyOption;
53  import java.security.cert.X509Certificate;
54  import java.time.Duration;
55  import java.time.Instant;
56  import java.time.ZoneId;
57  import java.time.ZonedDateTime;
58  import java.time.format.DateTimeFormatter;
59  import java.time.format.DateTimeParseException;
60  import java.util.Base64;
61  import java.util.HashMap;
62  import java.util.Locale;
63  import java.util.Map;
64  import java.util.Objects;
65  import java.util.Optional;
66  import java.util.Set;
67  import java.util.TreeSet;
68  import java.util.concurrent.Semaphore;
69  import java.util.function.Function;
70  import java.util.regex.Matcher;
71  
72  import com.github.mizosoft.methanol.Methanol;
73  import com.github.mizosoft.methanol.RetryInterceptor;
74  import com.github.mizosoft.methanol.RetryInterceptor.Context;
75  import org.eclipse.aether.ConfigurationProperties;
76  import org.eclipse.aether.ConfigurationProperties.HttpVersion;
77  import org.eclipse.aether.ConfigurationProperties.RedirectMode;
78  import org.eclipse.aether.RepositorySystemSession;
79  import org.eclipse.aether.repository.AuthenticationContext;
80  import org.eclipse.aether.repository.RemoteRepository;
81  import org.eclipse.aether.spi.connector.transport.AbstractTransporter;
82  import org.eclipse.aether.spi.connector.transport.GetTask;
83  import org.eclipse.aether.spi.connector.transport.PeekTask;
84  import org.eclipse.aether.spi.connector.transport.PutTask;
85  import org.eclipse.aether.spi.connector.transport.TransportListenerNotifyingInputStream;
86  import org.eclipse.aether.spi.connector.transport.TransportTask;
87  import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor;
88  import org.eclipse.aether.spi.connector.transport.http.HttpTransportPropertiesBuilder;
89  import org.eclipse.aether.spi.connector.transport.http.HttpTransporter;
90  import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException;
91  import org.eclipse.aether.spi.io.PathProcessor;
92  import org.eclipse.aether.transfer.HttpTransportProperty;
93  import org.eclipse.aether.transfer.NoTransporterException;
94  import org.eclipse.aether.transfer.TransferCancelledException;
95  import org.eclipse.aether.transfer.TransferEvent;
96  import org.eclipse.aether.util.ConfigUtils;
97  import org.eclipse.aether.util.connector.transport.TransporterUtils;
98  import org.eclipse.aether.util.connector.transport.http.HttpTransporterUtils;
99  import org.slf4j.Logger;
100 import org.slf4j.LoggerFactory;
101 
102 import static java.nio.charset.StandardCharsets.ISO_8859_1;
103 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.ACCEPT_ENCODING;
104 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CACHE_CONTROL;
105 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_LENGTH;
106 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE;
107 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE_PATTERN;
108 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.IF_UNMODIFIED_SINCE;
109 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.LAST_MODIFIED;
110 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.MULTIPLE_CHOICES;
111 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.PRECONDITION_FAILED;
112 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.RANGE;
113 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.USER_AGENT;
114 import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.CONFIG_PROP_HTTP_VERSION;
115 import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.CONFIG_PROP_MAX_CONCURRENT_REQUESTS;
116 import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.CONFIG_PROP_UNSCOPED_AUTHENTICATION;
117 import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.DEFAULT_MAX_CONCURRENT_REQUESTS;
118 import static org.eclipse.aether.transport.jdk.JdkTransporterConfigurationKeys.DEFAULT_UNSCOPED_AUTHENTICATION;
119 
120 /**
121  * JDK Transport using {@link HttpClient}.
122  * <p>
123  * Known issues:
124  * <ul>
125  *     <li>Does not properly support {@link ConfigurationProperties#REQUEST_TIMEOUT} prior Java 26, see <a href="https://bugs.openjdk.org/browse/JDK-8208693">JDK-8208693</a></li>
126  * </ul>
127  * <p>
128  * Related: <a href="https://dev.to/kdrakon/httpclient-can-t-connect-to-a-tls-proxy-118a">No TLS proxy supported</a>.
129  *
130  * @since 2.0.0
131  */
132 final class JdkTransporter extends AbstractTransporter implements HttpTransporter {
133     private static final Logger LOGGER = LoggerFactory.getLogger(JdkTransporter.class);
134 
135     private static final DateTimeFormatter RFC7231 = DateTimeFormatter.ofPattern(
136                     "EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH)
137             .withZone(ZoneId.of("GMT"));
138 
139     private static final Runtime.Version JAVA_17_0_17 = Runtime.Version.parse("17.0.17");
140     /**
141      * Returns {@code true} if the given JVM version supports the {@code Expect: 100-continue}
142      * header. Disabled on JDK 18.x and 19.x (unfixed JDK-8286171), and on JDK 17 before
143      * 17.0.17 (backport JDK-8364017). Enabled on 17.0.17+, and all versions 20+.
144      * @param version the JVM version to check
145      * @return {@code true} if Expect-Continue is supported
146      */
147     static boolean isExpectContinueSupported(Runtime.Version version) {
148         if (version.feature() >= 20) {
149             return true;
150         }
151         if (version.feature() == 17) {
152             return version.compareTo(JAVA_17_0_17) >= 0;
153         }
154         return false;
155     }
156 
157     private static final long MODIFICATION_THRESHOLD = 60L * 1000L;
158 
159     /**
160      * Maximum redirect hops followed when this transporter follows redirects itself (origin-scoped headers mode);
161      * same limit as the JDK {@link HttpClient}'s own default ({@code jdk.httpclient.redirects.retrylimit}).
162      */
163     private static final int MAX_REDIRECTS = 5;
164 
165     private static final String LOCATION = "Location";
166 
167     /**
168      * Classes of IOExceptions that should not be retried (because they are permanent failures).
169      * Same as in <a href="https://github.com/apache/httpcomponents-client/blob/54900db4653d7f207477e6ee40135b88e9bcf832/httpclient/src/main/java/org/apache/http/impl/client/DefaultHttpRequestRetryHandler.java#L102">
170      * Apache HttpClient's DefaultHttpRequestRetryHandler</a>.
171      */
172     private static final Set<Class<? extends IOException>> NON_RETRIABLE_IO_EXCEPTIONS = Set.of(
173             InterruptedIOException.class,
174             UnknownHostException.class,
175             ConnectException.class,
176             NoRouteToHostException.class,
177             SSLException.class);
178 
179     private final ChecksumExtractor checksumExtractor;
180 
181     private final PathProcessor pathProcessor;
182 
183     private final URI baseUri;
184 
185     private final HttpClient client;
186 
187     private final Map<String, String> headers;
188 
189     private final boolean originScopedHeaders;
190 
191     private final RedirectMode redirectMode;
192 
193     private final boolean followInsecureRedirect;
194 
195     private final Set<String> crossOriginExcludedHeaders;
196 
197     private final int connectTimeout;
198 
199     private final int requestTimeout;
200 
201     private final Boolean expectContinue;
202 
203     private final Semaphore maxConcurrentRequests;
204 
205     private final boolean preemptivePutAuth;
206 
207     private final boolean preemptiveAuth;
208 
209     private final boolean sendRfc9457Accept;
210 
211     private PasswordAuthentication serverAuthentication;
212 
213     private PasswordAuthentication proxyAuthentication;
214 
215     @SuppressWarnings("deprecation")
216     JdkTransporter(
217             RepositorySystemSession session,
218             RemoteRepository repository,
219             Runtime.Version javaVersion,
220             ChecksumExtractor checksumExtractor,
221             PathProcessor pathProcessor)
222             throws NoTransporterException {
223         this.checksumExtractor = checksumExtractor;
224         this.pathProcessor = pathProcessor;
225         try {
226             this.baseUri = HttpTransporterUtils.getBaseUri(repository);
227         } catch (URISyntaxException e) {
228             throw new NoTransporterException(repository, e.getMessage(), e);
229         }
230 
231         HashMap<String, String> headers = new HashMap<>();
232         String userAgent = HttpTransporterUtils.getUserAgent(session, repository);
233         if (userAgent != null) {
234             headers.put(USER_AGENT, userAgent);
235         }
236         Map<String, String> configuredHeaders = HttpTransporterUtils.getHttpHeaders(session, repository);
237         if (configuredHeaders != null) {
238             headers.putAll(configuredHeaders);
239         }
240         headers.put(CACHE_CONTROL, "no-cache, no-store");
241 
242         this.connectTimeout = HttpTransporterUtils.getHttpConnectTimeout(session, repository);
243         this.requestTimeout = HttpTransporterUtils.getHttpRequestTimeout(session, repository);
244         Optional<Boolean> expectContinue = HttpTransporterUtils.getHttpExpectContinue(session, repository);
245         if (isExpectContinueSupported(javaVersion)) {
246             this.expectContinue = expectContinue.orElse(null);
247         } else {
248             this.expectContinue = null;
249             if (expectContinue.isPresent()) {
250                 LOGGER.warn(
251                         "Configuration for Expect-Continue set but is ignored on Java version {} "
252                                 + "(supported on 17.0.17+ and 20+) due to "
253                                 + "https://bugs.openjdk.org/browse/JDK-8286171",
254                         javaVersion);
255             }
256         }
257         final String httpsSecurityMode = HttpTransporterUtils.getHttpsSecurityMode(session, repository);
258         final boolean insecure = ConfigurationProperties.HTTPS_SECURITY_MODE_INSECURE.equals(httpsSecurityMode);
259 
260         this.maxConcurrentRequests = new Semaphore(ConfigUtils.getInteger(
261                 session,
262                 DEFAULT_MAX_CONCURRENT_REQUESTS,
263                 CONFIG_PROP_MAX_CONCURRENT_REQUESTS + "." + repository.getId(),
264                 CONFIG_PROP_MAX_CONCURRENT_REQUESTS));
265 
266         this.preemptiveAuth = HttpTransporterUtils.isHttpPreemptiveAuth(session, repository);
267         this.preemptivePutAuth = HttpTransporterUtils.isHttpPreemptivePutAuth(session, repository);
268         this.sendRfc9457Accept = HttpTransporterUtils.isHttpSendRfc9457Accept(session, repository);
269 
270         this.originScopedHeaders = HttpTransporterUtils.isOriginScopedHeaders(
271                 session, repository, JdkTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS);
272         this.redirectMode = HttpTransporterUtils.getRedirectMode(session, repository);
273         this.followInsecureRedirect = HttpTransporterUtils.isFollowInsecureRedirect(session, repository);
274         TreeSet<String> crossOriginExcludedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
275         // preemptively applied Authorization (see #prepare) must never leave the repository origin either
276         crossOriginExcludedHeaders.add("Authorization");
277         if (configuredHeaders != null) {
278             crossOriginExcludedHeaders.addAll(configuredHeaders.keySet());
279         }
280         this.crossOriginExcludedHeaders = crossOriginExcludedHeaders;
281 
282         this.headers = headers;
283         this.client = createClient(session, repository, insecure);
284     }
285 
286     private URI resolve(TransportTask task) {
287         return baseUri.resolve(task.getLocation());
288     }
289 
290     private ConnectException enhance(ConnectException connectException) {
291         ConnectException result = new ConnectException("Connection to " + baseUri.toASCIIString() + " refused");
292         result.initCause(connectException);
293         return result;
294     }
295 
296     @Override
297     protected void implPeek(PeekTask task) throws Exception {
298         HttpRequest.Builder request =
299                 HttpRequest.newBuilder().uri(resolve(task)).method("HEAD", HttpRequest.BodyPublishers.noBody());
300         headers.forEach(request::setHeader);
301 
302         prepare(request);
303         try {
304             HttpResponse<Void> response = send(request.build(), HttpResponse.BodyHandlers.discarding());
305             task.getListener().transportPropertiesAvailable(createTransportProperties(response));
306             if (response.statusCode() >= MULTIPLE_CHOICES) {
307                 throw new HttpTransporterException(response.statusCode());
308             }
309         } catch (ConnectException e) {
310             throw enhance(e);
311         }
312     }
313 
314     @Override
315     protected void implGet(GetTask task) throws Exception {
316         boolean resume = task.getResumeOffset() > 0L && task.getDataPath() != null;
317         HttpResponse<InputStream> response = null;
318 
319         try {
320             while (true) {
321                 HttpRequest.Builder request =
322                         HttpRequest.newBuilder().uri(resolve(task)).GET();
323                 headers.forEach(request::setHeader);
324                 if (sendRfc9457Accept) {
325                     JdkRFC9457Reporter.INSTANCE.prepareRequest(request);
326                 }
327 
328                 if (resume) {
329                     long resumeOffset = task.getResumeOffset();
330                     long lastModified = pathProcessor.lastModified(task.getDataPath(), 0L);
331                     request.header(RANGE, "bytes=" + resumeOffset + '-');
332                     request.header(
333                             IF_UNMODIFIED_SINCE,
334                             RFC7231.format(Instant.ofEpochMilli(lastModified - MODIFICATION_THRESHOLD)));
335                     request.header(ACCEPT_ENCODING, "identity");
336                 }
337 
338                 prepare(request);
339                 try {
340                     response = send(request.build(), HttpResponse.BodyHandlers.ofInputStream());
341                     if (resume && response.statusCode() == PRECONDITION_FAILED) {
342                         // the local contents are outdated: discard this response and fetch the whole file
343                         closeBody(response);
344                         resume = false;
345                         continue;
346                     }
347                     task.getListener().transportPropertiesAvailable(createTransportProperties(response));
348                     if (response.statusCode() >= MULTIPLE_CHOICES) {
349                         JdkRFC9457Reporter.INSTANCE.generateException(response, (statusCode, reasonPhrase) -> {
350                             throw new HttpTransporterException(statusCode);
351                         });
352                     }
353                 } catch (ConnectException e) {
354                     throw enhance(e);
355                 }
356                 break;
357             }
358 
359             long offset = 0L,
360                     length = response.headers().firstValueAsLong(CONTENT_LENGTH).orElse(-1L);
361             if (resume) {
362                 String range = response.headers().firstValue(CONTENT_RANGE).orElse(null);
363                 if (range != null) {
364                     Matcher m = CONTENT_RANGE_PATTERN.matcher(range);
365                     if (!m.matches()) {
366                         throw new IOException("Invalid Content-Range header for partial download: " + range);
367                     }
368                     offset = Long.parseLong(m.group(1));
369                     length = Long.parseLong(m.group(2)) + 1L;
370                     if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) {
371                         throw new IOException("Invalid Content-Range header for partial download from offset "
372                                 + task.getResumeOffset() + ": " + range);
373                     }
374                 }
375             }
376 
377             final boolean downloadResumed = offset > 0L;
378             final Path dataFile = task.getDataPath();
379             if (dataFile == null) {
380                 try (InputStream is = response.body()) {
381                     utilGet(task, is, true, length, downloadResumed);
382                 }
383             } else {
384                 try (PathProcessor.CollocatedTempFile tempFile = pathProcessor.newTempFile(dataFile)) {
385                     task.setDataPath(tempFile.getPath(), downloadResumed);
386                     if (downloadResumed && Files.isRegularFile(dataFile)) {
387                         try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(dataFile))) {
388                             Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
389                         }
390                     }
391                     try (InputStream is = response.body()) {
392                         utilGet(task, is, true, length, downloadResumed);
393                     }
394                     tempFile.move();
395                 } finally {
396                     task.setDataPath(dataFile);
397                 }
398             }
399             if (task.getDataPath() != null) {
400                 String lastModifiedHeader = response.headers()
401                         .firstValue(LAST_MODIFIED)
402                         .orElse(null); // note: Wagon also does first not last
403                 if (lastModifiedHeader != null) {
404                     try {
405                         pathProcessor.setLastModified(
406                                 task.getDataPath(),
407                                 HttpTransporterUtils.clampRemoteLastModified(
408                                         ZonedDateTime.parse(lastModifiedHeader, RFC7231)
409                                                 .toInstant()
410                                                 .toEpochMilli()));
411                     } catch (DateTimeParseException e) {
412                         // fall through
413                     }
414                 }
415             }
416             Map<String, String> checksums = checksumExtractor.extractChecksums(headerGetter(response));
417             if (checksums != null && !checksums.isEmpty()) {
418                 checksums.forEach(task::setChecksum);
419             }
420         } finally {
421             closeBody(response);
422         }
423     }
424 
425     private Map<TransferEvent.TransportPropertyKey, Object> createTransportProperties(HttpResponse<?> response) {
426         HttpTransportPropertiesBuilder builder = new HttpTransportPropertiesBuilder(toHttpVersion(response.version()));
427         response.sslSession().ifPresent(ssl -> {
428             builder.withSslProtocol(ssl.getProtocol());
429             builder.withSslCipherSuite(ssl.getCipherSuite());
430         });
431         // TODO: add compression algorithm if any (https://github.com/mizosoft/methanol/issues/182)
432         return builder.build();
433     }
434 
435     static HttpTransportProperty.HttpVersion toHttpVersion(HttpClient.Version version) {
436         switch (version) {
437             case HTTP_1_1:
438                 return HttpTransportProperty.HttpVersion.HTTP_1_1;
439             case HTTP_2:
440                 return HttpTransportProperty.HttpVersion.HTTP_2;
441             default:
442                 // support HTTP_3 via name (as only part of Java 26+ API)
443                 if ("HTTP_3".equals(version.name())) {
444                     return HttpTransportProperty.HttpVersion.HTTP_3;
445                 } else {
446                     throw new IllegalArgumentException("Unsupported HTTP version: " + version);
447                 }
448         }
449     }
450 
451     private static Function<String, String> headerGetter(HttpResponse<?> response) {
452         return s -> response.headers().firstValue(s).orElse(null);
453     }
454 
455     private void closeBody(HttpResponse<InputStream> streamHttpResponse) throws IOException {
456         if (streamHttpResponse != null) {
457             InputStream body = streamHttpResponse.body();
458             if (body != null) {
459                 body.close();
460             }
461         }
462     }
463 
464     @Override
465     protected void implPut(PutTask task) throws Exception {
466         HttpRequest.Builder request = HttpRequest.newBuilder().uri(resolve(task));
467         if (expectContinue != null) {
468             request = request.expectContinue(expectContinue);
469         }
470         headers.forEach(request::setHeader);
471         if (sendRfc9457Accept) {
472             JdkRFC9457Reporter.INSTANCE.prepareRequest(request);
473         }
474         if (task.getDataLength() == 0L) {
475             request.PUT(HttpRequest.BodyPublishers.noBody());
476         } else {
477             request.PUT(HttpRequest.BodyPublishers.fromPublisher(
478                     HttpRequest.BodyPublishers.ofInputStream(() -> {
479                         try {
480                             // transport properties are not available for outgoing requests
481                             return new TransportListenerNotifyingInputStream(
482                                     task.newInputStream(), task.getListener(), task.getDataLength());
483                         } catch (IOException e) {
484                             throw new UncheckedIOException(e);
485                         }
486                     }),
487                     // this adds a content-length request header
488                     task.getDataLength()));
489         }
490         prepare(request);
491         HttpResponse<InputStream> response = null;
492         try {
493             response = send(request.build(), HttpResponse.BodyHandlers.ofInputStream());
494             task.getListener().transportPropertiesAvailable(createTransportProperties(response));
495             if (response.statusCode() >= MULTIPLE_CHOICES) {
496                 JdkRFC9457Reporter.INSTANCE.generateException(response, (statusCode, reasonPhrase) -> {
497                     throw new HttpTransporterException(statusCode);
498                 });
499             }
500         } catch (ConnectException e) {
501             throw enhance(e);
502         } catch (IOException e) {
503             // unwrap possible underlying exception from body supplier
504             Throwable rootCause = getRootCause(e);
505             if (rootCause instanceof TransferCancelledException) {
506                 throw (TransferCancelledException) rootCause;
507             }
508             throw e;
509         } finally {
510             closeBody(response);
511         }
512     }
513 
514     private void prepare(HttpRequest.Builder requestBuilder) {
515         if (preemptiveAuth
516                 || (preemptivePutAuth && requestBuilder.build().method().equals("PUT"))) {
517             if (serverAuthentication != null) {
518                 // https://stackoverflow.com/a/58612586
519                 requestBuilder.setHeader(
520                         "Authorization",
521                         getBasicAuthValue(serverAuthentication.getUserName(), serverAuthentication.getPassword()));
522             }
523             if (proxyAuthentication != null) {
524                 requestBuilder.setHeader(
525                         "Proxy-Authorization",
526                         getBasicAuthValue(proxyAuthentication.getUserName(), proxyAuthentication.getPassword()));
527             }
528         }
529     }
530 
531     static String getBasicAuthValue(String username, char[] password) {
532         // Java's HTTP client uses ISO-8859-1 for Basic auth encoding
533         return "Basic "
534                 + Base64.getEncoder().encodeToString((username + ':' + String.valueOf(password)).getBytes(ISO_8859_1));
535     }
536 
537     private <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)
538             throws Exception {
539         maxConcurrentRequests.acquire();
540         try {
541             if (redirectMode == RedirectMode.ANY && !originScopedHeaders && !followInsecureRedirect) {
542                 return client.send(request, responseBodyHandler);
543             }
544             // the client is configured with Redirect.NEVER: follow redirects here instead, so that configured
545             // headers (and preemptively applied Authorization) can be scoped to the repository origin per hop -
546             // the JDK client itself re-sends all user-set headers on every hop it follows, with no per-hop hook
547             HttpRequest current = request;
548             int redirects = 0;
549             while (true) {
550                 HttpResponse<T> response = client.send(
551                         current,
552                         discardingOnFollowedRedirect(
553                                 responseBodyHandler, current.uri(), followInsecureRedirect, redirectMode));
554                 URI target = followableRedirect(
555                         response.statusCode(),
556                         current.uri(),
557                         response.headers().firstValue(LOCATION).orElse(null),
558                         followInsecureRedirect,
559                         redirectMode);
560                 if (target == null) {
561                     return response;
562                 }
563                 redirects++;
564                 if (redirects > MAX_REDIRECTS) {
565                     throw new IOException("Too many redirects for " + request.uri() + " (max " + MAX_REDIRECTS
566                             + "), last redirect target: " + target);
567                 }
568                 current = redirectRequest(
569                         current,
570                         response.statusCode(),
571                         target,
572                         baseUri,
573                         originScopedHeaders ? crossOriginExcludedHeaders : Set.of());
574             }
575         } finally {
576             maxConcurrentRequests.release();
577         }
578     }
579 
580     /**
581      * Body handler that discards the body of responses this transporter is about to follow as redirect (the
582      * caller only ever sees the final response of the hop chain), delegating everything else to the original
583      * handler.
584      */
585     private static <T> HttpResponse.BodyHandler<T> discardingOnFollowedRedirect(
586             HttpResponse.BodyHandler<T> delegate,
587             URI requestUri,
588             boolean followInsecureRedirect,
589             RedirectMode redirectMode) {
590         return responseInfo -> {
591             String location = responseInfo.headers().firstValue(LOCATION).orElse(null);
592             if (followableRedirect(
593                             responseInfo.statusCode(), requestUri, location, followInsecureRedirect, redirectMode)
594                     != null) {
595                 return HttpResponse.BodySubscribers.mapping(HttpResponse.BodySubscribers.discarding(), v -> null);
596             }
597             return delegate.apply(responseInfo);
598         };
599     }
600 
601     /**
602      * Returns the resolved redirect target if the response is a redirect this transporter follows, otherwise
603      * {@code null}. Follow rules mirror {@link HttpClient.Redirect#NORMAL}: redirect status with a resolvable
604      * {@code Location}, {@code http}/{@code https} targets only, and never a downgrade from https to http unless
605      * configured.
606      */
607     static URI followableRedirect(int statusCode, URI requestUri, String locationHeader) {
608         return followableRedirect(statusCode, requestUri, locationHeader, false, RedirectMode.ANY);
609     }
610 
611     static URI followableRedirect(
612             int statusCode, URI requestUri, String locationHeader, boolean followInsecureRedirect) {
613         return followableRedirect(statusCode, requestUri, locationHeader, followInsecureRedirect, RedirectMode.ANY);
614     }
615 
616     static URI followableRedirect(
617             int statusCode,
618             URI requestUri,
619             String locationHeader,
620             boolean followInsecureRedirect,
621             RedirectMode redirectMode) {
622         if (redirectMode == RedirectMode.NONE) {
623             return null;
624         }
625         if (!isRedirect(statusCode) || locationHeader == null) {
626             return null;
627         }
628         final URI target;
629         try {
630             target = requestUri.resolve(locationHeader);
631         } catch (IllegalArgumentException e) {
632             return null;
633         }
634         String scheme = target.getScheme();
635         if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
636             return null;
637         }
638         if (!followInsecureRedirect
639                 && "https".equalsIgnoreCase(requestUri.getScheme())
640                 && !"https".equalsIgnoreCase(scheme)) {
641             return null;
642         }
643         if (redirectMode == RedirectMode.SAME_AUTHORITY && !TransporterUtils.isSameAuthority(requestUri, target)) {
644             return null;
645         }
646         return target;
647     }
648 
649     static boolean isRedirect(int statusCode) {
650         return statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307 || statusCode == 308;
651     }
652 
653     /**
654      * Builds the next-hop request: the previous request re-targeted at the redirect target, with the origin-scoped
655      * headers (operator-configured headers and preemptively applied {@code Authorization}) removed when the target
656      * is not the repository origin (same scheme, case-insensitive host and effective port). Method rewriting
657      * mirrors {@link HttpClient.Redirect#NORMAL}.
658      */
659     static HttpRequest redirectRequest(
660             HttpRequest previous, int statusCode, URI target, URI baseUri, Set<String> crossOriginExcludedHeaders) {
661         HttpRequest.Builder builder = HttpRequest.newBuilder().uri(target).expectContinue(previous.expectContinue());
662         previous.version().ifPresent(builder::version);
663         previous.timeout().ifPresent(builder::timeout);
664         boolean sameOrigin = TransporterUtils.isSameOrigin(baseUri, target);
665         previous.headers().map().forEach((name, values) -> {
666             if (sameOrigin || !crossOriginExcludedHeaders.contains(name)) {
667                 for (String value : values) {
668                     builder.header(name, value);
669                 }
670             }
671         });
672         String method = previous.method();
673         if (statusCode == 303 && !"HEAD".equals(method)) {
674             builder.method("GET", HttpRequest.BodyPublishers.noBody());
675         } else if ((statusCode == 301 || statusCode == 302) && "POST".equals(method)) {
676             builder.method("GET", HttpRequest.BodyPublishers.noBody());
677         } else {
678             builder.method(method, previous.bodyPublisher().orElse(HttpRequest.BodyPublishers.noBody()));
679         }
680         return builder.build();
681     }
682 
683     @Override
684     protected void implClose() {
685         if (client != null) {
686             JdkTransporterCloser.closer(client).run();
687         }
688     }
689 
690     HttpClient.Version getHttpVersion(RepositorySystemSession session, RemoteRepository repository) {
691         HttpVersion httpVersion = HttpTransporterUtils.getHttpVersion(session, repository);
692         if (httpVersion == ConfigurationProperties.DEFAULT_HTTP_VERSION) {
693             // Fall back to legacy JDK Transporter specific property when it is explicitly configured.
694             @SuppressWarnings("deprecation")
695             String legacyHttpVersionKey = CONFIG_PROP_HTTP_VERSION;
696             String configuredLegacyHttpVersion = ConfigUtils.getString(
697                     session, null, legacyHttpVersionKey + "." + repository.getId(), legacyHttpVersionKey);
698             if (configuredLegacyHttpVersion != null) {
699                 return resolveHttpVersion(configuredLegacyHttpVersion);
700             }
701             return HttpClient.Version.HTTP_2;
702         } else {
703             switch (httpVersion) {
704                 case MAXIMUM:
705                     return getMaximumSupportedHttpVersion();
706                 case HTTP_1_1:
707                     return HttpClient.Version.HTTP_1_1;
708                 case HTTP_2:
709                 case DEFAULT:
710                     return HttpClient.Version.HTTP_2;
711                 case HTTP_3:
712                     return resolveHttpVersion("HTTP_3");
713                 default:
714                     // unreachable but necessary for Checkstyle to not complain about missing default case
715                     throw new IllegalStateException("Unknown HTTP version: " + httpVersion);
716             }
717         }
718     }
719 
720     private HttpClient.Version resolveHttpVersion(String requestedVersion) {
721         try {
722             return HttpClient.Version.valueOf(requestedVersion);
723         } catch (IllegalArgumentException e) {
724             HttpClient.Version maximumHttpVersion = getMaximumSupportedHttpVersion();
725             LOGGER.warn(
726                     "HTTP version '{}' is not supported by the running JRE, using '{}' instead",
727                     requestedVersion,
728                     maximumHttpVersion);
729             return maximumHttpVersion;
730         }
731     }
732 
733     HttpClient.Version getMaximumSupportedHttpVersion() {
734         HttpClient.Version[] values = HttpClient.Version.values();
735         return values[values.length - 1];
736     }
737 
738     private HttpClient createClient(RepositorySystemSession session, RemoteRepository repository, boolean insecure)
739             throws RuntimeException {
740 
741         HashMap<Authenticator.RequestorType, PasswordAuthentication> authentications = new HashMap<>();
742         SSLContext sslContext = null;
743         try (AuthenticationContext repoAuthContext = AuthenticationContext.forRepository(session, repository)) {
744             if (repoAuthContext != null) {
745                 sslContext = repoAuthContext.get(AuthenticationContext.SSL_CONTEXT, SSLContext.class);
746 
747                 String username = repoAuthContext.get(AuthenticationContext.USERNAME);
748                 String password = repoAuthContext.get(AuthenticationContext.PASSWORD);
749                 serverAuthentication = new PasswordAuthentication(username, password.toCharArray());
750                 authentications.put(Authenticator.RequestorType.SERVER, serverAuthentication);
751             }
752         }
753 
754         Version httpVersion = getHttpVersion(session, repository);
755         if (sslContext == null) {
756             try {
757                 if (insecure) {
758                     if (httpVersion.name().equals("HTTP_3")) {
759                         // custom trust manager not supported for HTTP/3 (Quic)
760                         // (https://github.com/openjdk/jdk/blob/631b675d7949a0e6312d8d6f45e2515d53b12f05/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java#L529)
761                         // https://openjdk.org/jeps/517
762                         // https://mail.openjdk.org/archives/list/net-dev@openjdk.org/thread/LHSC7MWRFDJE2KGS2QMPFJPZX3XEQKOQ/
763                         throw new IllegalStateException(
764                                 "Insecure HTTPS connections are not supported for HTTP/3 (Quic)");
765                     }
766                     sslContext = SSLContext.getInstance("TLS");
767                     X509ExtendedTrustManager tm = new X509ExtendedTrustManager() {
768                         @Override
769                         public void checkClientTrusted(X509Certificate[] chain, String authType) {}
770 
771                         @Override
772                         public void checkServerTrusted(X509Certificate[] chain, String authType) {}
773 
774                         @Override
775                         public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) {}
776 
777                         @Override
778                         public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) {}
779 
780                         @Override
781                         public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {}
782 
783                         @Override
784                         public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {}
785 
786                         @Override
787                         public X509Certificate[] getAcceptedIssuers() {
788                             return null;
789                         }
790                     };
791                     sslContext.init(null, new X509TrustManager[] {tm}, null);
792                 } else {
793                     sslContext = SSLContext.getDefault();
794                 }
795             } catch (Exception e) {
796                 if (e instanceof RuntimeException) {
797                     throw (RuntimeException) e;
798                 } else {
799                     throw new IllegalStateException("SSL Context setup failure", e);
800                 }
801             }
802         } else {
803             if (insecure) {
804                 throw new IllegalStateException(
805                         "Insecure HTTPS connections are not supported when a custom SSLContext is configured");
806             }
807         }
808 
809         Methanol.Builder builder = Methanol.newBuilder()
810                 .version(httpVersion)
811                 // with origin-scoped headers (default) the transporter follows redirects itself (see #send) so
812                 // that configured headers can be dropped on hops leaving the repository origin; the JDK client
813                 // has no per-hop hook and re-sends all user-set headers on every hop it follows
814                 .followRedirects(
815                         redirectMode != RedirectMode.ANY || originScopedHeaders || followInsecureRedirect
816                                 ? HttpClient.Redirect.NEVER
817                                 : HttpClient.Redirect.NORMAL)
818                 .connectTimeout(Duration.ofMillis(connectTimeout))
819                 // this only considers the time until the response header is received, see
820                 // https://bugs.openjdk.org/browse/JDK-8208693
821                 // but better than nothing
822                 .requestTimeout(Duration.ofMillis(requestTimeout))
823                 .sslContext(sslContext);
824 
825         if (insecure) {
826             SSLParameters sslParameters = sslContext.getDefaultSSLParameters();
827             sslParameters.setEndpointIdentificationAlgorithm(null);
828             builder.sslParameters(sslParameters);
829         }
830 
831         setLocalAddress(
832                 builder,
833                 HttpTransporterUtils.getHttpLocalAddress(session, repository).orElse(null));
834 
835         InetSocketAddress proxyAddress = null;
836         if (repository.getProxy() != null) {
837             proxyAddress = new InetSocketAddress(
838                     repository.getProxy().getHost(), repository.getProxy().getPort());
839             if (proxyAddress.isUnresolved()) {
840                 throw new IllegalStateException(
841                         "Proxy host " + repository.getProxy().getHost() + " could not be resolved");
842             }
843             builder.proxy(ProxySelector.of(proxyAddress));
844             try (AuthenticationContext proxyAuthContext = AuthenticationContext.forProxy(session, repository)) {
845                 if (proxyAuthContext != null) {
846                     String username = proxyAuthContext.get(AuthenticationContext.USERNAME);
847                     String password = proxyAuthContext.get(AuthenticationContext.PASSWORD);
848 
849                     proxyAuthentication = new PasswordAuthentication(username, password.toCharArray());
850                     authentications.put(Authenticator.RequestorType.PROXY, proxyAuthentication);
851                 }
852             }
853         }
854 
855         if (!authentications.isEmpty()) {
856             boolean unscopedAuthentication = ConfigUtils.getBoolean(
857                     session,
858                     DEFAULT_UNSCOPED_AUTHENTICATION,
859                     CONFIG_PROP_UNSCOPED_AUTHENTICATION + "." + repository.getId(),
860                     CONFIG_PROP_UNSCOPED_AUTHENTICATION);
861             if (unscopedAuthentication) {
862                 // legacy behavior, explicit opt-in only: hands out credentials to ANY challenging host
863                 builder.authenticator(new Authenticator() {
864                     @Override
865                     protected PasswordAuthentication getPasswordAuthentication() {
866                         return authentications.get(getRequestorType());
867                     }
868                 });
869             } else {
870                 builder.authenticator(new ScopedAuthenticator(baseUri, proxyAddress, authentications));
871             }
872         }
873 
874         configureRetryHandler(session, repository, builder);
875 
876         return builder.build();
877     }
878 
879     /**
880      * An {@link Authenticator} that only hands out credentials to the origin it was configured for. The JDK
881      * {@link HttpClient} consults the authenticator for any host that answers with an authentication challenge -
882      * including hosts reached by following redirects off the repository - so the requesting protocol, host and
883      * port must be verified against the repository base URI (or, for proxy challenges, against the configured
884      * proxy address) before any credential is returned. Legacy unscoped behavior is available as explicit opt-in
885      * via {@link JdkTransporterConfigurationKeys#CONFIG_PROP_UNSCOPED_AUTHENTICATION}.
886      */
887     static final class ScopedAuthenticator extends Authenticator {
888         private final URI baseUri;
889 
890         private final InetSocketAddress proxyAddress;
891 
892         private final Map<RequestorType, PasswordAuthentication> authentications;
893 
894         ScopedAuthenticator(
895                 URI baseUri,
896                 InetSocketAddress proxyAddress,
897                 Map<RequestorType, PasswordAuthentication> authentications) {
898             this.baseUri = Objects.requireNonNull(baseUri);
899             this.proxyAddress = proxyAddress;
900             this.authentications = new HashMap<>(authentications);
901         }
902 
903         @Override
904         protected PasswordAuthentication getPasswordAuthentication() {
905             PasswordAuthentication authentication = authentications.get(getRequestorType());
906             if (authentication == null) {
907                 return null;
908             }
909             if (getRequestorType() == RequestorType.PROXY) {
910                 if (proxyAddress == null
911                         || getRequestingHost() == null
912                         || !proxyAddress.getHostString().equalsIgnoreCase(getRequestingHost())
913                         || proxyAddress.getPort() != getRequestingPort()) {
914                     LOGGER.warn(
915                             "Refusing to send proxy credentials to '{}:{}': not the configured proxy '{}'",
916                             getRequestingHost(),
917                             getRequestingPort(),
918                             proxyAddress);
919                     return null;
920                 }
921                 return authentication;
922             }
923             // RequestorType.SERVER: the challenge must originate from the repository itself
924             if (!originMatchesBaseUri(getRequestingProtocol(), getRequestingHost(), getRequestingPort())) {
925                 LOGGER.warn(
926                         "Refusing to send repository credentials to '{}://{}:{}': it does not match the repository"
927                                 + " base URI '{}' (a redirect may have left the repository host); set the"
928                                 + " configuration property {}=true to restore the legacy unscoped behavior",
929                         getRequestingProtocol(),
930                         getRequestingHost(),
931                         getRequestingPort(),
932                         baseUri,
933                         CONFIG_PROP_UNSCOPED_AUTHENTICATION);
934                 return null;
935             }
936             return authentication;
937         }
938 
939         private boolean originMatchesBaseUri(String protocol, String host, int port) {
940             if (protocol == null || host == null || baseUri.getScheme() == null || baseUri.getHost() == null) {
941                 return false;
942             }
943             try {
944                 URI requestingUri = new URI(protocol, null, host, port, null, null, null);
945                 return TransporterUtils.isSameOrigin(baseUri, requestingUri);
946             } catch (URISyntaxException e) {
947                 return false;
948             }
949         }
950     }
951 
952     private static class RetryLoggingListener implements RetryInterceptor.Listener {
953         private final int maxNumRetries;
954 
955         RetryLoggingListener(int maxNumRetries) {
956             this.maxNumRetries = maxNumRetries;
957         }
958 
959         @Override
960         public void onRetry(Context<?> context, HttpRequest nextRequest, Duration delay) {
961             if (context.exception().isPresent()) {
962                 HttpTransporter.logImmediateRetry(
963                         LOGGER,
964                         context.request().method(),
965                         context.request().uri(),
966                         context.retryCount(),
967                         maxNumRetries + 1,
968                         context.exception().get());
969             } else if (context.response().isPresent()) {
970                 // Methanol does not expose the reason for the backoff delay
971                 // (https://github.com/mizosoft/methanol/issues/200)
972                 HttpTransporter.logRetry(
973                         LOGGER,
974                         context.request().method(),
975                         context.request().uri(),
976                         context.retryCount(),
977                         maxNumRetries + 1,
978                         "status " + context.response().get().statusCode(),
979                         delay.toMillis(),
980                         "");
981             } else {
982                 throw new IllegalStateException("Retry context has neither exception nor response");
983             }
984         }
985     }
986 
987     private static void configureRetryHandler(
988             RepositorySystemSession session, RemoteRepository repository, Methanol.Builder builder) {
989         int retryCount = HttpTransporterUtils.getHttpRetryHandlerCount(session, repository);
990         long retryInterval = HttpTransporterUtils.getHttpRetryHandlerInterval(session, repository);
991         long retryIntervalMax = HttpTransporterUtils.getHttpRetryHandlerIntervalMax(session, repository);
992         if (retryCount > 0) {
993             Methanol.Interceptor rateLimitingRetryInterceptor = RetryInterceptor.newBuilder()
994                     .maxRetries(retryCount)
995                     .onStatus(HttpTransporterUtils.getHttpServiceUnavailableCodes(session, repository)::contains)
996                     .listener(new RetryLoggingListener(retryCount))
997                     .backoff(RetryInterceptor.BackoffStrategy.retryAfterOr(RetryInterceptor.BackoffStrategy.linear(
998                             Duration.ofMillis(retryInterval), Duration.ofMillis(retryIntervalMax))))
999                     .build();
1000             builder.interceptor(rateLimitingRetryInterceptor);
1001             Methanol.Interceptor retryIoExceptionsInterceptor = RetryInterceptor.newBuilder()
1002                     // this is in addition to the JDK internal retries (https://github.com/mizosoft/methanol/issues/174)
1003                     // e.g. for connection timeouts this is hardcoded to 2 attempts:
1004                     // https://github.com/openjdk/jdk/blob/640343f7d94894b0378ea5b1768eeac203a9aaf8/src/java.net.http/share/classes/jdk/internal/net/http/MultiExchange.java#L665
1005                     .maxRetries(retryCount)
1006                     .onException(t -> {
1007                         // exceptions from body publishers are wrapped inside IOExceptions
1008                         // but hard to distinguish from others, so just exclude some we know are emitted from body
1009                         // suppliers (https://github.com/mizosoft/methanol/issues/179)
1010                         Throwable rootCause = getRootCause(t);
1011                         return t instanceof IOException
1012                                 && !NON_RETRIABLE_IO_EXCEPTIONS.contains(t.getClass())
1013                                 && !(rootCause instanceof TransferCancelledException);
1014                     })
1015                     .listener(new RetryLoggingListener(retryCount))
1016                     .build();
1017             builder.interceptor(retryIoExceptionsInterceptor);
1018         }
1019     }
1020 
1021     private static void setLocalAddress(HttpClient.Builder builder, InetAddress address) {
1022         if (address == null) {
1023             return;
1024         }
1025         try {
1026             final Method mtd = builder.getClass().getDeclaredMethod("localAddress", InetAddress.class);
1027             if (!mtd.canAccess(builder)) {
1028                 mtd.setAccessible(true);
1029             }
1030             mtd.invoke(builder, address);
1031         } catch (final NoSuchMethodException ignore) {
1032             // skip, not yet in the API
1033         } catch (InvocationTargetException e) {
1034             throw new IllegalStateException(e.getTargetException());
1035         } catch (IllegalAccessException e) {
1036             throw new IllegalStateException(e);
1037         }
1038     }
1039 
1040     private static Throwable getRootCause(Throwable throwable) {
1041         Objects.requireNonNull(throwable);
1042         Throwable rootCause = throwable;
1043         while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
1044             rootCause = rootCause.getCause();
1045         }
1046         return rootCause;
1047     }
1048 }