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.jetty;
20  
21  import javax.net.ssl.SSLContext;
22  
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.net.URI;
26  import java.net.URISyntaxException;
27  import java.nio.ByteBuffer;
28  import java.nio.file.Files;
29  import java.nio.file.Path;
30  import java.nio.file.StandardCopyOption;
31  import java.security.NoSuchAlgorithmException;
32  import java.util.ArrayList;
33  import java.util.Collection;
34  import java.util.HashMap;
35  import java.util.Map;
36  import java.util.TreeSet;
37  import java.util.concurrent.ExecutionException;
38  import java.util.concurrent.TimeUnit;
39  import java.util.concurrent.TimeoutException;
40  import java.util.concurrent.atomic.AtomicBoolean;
41  import java.util.concurrent.atomic.AtomicReference;
42  import java.util.function.Function;
43  import java.util.regex.Matcher;
44  
45  import org.eclipse.aether.ConfigurationProperties;
46  import org.eclipse.aether.ConfigurationProperties.HttpVersion;
47  import org.eclipse.aether.ConfigurationProperties.RedirectMode;
48  import org.eclipse.aether.RepositorySystemSession;
49  import org.eclipse.aether.repository.AuthenticationContext;
50  import org.eclipse.aether.repository.RemoteRepository;
51  import org.eclipse.aether.spi.connector.transport.AbstractTransporter;
52  import org.eclipse.aether.spi.connector.transport.GetTask;
53  import org.eclipse.aether.spi.connector.transport.PeekTask;
54  import org.eclipse.aether.spi.connector.transport.PutTask;
55  import org.eclipse.aether.spi.connector.transport.TransportTask;
56  import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor;
57  import org.eclipse.aether.spi.connector.transport.http.HttpTransportPropertiesBuilder;
58  import org.eclipse.aether.spi.connector.transport.http.HttpTransporter;
59  import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException;
60  import org.eclipse.aether.spi.io.PathProcessor;
61  import org.eclipse.aether.transfer.HttpTransportProperty;
62  import org.eclipse.aether.transfer.NoTransporterException;
63  import org.eclipse.aether.transfer.TransferCancelledException;
64  import org.eclipse.aether.transfer.TransferEvent;
65  import org.eclipse.aether.util.ConfigUtils;
66  import org.eclipse.aether.util.connector.transport.http.HttpTransporterUtils;
67  import org.eclipse.jetty.client.Authentication;
68  import org.eclipse.jetty.client.BasicAuthentication;
69  import org.eclipse.jetty.client.HttpClient;
70  import org.eclipse.jetty.client.HttpProxy;
71  import org.eclipse.jetty.client.InputStreamResponseListener;
72  import org.eclipse.jetty.client.Request;
73  import org.eclipse.jetty.client.Response;
74  import org.eclipse.jetty.client.transport.HttpClientConnectionFactory;
75  import org.eclipse.jetty.client.transport.HttpClientTransportDynamic;
76  import org.eclipse.jetty.http.HttpField;
77  import org.eclipse.jetty.http.HttpHeader;
78  import org.eclipse.jetty.http2.client.HTTP2Client;
79  import org.eclipse.jetty.http2.client.transport.ClientConnectionFactoryOverHTTP2;
80  import org.eclipse.jetty.http3.client.HTTP3Client;
81  import org.eclipse.jetty.http3.client.HTTP3ClientQuicConfiguration;
82  import org.eclipse.jetty.http3.client.transport.ClientConnectionFactoryOverHTTP3;
83  import org.eclipse.jetty.io.ClientConnectionFactory;
84  import org.eclipse.jetty.io.ClientConnector;
85  import org.eclipse.jetty.io.EndPoint.SslSessionData;
86  import org.eclipse.jetty.quic.quiche.client.QuicheClientQuicConfiguration;
87  import org.eclipse.jetty.quic.quiche.client.QuicheTransport;
88  import org.eclipse.jetty.util.ssl.SslContextFactory;
89  import org.slf4j.Logger;
90  import org.slf4j.LoggerFactory;
91  
92  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.ACCEPT_ENCODING;
93  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_LENGTH;
94  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE;
95  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE_PATTERN;
96  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.IF_UNMODIFIED_SINCE;
97  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.LAST_MODIFIED;
98  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.MULTIPLE_CHOICES;
99  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.PRECONDITION_FAILED;
100 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.RANGE;
101 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.USER_AGENT;
102 
103 /**
104  * A transporter for HTTP/HTTPS.
105  *
106  * @since 2.0.0
107  */
108 final class JettyTransporter extends AbstractTransporter implements HttpTransporter {
109     private static final Logger LOGGER = LoggerFactory.getLogger(JettyTransporter.class);
110 
111     private static final long MODIFICATION_THRESHOLD = 60L * 1000L;
112 
113     private final RepositorySystemSession session;
114 
115     private final RemoteRepository repository;
116 
117     private final ChecksumExtractor checksumExtractor;
118 
119     private final PathProcessor pathProcessor;
120 
121     private final URI baseUri;
122 
123     private final HttpClient client;
124 
125     private final int connectTimeout;
126 
127     private final int requestTimeout;
128 
129     private final JettyRetryHandler retryHandler;
130 
131     private final Map<String, String> headers;
132 
133     private final boolean preemptiveAuth;
134 
135     private final boolean preemptivePutAuth;
136 
137     private final boolean sendRfc9457Accept;
138 
139     private final boolean insecure;
140 
141     private final AtomicReference<BasicAuthentication.BasicResult> basicServerAuthenticationResult;
142 
143     private final AtomicReference<BasicAuthentication.BasicResult> basicProxyAuthenticationResult;
144 
145     JettyTransporter(
146             RepositorySystemSession session,
147             RemoteRepository repository,
148             ChecksumExtractor checksumExtractor,
149             PathProcessor pathProcessor)
150             throws NoTransporterException {
151         this.session = session;
152         this.repository = repository;
153         this.checksumExtractor = checksumExtractor;
154         this.pathProcessor = pathProcessor;
155         try {
156             this.baseUri = HttpTransporterUtils.getBaseUri(repository);
157         } catch (URISyntaxException e) {
158             throw new NoTransporterException(repository, e.getMessage(), e);
159         }
160 
161         HashMap<String, String> headers = new HashMap<>();
162         String userAgent = HttpTransporterUtils.getUserAgent(session, repository);
163         if (userAgent != null) {
164             headers.put(USER_AGENT, userAgent);
165         }
166         Map<String, String> configuredHeaders = HttpTransporterUtils.getHttpHeaders(session, repository);
167         if (configuredHeaders != null) {
168             headers.putAll(configuredHeaders);
169         }
170 
171         this.headers = headers;
172 
173         this.connectTimeout = HttpTransporterUtils.getHttpConnectTimeout(session, repository);
174         this.requestTimeout = HttpTransporterUtils.getHttpRequestTimeout(session, repository);
175         this.retryHandler = new JettyRetryHandler(session, repository);
176         this.preemptiveAuth = HttpTransporterUtils.isHttpPreemptiveAuth(session, repository);
177         this.preemptivePutAuth = HttpTransporterUtils.isHttpPreemptivePutAuth(session, repository);
178         this.sendRfc9457Accept = HttpTransporterUtils.isHttpSendRfc9457Accept(session, repository);
179         final String httpsSecurityMode = HttpTransporterUtils.getHttpsSecurityMode(session, repository);
180         this.insecure = ConfigurationProperties.HTTPS_SECURITY_MODE_INSECURE.equals(httpsSecurityMode);
181 
182         this.basicServerAuthenticationResult = new AtomicReference<>(null);
183         this.basicProxyAuthenticationResult = new AtomicReference<>(null);
184         this.client = createClient();
185     }
186 
187     private void mayApplyPreemptiveAuth(Request request) {
188         if (basicServerAuthenticationResult.get() != null) {
189             basicServerAuthenticationResult.get().apply(request);
190         }
191         if (basicProxyAuthenticationResult.get() != null) {
192             basicProxyAuthenticationResult.get().apply(request);
193         }
194     }
195 
196     private URI resolve(TransportTask task) {
197         return baseUri.resolve(task.getLocation());
198     }
199 
200     /**
201      * Logs that the request is sent again right away, after the given attempt failed without a (retriable) response.
202      */
203     private void logImmediateRetry(Request request, int attempt, Throwable failure) {
204         HttpTransporter.logImmediateRetry(
205                 LOGGER, request.getMethod(), request.getURI(), attempt, retryHandler.getRetryCount() + 1, failure);
206     }
207 
208     /**
209      * Logs and waits until the request is sent again, after the given attempt got a retriable response.
210      */
211     private void waitBeforeRetry(Request request, int attempt, Response response) throws InterruptedException {
212         JettyRetryHandler.Delay delay = retryHandler.getDelay(response.getHeaders(), attempt);
213         HttpTransporter.logRetry(
214                 LOGGER,
215                 request.getMethod(),
216                 request.getURI(),
217                 attempt,
218                 retryHandler.getRetryCount() + 1,
219                 "status " + response.getStatus(),
220                 delay.millis(),
221                 delay.reason());
222         if (delay.millis() > 0L) {
223             Thread.sleep(delay.millis());
224         }
225     }
226 
227     @Override
228     protected void implPeek(PeekTask task) throws Exception {
229         for (int attempt = 0; ; attempt++) {
230             Request request = client.newRequest(resolve(task)).method("HEAD");
231             request.headers(m -> headers.forEach(m::add));
232             if (preemptiveAuth) {
233                 mayApplyPreemptiveAuth(request);
234             }
235             // capture raw response headers as described in https://github.com/jetty/jetty.project/discussions/14404
236             Map<String, HttpField> rawResponseHeaders = new HashMap<>();
237             request.onResponseHeader((r, field) -> {
238                 rawResponseHeaders.put(field.getLowerCaseName(), field);
239                 return true; // continue processing
240             });
241             Response response;
242             try {
243                 response = request.send();
244             } catch (ExecutionException | TimeoutException e) {
245                 Throwable failure = e instanceof ExecutionException ? e.getCause() : e;
246                 if (retryHandler.shouldRetry(attempt, failure)) {
247                     logImmediateRetry(request, attempt, failure);
248                     continue;
249                 }
250                 if (failure instanceof Exception) {
251                     throw (Exception) failure;
252                 } else {
253                     throw new RuntimeException(failure);
254                 }
255             }
256             if (retryHandler.shouldRetry(attempt, response.getStatus())) {
257                 waitBeforeRetry(request, attempt, response);
258                 continue;
259             }
260             Map<TransferEvent.TransportPropertyKey, Object> transportProperties =
261                     createTransportProperties(request, rawResponseHeaders);
262             task.getListener().transportPropertiesAvailable(transportProperties);
263             if (response.getStatus() >= MULTIPLE_CHOICES) {
264                 throw new HttpTransporterException(response.getStatus());
265             }
266             return;
267         }
268     }
269 
270     @Override
271     protected void implGet(GetTask task) throws Exception {
272         boolean resume = task.getResumeOffset() > 0L && task.getDataPath() != null;
273         Response response;
274         InputStreamResponseListener listener;
275 
276         int attempt = 0;
277         while (true) {
278             Request request = client.newRequest(resolve(task)).method("GET");
279             request.headers(m -> headers.forEach(m::add));
280             if (preemptiveAuth) {
281                 mayApplyPreemptiveAuth(request);
282             }
283             if (sendRfc9457Accept) {
284                 JettyRFC9457Reporter.INSTANCE.prepareRequest(request);
285             }
286             if (resume) {
287                 long resumeOffset = task.getResumeOffset();
288                 long lastModified =
289                         Files.getLastModifiedTime(task.getDataPath()).toMillis();
290                 request.headers(h -> {
291                     h.add(RANGE, "bytes=" + resumeOffset + '-');
292                     h.addDateField(IF_UNMODIFIED_SINCE, lastModified - MODIFICATION_THRESHOLD);
293                     h.remove(HttpHeader.ACCEPT_ENCODING);
294                     h.add(ACCEPT_ENCODING, "identity");
295                 });
296             }
297 
298             // capture raw response headers as described in https://github.com/jetty/jetty.project/discussions/14404
299             Map<String, HttpField> rawResponseHeaders = new HashMap<>();
300             request.onResponseHeader((r, field) -> {
301                 rawResponseHeaders.put(field.getLowerCaseName(), field);
302                 return true; // continue processing
303             });
304             listener = new InputStreamResponseListener();
305             request.send(listener);
306             try {
307                 response = listener.get(requestTimeout, TimeUnit.MILLISECONDS);
308             } catch (ExecutionException | TimeoutException e) {
309                 Throwable t = e instanceof ExecutionException ? e.getCause() : e;
310                 if (retryHandler.shouldRetry(attempt, t)) {
311                     request.abort(t); // no-op if the request already failed
312                     listener.close();
313                     logImmediateRetry(request, attempt, t);
314                     attempt++;
315                     continue;
316                 }
317                 if (t instanceof Exception) {
318                     throw (Exception) t;
319                 } else {
320                     throw new RuntimeException(t);
321                 }
322             }
323             if (retryHandler.shouldRetry(attempt, response.getStatus())) {
324                 listener.close(); // discards the response body
325                 waitBeforeRetry(request, attempt, response);
326                 attempt++;
327                 continue;
328             }
329             if (resume && response.getStatus() == PRECONDITION_FAILED) {
330                 // the local contents are outdated: discard this response and fetch the whole file
331                 listener.close();
332                 resume = false;
333                 continue;
334             }
335             Map<TransferEvent.TransportPropertyKey, Object> transportProperties =
336                     createTransportProperties(request, rawResponseHeaders);
337             task.getListener().transportPropertiesAvailable(transportProperties);
338             if (response.getStatus() >= MULTIPLE_CHOICES) {
339                 JettyRFC9457Reporter.INSTANCE.generateException(listener, (statusCode, reasonPhrase) -> {
340                     throw new HttpTransporterException(statusCode);
341                 });
342             }
343             break;
344         }
345 
346         long offset = 0L, length = response.getHeaders().getLongField(CONTENT_LENGTH);
347         if (resume) {
348             String range = response.getHeaders().get(CONTENT_RANGE);
349             if (range != null) {
350                 Matcher m = CONTENT_RANGE_PATTERN.matcher(range);
351                 if (!m.matches()) {
352                     throw new IOException("Invalid Content-Range header for partial download: " + range);
353                 }
354                 offset = Long.parseLong(m.group(1));
355                 length = Long.parseLong(m.group(2)) + 1L;
356                 if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) {
357                     throw new IOException("Invalid Content-Range header for partial download from offset "
358                             + task.getResumeOffset() + ": " + range);
359                 }
360             }
361         }
362 
363         final boolean downloadResumed = offset > 0L;
364         final Path dataFile = task.getDataPath();
365         if (dataFile == null) {
366             try (InputStream is = listener.getInputStream()) {
367                 utilGet(task, is, true, length, downloadResumed);
368             }
369         } else {
370             try (PathProcessor.CollocatedTempFile tempFile = pathProcessor.newTempFile(dataFile)) {
371                 task.setDataPath(tempFile.getPath(), downloadResumed);
372                 if (downloadResumed && Files.isRegularFile(dataFile)) {
373                     try (InputStream inputStream = Files.newInputStream(dataFile)) {
374                         Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
375                     }
376                 }
377                 try (InputStream is = listener.getInputStream()) {
378                     utilGet(task, is, true, length, downloadResumed);
379                 }
380                 tempFile.move();
381             } finally {
382                 task.setDataPath(dataFile);
383             }
384         }
385         if (task.getDataPath() != null && response.getHeaders().getDateField(LAST_MODIFIED) != -1) {
386             long lastModified =
387                     response.getHeaders().getDateField(LAST_MODIFIED); // note: Wagon also does first not last
388             if (lastModified != -1) {
389                 pathProcessor.setLastModified(
390                         task.getDataPath(), HttpTransporterUtils.clampRemoteLastModified(lastModified));
391             }
392         }
393         Map<String, String> checksums = checksumExtractor.extractChecksums(headerGetter(response));
394         if (checksums != null && !checksums.isEmpty()) {
395             checksums.forEach(task::setChecksum);
396         }
397     }
398 
399     private Map<TransferEvent.TransportPropertyKey, Object> createTransportProperties(
400             Request request, Map<String, HttpField> rawResponseHeaders) {
401         HttpTransportPropertiesBuilder builder =
402                 new HttpTransportPropertiesBuilder(toHttpVersion(request.getVersion()));
403         SslSessionData sslSessionData = request.getConnection().getSslSessionData();
404         if (sslSessionData != null && sslSessionData.sslSession() != null) {
405             builder.withSslProtocol(sslSessionData.sslSession().getProtocol());
406             builder.withSslCipherSuite(sslSessionData.sslSession().getCipherSuite());
407         }
408         if (rawResponseHeaders.containsKey("content-encoding")) {
409             builder.withContentCoding(rawResponseHeaders.get("content-encoding").getValue());
410         }
411         return builder.build();
412     }
413 
414     static HttpTransportProperty.HttpVersion toHttpVersion(org.eclipse.jetty.http.HttpVersion version) {
415         switch (version) {
416             case HTTP_1_0:
417                 return HttpTransportProperty.HttpVersion.HTTP_1_0;
418             case HTTP_1_1:
419                 return HttpTransportProperty.HttpVersion.HTTP_1_1;
420             case HTTP_2:
421                 return HttpTransportProperty.HttpVersion.HTTP_2;
422             case HTTP_3:
423                 return HttpTransportProperty.HttpVersion.HTTP_3;
424             default:
425                 throw new IllegalArgumentException("Unknown version " + version.toString());
426         }
427     }
428 
429     private static Function<String, String> headerGetter(Response response) {
430         return s -> response.getHeaders().get(s);
431     }
432 
433     @Override
434     protected void implPut(PutTask task) throws Exception {
435         int attempt = 0;
436         while (!put(task, attempt)) {
437             attempt++;
438         }
439     }
440 
441     /**
442      * Sends the PUT request once.
443      *
444      * @param attempt the 0-based number of this attempt
445      * @return {@code true} if the upload is complete, {@code false} if it failed in a way that is worth another attempt
446      */
447     private boolean put(PutTask task, int attempt) throws Exception {
448         Request request = client.newRequest(resolve(task)).method("PUT");
449         request.headers(m -> headers.forEach(m::add));
450         if (sendRfc9457Accept) {
451             JettyRFC9457Reporter.INSTANCE.prepareRequest(request);
452         }
453         if (preemptiveAuth || preemptivePutAuth) {
454             mayApplyPreemptiveAuth(request);
455         }
456         request.body(PutTaskRequestContent.from(task));
457         // capture raw response headers as described in https://github.com/jetty/jetty.project/discussions/14404
458         Map<String, HttpField> rawResponseHeaders = new HashMap<>();
459         request.onResponseHeader((r, field) -> {
460             rawResponseHeaders.put(field.getLowerCaseName(), field);
461             return true; // continue processing
462         });
463         AtomicBoolean started = new AtomicBoolean(false);
464         AtomicBoolean progressed = new AtomicBoolean(false);
465         Response response;
466         try (InputStreamResponseListener listener = new InputStreamResponseListener()) {
467             request.onRequestCommit(r -> {
468                         if (task.getDataLength() == 0) {
469                             if (started.compareAndSet(false, true)) {
470                                 try {
471                                     task.getListener().transportStarted(0, task.getDataLength());
472                                 } catch (TransferCancelledException e) {
473                                     r.abort(e);
474                                 }
475                             }
476                         }
477                     })
478                     .onRequestContent((r, b) -> {
479                         if (started.compareAndSet(false, true)) {
480                             try {
481                                 task.getListener().transportStarted(0, task.getDataLength());
482                             } catch (TransferCancelledException e) {
483                                 r.abort(e);
484                                 return;
485                             }
486                         }
487                         progressed.set(true);
488                         try {
489                             task.getListener().transportProgressed(b);
490                         } catch (TransferCancelledException e) {
491                             r.abort(e);
492                         }
493                     })
494                     .send(listener);
495             response = listener.get(requestTimeout, TimeUnit.MILLISECONDS);
496             // On some platforms (macOS) with certain configurations (proxy auth, TLS/HTTP2),
497             // Jetty may complete a small PUT without firing onRequestContent callbacks, leaving
498             // the progress listener uninformed even though the upload was sent.
499             // Fire the missing events regardless of response status so the listener contract
500             // is honoured on both success and error paths. TransferCancelledException from
501             // transportStarted is propagated to the caller (cancelStart must be observable).
502             if (task.getDataLength() > 0 && !progressed.get()) {
503                 if (started.compareAndSet(false, true)) {
504                     // propagate cancellation: even though the bytes are already sent,
505                     // the TransportListener contract requires callers to observe cancelStart
506                     task.getListener().transportStarted(0, task.getDataLength());
507                 }
508                 try (InputStream is = task.newInputStream()) {
509                     byte[] buf = new byte[1024 * 32];
510                     int n;
511                     while ((n = is.read(buf)) != -1) {
512                         try {
513                             task.getListener().transportProgressed(ByteBuffer.wrap(buf, 0, n));
514                         } catch (TransferCancelledException e) {
515                             break; // exit loop; fall through to transportPropertiesAvailable
516                         }
517                     }
518                 }
519             }
520             if (!retryHandler.shouldRetry(attempt, response.getStatus())) {
521                 // transportPropertiesAvailable is called after transportStarted/transportProgressed
522                 // to honour the TransportListener contract: "for remote put tasks this is called
523                 // after transportStarted(long, long)". Placed before the status check so it is
524                 // reachable on both success (2xx) and error (3xx/4xx/5xx) responses.
525                 task.getListener().transportPropertiesAvailable(createTransportProperties(request, rawResponseHeaders));
526                 if (response.getStatus() >= MULTIPLE_CHOICES) {
527                     JettyRFC9457Reporter.INSTANCE.generateException(listener, (statusCode, reasonPhrase) -> {
528                         throw new HttpTransporterException(statusCode);
529                     });
530                 }
531                 return true;
532             }
533         } catch (ExecutionException | TimeoutException e) {
534             Throwable t = e instanceof ExecutionException ? e.getCause() : e;
535             if (retryHandler.shouldRetry(attempt, t)) {
536                 request.abort(t); // no-op if the request already failed
537                 logImmediateRetry(request, attempt, t);
538                 return false;
539             }
540             if (t instanceof IOException ioex) {
541                 if (ioex.getCause() instanceof TransferCancelledException) {
542                     throw (TransferCancelledException) ioex.getCause();
543                 } else {
544                     throw ioex;
545                 }
546             } else if (t instanceof Exception) {
547                 throw (Exception) t;
548             } else {
549                 throw new RuntimeException(t);
550             }
551         }
552         // the listener is closed by now, which discards the response body
553         waitBeforeRetry(request, attempt, response);
554         return false;
555     }
556 
557     @Override
558     protected void implClose() {
559         try {
560             this.client.stop();
561         } catch (Exception e) {
562             throw new RuntimeException(e);
563         }
564     }
565 
566     @SuppressWarnings({"checkstyle:methodlength", "deprecation"})
567     private HttpClient createClient() throws RuntimeException {
568         BasicAuthentication.BasicResult serverAuth = null;
569         BasicAuthentication.BasicResult proxyAuth = null;
570         SSLContext sslContext = null;
571         BasicAuthentication basicAuthentication = null;
572         try (AuthenticationContext repoAuthContext = AuthenticationContext.forRepository(session, repository)) {
573             if (repoAuthContext != null) {
574                 sslContext = repoAuthContext.get(AuthenticationContext.SSL_CONTEXT, SSLContext.class);
575 
576                 String username = repoAuthContext.get(AuthenticationContext.USERNAME);
577                 String password = repoAuthContext.get(AuthenticationContext.PASSWORD);
578 
579                 URI uri = URI.create(repository.getUrl());
580                 basicAuthentication = new BasicAuthentication(uri, Authentication.ANY_REALM, username, password);
581                 if (preemptiveAuth || preemptivePutAuth) {
582                     serverAuth = new BasicAuthentication.BasicResult(uri, HttpHeader.AUTHORIZATION, username, password);
583                 }
584             }
585         }
586 
587         SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
588         if (insecure) {
589             // this is also passed on to Quiche for HTTP/3
590             sslContextFactory.setEndpointIdentificationAlgorithm(null);
591             sslContextFactory.setHostnameVerifier((name, context) -> true);
592             sslContextFactory.setTrustAll(true);
593         } else {
594             try {
595                 if (sslContext == null) {
596                     // use the JVM's default SSL context (potentially with custom keystores/truststores)
597                     // https://github.com/jetty/jetty.project/issues/15378
598                     sslContext = SSLContext.getDefault();
599                 }
600             } catch (NoSuchAlgorithmException e) {
601                 throw new IllegalStateException("SSL Context setup failure", e);
602             }
603         }
604 
605         if (sslContext != null) {
606             // not properly supported by Quiche for HTTP/3, but Jetty will use it for HTTP/2 and HTTP/1.1
607             sslContextFactory.setSslContext(sslContext);
608         }
609 
610         ClientConnector clientConnector = new ClientConnector();
611         clientConnector.setSslContextFactory(sslContextFactory);
612 
613         Collection<ClientConnectionFactory.Info> connectors = new ArrayList<>();
614         if ("https".equalsIgnoreCase(repository.getProtocol())) {
615             HttpVersion httpVersion = HttpTransporterUtils.getHttpVersion(session, repository);
616             switch (httpVersion) {
617                 case MAXIMUM:
618                 case HTTP_3:
619                     QuicheClientQuicConfiguration clientQuicConfig =
620                             HTTP3ClientQuicConfiguration.configure(new QuicheClientQuicConfiguration());
621                     HTTP3Client http3Client = new HTTP3Client(clientQuicConfig, clientConnector);
622                     QuicheTransport transport = new QuicheTransport(clientQuicConfig);
623                     ClientConnectionFactoryOverHTTP3.HTTP3 http3 =
624                             new ClientConnectionFactoryOverHTTP3.HTTP3(http3Client, transport);
625                     connectors.add(http3);
626                     break; // fallback to HTTP/2 not supported yet (https://github.com/jetty/jetty.project/issues/15423)
627                 case HTTP_2:
628                 case DEFAULT:
629                     HTTP2Client http2Client = new HTTP2Client(clientConnector);
630                     ClientConnectionFactoryOverHTTP2.HTTP2 http2 =
631                             new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client);
632                     connectors.add(http2);
633                     break;
634                 default:
635                     break;
636             }
637         }
638         connectors.add(HttpClientConnectionFactory.HTTP11); // HTTP/1.1, always supported but has least priority
639 
640         HttpClientTransportDynamic dynamicTransport = new HttpClientTransportDynamic(
641                 clientConnector, connectors.toArray(new ClientConnectionFactory.Info[0]));
642         HttpClient httpClient = new HttpClient(dynamicTransport);
643         httpClient.setConnectTimeout(connectTimeout);
644         httpClient.setIdleTimeout(requestTimeout);
645         RedirectMode redirectMode = HttpTransporterUtils.getRedirectMode(
646                 session,
647                 repository,
648                 JettyTransporterConfigurationKeys.DEFAULT_FOLLOW_REDIRECTS,
649                 JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_REDIRECTS);
650         httpClient.setFollowRedirects(redirectMode != RedirectMode.NONE);
651         httpClient.setMaxRedirects(ConfigUtils.getInteger(
652                 session,
653                 JettyTransporterConfigurationKeys.DEFAULT_MAX_REDIRECTS,
654                 JettyTransporterConfigurationKeys.CONFIG_PROP_MAX_REDIRECTS));
655 
656         boolean followInsecureRedirects = HttpTransporterUtils.isFollowInsecureRedirect(
657                 session, repository, JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS);
658         boolean originScopedHeaders = HttpTransporterUtils.isOriginScopedHeaders(
659                 session, repository, JettyTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS);
660 
661         httpClient.setUserAgentField(null); // we manage it
662 
663         if (basicAuthentication != null) {
664             httpClient.getAuthenticationStore().addAuthentication(basicAuthentication);
665         }
666 
667         if (repository.getProxy() != null) {
668             HttpProxy proxy = new HttpProxy(
669                     repository.getProxy().getHost(), repository.getProxy().getPort());
670 
671             httpClient.getProxyConfiguration().addProxy(proxy);
672             try (AuthenticationContext proxyAuthContext = AuthenticationContext.forProxy(session, repository)) {
673                 if (proxyAuthContext != null) {
674                     String username = proxyAuthContext.get(AuthenticationContext.USERNAME);
675                     String password = proxyAuthContext.get(AuthenticationContext.PASSWORD);
676 
677                     BasicAuthentication proxyAuthentication =
678                             new BasicAuthentication(proxy.getURI(), Authentication.ANY_REALM, username, password);
679 
680                     httpClient.getAuthenticationStore().addAuthentication(proxyAuthentication);
681                     if (preemptiveAuth || preemptivePutAuth) {
682                         proxyAuth = new BasicAuthentication.BasicResult(
683                                 proxy.getURI(), HttpHeader.PROXY_AUTHORIZATION, username, password);
684                     }
685                 }
686             }
687         }
688         if (serverAuth != null) {
689             this.basicServerAuthenticationResult.set(serverAuth);
690         }
691         if (proxyAuth != null) {
692             this.basicProxyAuthenticationResult.set(proxyAuth);
693         }
694 
695         try {
696             httpClient.start();
697 
698             // Register request listeners after start() so that Jetty's content decoder factories are
699             // fully initialized first.
700             if (!followInsecureRedirects && "https".equalsIgnoreCase(repository.getProtocol())) {
701                 // this client serves exactly one repository: any non-https request it ever issues can only be the
702                 // result of following a protocol-downgrading redirect, so refuse it before anything is sent
703                 httpClient.getRequestListeners().addQueuedListener(new InsecureRedirectGuard());
704             }
705             if (redirectMode == RedirectMode.SAME_AUTHORITY) {
706                 httpClient.getRequestListeners().addQueuedListener(new SameAuthorityRedirectGuard(baseUri));
707             }
708             if (originScopedHeaders) {
709                 // Jetty's redirector copies the request headers onto every redirect hop it follows; scope configured
710                 // headers (and preemptively applied Authorization) to the repository origin so a cross-origin redirect
711                 // does not replay them to the redirect target. The copied redirect request passes through the
712                 // client-level request listeners again, same mechanism as the InsecureRedirectGuard above.
713                 // Challenge-based authentication from the authentication store is URI-scoped by Jetty already.
714                 //
715                 // Only register the listener when there are actual credentials or configured headers to protect:
716                 // without preemptive authentication or user-configured headers, there is nothing on the request
717                 // that could leak to a redirect target, so registering the listener would be a no-op.
718                 Map<String, String> configuredHeaders = HttpTransporterUtils.getHttpHeaders(session, repository);
719                 boolean hasPreemptiveAuth = basicAuthentication != null;
720                 boolean hasConfiguredHeaders = configuredHeaders != null && !configuredHeaders.isEmpty();
721                 if (hasPreemptiveAuth || hasConfiguredHeaders) {
722                     TreeSet<String> scopedHeaderNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
723                     scopedHeaderNames.add(HttpHeader.AUTHORIZATION.asString());
724                     if (hasConfiguredHeaders) {
725                         scopedHeaderNames.addAll(configuredHeaders.keySet());
726                     }
727                     httpClient
728                             .getRequestListeners()
729                             .addHeadersListener(new OriginScopedHeadersListener(baseUri, scopedHeaderNames));
730                 }
731             }
732 
733             return httpClient;
734         } catch (Exception e) {
735             if (e instanceof RuntimeException) {
736                 throw (RuntimeException) e;
737             } else {
738                 throw new IllegalStateException("Jetty client start failure", e);
739             }
740         }
741     }
742 }