1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
122
123
124
125
126
127
128
129
130
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
142
143
144
145
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
161
162
163 private static final int MAX_REDIRECTS = 5;
164
165 private static final String LOCATION = "Location";
166
167
168
169
170
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
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
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);
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
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
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
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
481 return new TransportListenerNotifyingInputStream(
482 task.newInputStream(), task.getListener(), task.getDataLength());
483 } catch (IOException e) {
484 throw new UncheckedIOException(e);
485 }
486 }),
487
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
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
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
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
545
546
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
582
583
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
603
604
605
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
655
656
657
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
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
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
760
761
762
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
812
813
814 .followRedirects(
815 redirectMode != RedirectMode.ANY || originScopedHeaders || followInsecureRedirect
816 ? HttpClient.Redirect.NEVER
817 : HttpClient.Redirect.NORMAL)
818 .connectTimeout(Duration.ofMillis(connectTimeout))
819
820
821
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
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
881
882
883
884
885
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
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
971
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
1003
1004
1005 .maxRetries(retryCount)
1006 .onException(t -> {
1007
1008
1009
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
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 }