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.apache;
20  
21  import javax.net.ssl.SSLSession;
22  
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.InterruptedIOException;
26  import java.io.OutputStream;
27  import java.io.UncheckedIOException;
28  import java.net.URI;
29  import java.net.URISyntaxException;
30  import java.nio.charset.Charset;
31  import java.nio.file.Files;
32  import java.nio.file.Path;
33  import java.nio.file.StandardCopyOption;
34  import java.util.Date;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.Set;
38  import java.util.concurrent.ConcurrentHashMap;
39  import java.util.function.Function;
40  import java.util.function.IntPredicate;
41  import java.util.regex.Matcher;
42  
43  import org.apache.http.Header;
44  import org.apache.http.HttpClientConnection;
45  import org.apache.http.HttpEntity;
46  import org.apache.http.HttpEntityEnclosingRequest;
47  import org.apache.http.HttpException;
48  import org.apache.http.HttpHeaders;
49  import org.apache.http.HttpHost;
50  import org.apache.http.HttpRequest;
51  import org.apache.http.HttpResponse;
52  import org.apache.http.HttpStatus;
53  import org.apache.http.ProtocolVersion;
54  import org.apache.http.auth.AuthScheme;
55  import org.apache.http.auth.AuthSchemeProvider;
56  import org.apache.http.auth.AuthScope;
57  import org.apache.http.client.AuthCache;
58  import org.apache.http.client.CredentialsProvider;
59  import org.apache.http.client.HttpRequestRetryHandler;
60  import org.apache.http.client.HttpResponseException;
61  import org.apache.http.client.ServiceUnavailableRetryStrategy;
62  import org.apache.http.client.config.AuthSchemes;
63  import org.apache.http.client.config.CookieSpecs;
64  import org.apache.http.client.config.RequestConfig;
65  import org.apache.http.client.methods.CloseableHttpResponse;
66  import org.apache.http.client.methods.HttpGet;
67  import org.apache.http.client.methods.HttpHead;
68  import org.apache.http.client.methods.HttpOptions;
69  import org.apache.http.client.methods.HttpPut;
70  import org.apache.http.client.methods.HttpUriRequest;
71  import org.apache.http.client.utils.DateUtils;
72  import org.apache.http.client.utils.URIUtils;
73  import org.apache.http.config.Registry;
74  import org.apache.http.config.RegistryBuilder;
75  import org.apache.http.config.SocketConfig;
76  import org.apache.http.conn.ManagedHttpClientConnection;
77  import org.apache.http.entity.AbstractHttpEntity;
78  import org.apache.http.entity.ByteArrayEntity;
79  import org.apache.http.impl.NoConnectionReuseStrategy;
80  import org.apache.http.impl.auth.BasicScheme;
81  import org.apache.http.impl.auth.BasicSchemeFactory;
82  import org.apache.http.impl.auth.DigestSchemeFactory;
83  import org.apache.http.impl.auth.KerberosSchemeFactory;
84  import org.apache.http.impl.auth.NTLMSchemeFactory;
85  import org.apache.http.impl.auth.SPNegoSchemeFactory;
86  import org.apache.http.impl.client.CloseableHttpClient;
87  import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
88  import org.apache.http.impl.client.HttpClientBuilder;
89  import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
90  import org.apache.http.protocol.HttpContext;
91  import org.apache.http.protocol.HttpCoreContext;
92  import org.apache.http.protocol.HttpRequestExecutor;
93  import org.apache.http.util.EntityUtils;
94  import org.eclipse.aether.ConfigurationProperties.RedirectMode;
95  import org.eclipse.aether.Keys;
96  import org.eclipse.aether.RepositorySystemSession;
97  import org.eclipse.aether.repository.AuthenticationContext;
98  import org.eclipse.aether.repository.Proxy;
99  import org.eclipse.aether.repository.RemoteRepository;
100 import org.eclipse.aether.spi.connector.transport.AbstractTransporter;
101 import org.eclipse.aether.spi.connector.transport.GetTask;
102 import org.eclipse.aether.spi.connector.transport.PeekTask;
103 import org.eclipse.aether.spi.connector.transport.PutTask;
104 import org.eclipse.aether.spi.connector.transport.TransportListener;
105 import org.eclipse.aether.spi.connector.transport.TransportTask;
106 import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor;
107 import org.eclipse.aether.spi.connector.transport.http.HttpTransportPropertiesBuilder;
108 import org.eclipse.aether.spi.connector.transport.http.HttpTransporter;
109 import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException;
110 import org.eclipse.aether.spi.io.PathProcessor;
111 import org.eclipse.aether.transfer.HttpTransportProperty.HttpVersion;
112 import org.eclipse.aether.transfer.NoTransporterException;
113 import org.eclipse.aether.transfer.TransferCancelledException;
114 import org.eclipse.aether.transfer.TransferEvent;
115 import org.eclipse.aether.util.ConfigUtils;
116 import org.eclipse.aether.util.StringDigestUtil;
117 import org.eclipse.aether.util.connector.transport.http.HttpTransporterUtils;
118 import org.slf4j.Logger;
119 import org.slf4j.LoggerFactory;
120 
121 import static java.util.Objects.requireNonNull;
122 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE_PATTERN;
123 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_REDIRECTS;
124 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_HTTP_RETRY_HANDLER_NAME;
125 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED;
126 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_MAX_REDIRECTS;
127 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_USE_SYSTEM_PROPERTIES;
128 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_FOLLOW_REDIRECTS;
129 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED;
130 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_MAX_REDIRECTS;
131 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_USE_SYSTEM_PROPERTIES;
132 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.HTTP_RETRY_HANDLER_NAME_DEFAULT;
133 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.HTTP_RETRY_HANDLER_NAME_STANDARD;
134 
135 /**
136  * A transporter for HTTP/HTTPS.
137  */
138 final class ApacheTransporter extends AbstractTransporter implements HttpTransporter {
139     /**
140      * Custom context attribute name to store the SSL session in the HTTP context. This is populated by a custom request executor.
141      */
142     private static final String CONTEXT_ATTRIBUTE_NAME_SSL_SESSION = "ssl.session";
143 
144     private static final Logger LOGGER = LoggerFactory.getLogger(ApacheTransporter.class);
145 
146     private final ChecksumExtractor checksumExtractor;
147 
148     private final PathProcessor pathProcessor;
149 
150     private final AuthenticationContext repoAuthContext;
151 
152     private final AuthenticationContext proxyAuthContext;
153 
154     private final URI baseUri;
155 
156     private final HttpHost server;
157 
158     private final HttpHost proxy;
159 
160     private final CloseableHttpClient client;
161 
162     private final Map<?, ?> headers;
163 
164     private final LocalState state;
165 
166     private final boolean preemptiveAuth;
167 
168     private final boolean preemptivePutAuth;
169 
170     private final boolean supportWebDav;
171 
172     private final boolean sendRfc9457Accept;
173 
174     private final AuthCache authCache;
175 
176     @SuppressWarnings({"checkstyle:methodlength", "deprecation"})
177     ApacheTransporter(
178             RemoteRepository repository,
179             RepositorySystemSession session,
180             ChecksumExtractor checksumExtractor,
181             PathProcessor pathProcessor)
182             throws NoTransporterException {
183         this.checksumExtractor = checksumExtractor;
184         this.pathProcessor = pathProcessor;
185         try {
186             this.baseUri = HttpTransporterUtils.getBaseUri(repository);
187             this.server = URIUtils.extractHost(baseUri);
188             if (server == null) {
189                 throw new URISyntaxException(repository.getUrl(), "URL lacks host name");
190             }
191         } catch (URISyntaxException e) {
192             throw new NoTransporterException(repository, e.getMessage(), e);
193         }
194         this.proxy = toHost(repository.getProxy());
195 
196         this.repoAuthContext = AuthenticationContext.forRepository(session, repository);
197         this.proxyAuthContext = AuthenticationContext.forProxy(session, repository);
198 
199         String httpsSecurityMode = HttpTransporterUtils.getHttpsSecurityMode(session, repository);
200         final int connectionMaxTtlSeconds = HttpTransporterUtils.getHttpConnectionMaxTtlSeconds(session, repository);
201         final int maxConnectionsPerRoute = HttpTransporterUtils.getHttpMaxConnectionsPerRoute(session, repository);
202         this.state = new LocalState(
203                 session,
204                 repository,
205                 new ConnMgrConfig(
206                         session, repoAuthContext, httpsSecurityMode, connectionMaxTtlSeconds, maxConnectionsPerRoute));
207 
208         this.headers = HttpTransporterUtils.getHttpHeaders(session, repository);
209         this.preemptiveAuth = HttpTransporterUtils.isHttpPreemptiveAuth(session, repository);
210         this.preemptivePutAuth = HttpTransporterUtils.isHttpPreemptivePutAuth(session, repository);
211         this.supportWebDav = HttpTransporterUtils.isHttpSupportWebDav(session, repository);
212         this.sendRfc9457Accept = HttpTransporterUtils.isHttpSendRfc9457Accept(session, repository);
213         int connectTimeout = HttpTransporterUtils.getHttpConnectTimeout(session, repository);
214         int requestTimeout = HttpTransporterUtils.getHttpRequestTimeout(session, repository);
215         int retryCount = HttpTransporterUtils.getHttpRetryHandlerCount(session, repository);
216         long retryInterval = HttpTransporterUtils.getHttpRetryHandlerInterval(session, repository);
217         long retryIntervalMax = HttpTransporterUtils.getHttpRetryHandlerIntervalMax(session, repository);
218         String retryHandlerName = ConfigUtils.getString(
219                 session,
220                 HTTP_RETRY_HANDLER_NAME_STANDARD,
221                 CONFIG_PROP_HTTP_RETRY_HANDLER_NAME + "." + repository.getId(),
222                 CONFIG_PROP_HTTP_RETRY_HANDLER_NAME);
223         boolean retryHandlerRequestSentEnabled = ConfigUtils.getBoolean(
224                 session,
225                 DEFAULT_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED,
226                 CONFIG_PROP_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED + "." + repository.getId(),
227                 CONFIG_PROP_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED);
228         int maxRedirects = ConfigUtils.getInteger(
229                 session,
230                 DEFAULT_MAX_REDIRECTS,
231                 CONFIG_PROP_MAX_REDIRECTS + "." + repository.getId(),
232                 CONFIG_PROP_MAX_REDIRECTS);
233         RedirectMode redirectMode = HttpTransporterUtils.getRedirectMode(
234                 session, repository, DEFAULT_FOLLOW_REDIRECTS, CONFIG_PROP_FOLLOW_REDIRECTS);
235         boolean followInsecureRedirects = HttpTransporterUtils.isFollowInsecureRedirect(
236                 session, repository, ApacheTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_INSECURE_REDIRECTS);
237         String userAgent = HttpTransporterUtils.getUserAgent(session, repository);
238 
239         Charset credentialsCharset = HttpTransporterUtils.getHttpCredentialsEncoding(session, repository);
240         Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
241                 .register(AuthSchemes.BASIC, new BasicSchemeFactory(credentialsCharset))
242                 .register(AuthSchemes.DIGEST, new DigestSchemeFactory(credentialsCharset))
243                 .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
244                 .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
245                 .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())
246                 .build();
247         SocketConfig socketConfig =
248                 // the time to establish connection (low level)
249                 SocketConfig.custom().setSoTimeout(requestTimeout).build();
250         RequestConfig requestConfig = RequestConfig.custom()
251                 .setMaxRedirects(maxRedirects)
252                 .setRedirectsEnabled(redirectMode != RedirectMode.NONE)
253                 .setRelativeRedirectsAllowed(redirectMode != RedirectMode.NONE)
254                 // the time waiting for data; max time between two data packets
255                 .setSocketTimeout(requestTimeout)
256                 // the time to establish the connection (high level)
257                 .setConnectTimeout(connectTimeout)
258                 // the time to wait for a connection from the connection manager/pool
259                 .setConnectionRequestTimeout(connectTimeout)
260                 .setLocalAddress(HttpTransporterUtils.getHttpLocalAddress(session, repository)
261                         .orElse(null))
262                 .setCookieSpec(CookieSpecs.STANDARD)
263                 .build();
264 
265         HttpRequestRetryHandler retryHandler;
266         if (HTTP_RETRY_HANDLER_NAME_STANDARD.equals(retryHandlerName)) {
267             retryHandler = new StandardHttpRequestRetryHandler(retryCount, retryHandlerRequestSentEnabled);
268         } else if (HTTP_RETRY_HANDLER_NAME_DEFAULT.equals(retryHandlerName)) {
269             retryHandler = new DefaultHttpRequestRetryHandler(retryCount, retryHandlerRequestSentEnabled);
270         } else {
271             throw new IllegalArgumentException(
272                     "Unsupported parameter " + CONFIG_PROP_HTTP_RETRY_HANDLER_NAME + " value: " + retryHandlerName);
273         }
274         ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new ResolverServiceUnavailableRetryStrategy(
275                 retryCount,
276                 retryInterval,
277                 retryIntervalMax,
278                 HttpTransporterUtils.getHttpServiceUnavailableCodes(session, repository));
279 
280         HttpClientBuilder builder = HttpClientBuilder.create()
281                 .setUserAgent(userAgent)
282                 .setRedirectStrategy(new ResolverRedirectStrategy(redirectMode, baseUri, followInsecureRedirects))
283                 .setDefaultSocketConfig(socketConfig)
284                 .setDefaultRequestConfig(requestConfig)
285                 .setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
286                 .setRetryHandler((exception, executionCount, context) -> {
287                     if (retryHandler.retryRequest(exception, executionCount, context)) {
288                         logImmediateRetry(context, executionCount, retryCount, exception);
289                         return true;
290                     }
291                     return false;
292                 })
293                 .setDefaultAuthSchemeRegistry(authSchemeRegistry)
294                 .setConnectionManager(state.getConnectionManager())
295                 .setConnectionManagerShared(true)
296                 .setDefaultCredentialsProvider(toCredentialsProvider(server, repoAuthContext, proxy, proxyAuthContext))
297                 .setProxy(proxy);
298         if (HttpTransporterUtils.isOriginScopedHeaders(
299                 session, repository, ApacheTransporterConfigurationKeys.CONFIG_PROP_ORIGIN_SCOPED_HEADERS)) {
300             // Configured headers are per-repository data and frequently carry credentials; scope them to the
301             // repository origin so a cross-origin redirect hop does not replay them to the redirect target.
302             // Challenge-based credentials are host-scoped by the credentials provider already.
303             builder.addInterceptorLast(new OriginScopedHeadersInterceptor(server, this.headers.keySet()));
304         }
305         final boolean useSystemProperties = ConfigUtils.getBoolean(
306                 session,
307                 DEFAULT_USE_SYSTEM_PROPERTIES,
308                 CONFIG_PROP_USE_SYSTEM_PROPERTIES + "." + repository.getId(),
309                 CONFIG_PROP_USE_SYSTEM_PROPERTIES);
310         if (useSystemProperties) {
311             LOGGER.warn(
312                     "Transport used Apache HttpClient is instructed to use system properties: this may yield in unwanted side-effects!");
313             LOGGER.warn("Please use documented means to configure resolver transport.");
314             builder.useSystemProperties();
315             SystemProxyAuthenticationStrategy systemProxyAuth = new SystemProxyAuthenticationStrategy();
316             builder.setProxyAuthenticationStrategy(systemProxyAuth);
317             builder.addInterceptorFirst(systemProxyAuth);
318         }
319 
320         // capture SSL session for logging purposes (https://issues.apache.org/jira/browse/HTTPCLIENT-2164)
321         builder.setRequestExecutor(new HttpRequestExecutor() {
322 
323             @Override
324             public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context)
325                     throws IOException, HttpException {
326                 if (conn instanceof ManagedHttpClientConnection) {
327                     context.setAttribute(
328                             CONTEXT_ATTRIBUTE_NAME_SSL_SESSION, ((ManagedHttpClientConnection) conn).getSSLSession());
329                 }
330                 return super.execute(request, conn, context);
331             }
332         });
333 
334         HttpTransporterUtils.getHttpExpectContinue(session, repository).ifPresent(state::setExpectContinue);
335         if (!HttpTransporterUtils.isHttpReuseConnections(session, repository)) {
336             builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
337         }
338 
339         if (session.getCache() != null) {
340             this.authCache = (AuthCache) session.getCache()
341                     .computeIfAbsent(
342                             session,
343                             Keys.of(
344                                     getClass(),
345                                     repository.getId() + "-" + StringDigestUtil.sha1(repository.toString())),
346                             ConcurrentAuthCache::new);
347         } else {
348             this.authCache = new ConcurrentAuthCache();
349         }
350         this.client = builder.build();
351     }
352 
353     private static HttpHost toHost(Proxy proxy) {
354         HttpHost host = null;
355         if (proxy != null) {
356             // in Maven, the proxy.protocol is used for proxy matching against remote repository protocol; no TLS proxy
357             // support
358             // https://github.com/apache/maven/issues/2519
359             // https://github.com/apache/maven-resolver/issues/745
360             host = new HttpHost(proxy.getHost(), proxy.getPort());
361         }
362         return host;
363     }
364 
365     private static CredentialsProvider toCredentialsProvider(
366             HttpHost server, AuthenticationContext serverAuthCtx, HttpHost proxy, AuthenticationContext proxyAuthCtx) {
367         CredentialsProvider provider =
368                 toCredentialsProvider(server.getHostName(), effectivePort(server), serverAuthCtx);
369         if (proxy != null) {
370             CredentialsProvider p = toCredentialsProvider(proxy.getHostName(), proxy.getPort(), proxyAuthCtx);
371             provider = new DemuxCredentialsProvider(provider, p, proxy);
372         }
373         return provider;
374     }
375 
376     /**
377      * Determines the effective port of the given host: the explicit port if present, otherwise the default port
378      * implied by the scheme. Used to bind repository credentials to the repository's own origin (host and port)
379      * instead of {@link AuthScope#ANY_PORT}: with any-port scoping, a request landing on the same host but a
380      * different port - for example after an https-to-http downgrade redirect - would still be eligible to
381      * receive the credentials.
382      */
383     static int effectivePort(HttpHost host) {
384         if (host.getPort() >= 0) {
385             return host.getPort();
386         }
387         return "https".equalsIgnoreCase(host.getSchemeName()) ? 443 : 80;
388     }
389 
390     private static CredentialsProvider toCredentialsProvider(String host, int port, AuthenticationContext ctx) {
391         DeferredCredentialsProvider provider = new DeferredCredentialsProvider();
392         if (ctx != null) {
393             AuthScope basicScope = new AuthScope(host, port);
394             provider.setCredentials(basicScope, new DeferredCredentialsProvider.BasicFactory(ctx));
395 
396             AuthScope ntlmScope = new AuthScope(host, port, AuthScope.ANY_REALM, "ntlm");
397             provider.setCredentials(ntlmScope, new DeferredCredentialsProvider.NtlmFactory(ctx));
398         }
399         return provider;
400     }
401 
402     LocalState getState() {
403         return state;
404     }
405 
406     private URI resolve(TransportTask task) {
407         return UriUtils.resolve(baseUri, task.getLocation());
408     }
409 
410     @Override
411     protected void implPeek(PeekTask task) throws Exception {
412         HttpHead request = commonHeaders(new HttpHead(resolve(task)));
413         try {
414             execute(request, null, task.getListener());
415         } catch (HttpResponseException e) {
416             throw new HttpTransporterException(e.getStatusCode());
417         }
418     }
419 
420     @Override
421     protected void implGet(GetTask task) throws Exception {
422         boolean resume = true;
423 
424         EntityGetter getter = new EntityGetter(task);
425         HttpGet request = commonHeaders(new HttpGet(resolve(task)));
426         if (sendRfc9457Accept) {
427             ApacheRFC9457Reporter.INSTANCE.prepareRequest(request);
428         }
429         while (true) {
430             final boolean resumeRequested = resume;
431             try {
432                 if (resumeRequested) {
433                     resume(request, task);
434                 }
435                 // a 412 to a resume request is retried below as a plain GET, so that response is not reported
436                 execute(
437                         request,
438                         getter,
439                         task.getListener(),
440                         status -> resumeRequested && status == HttpStatus.SC_PRECONDITION_FAILED);
441                 break;
442             } catch (HttpResponseException e) {
443                 if (resume
444                         && e.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED
445                         && request.containsHeader(HttpHeaders.RANGE)) {
446                     request = commonHeaders(new HttpGet(resolve(task)));
447                     resume = false;
448                     continue;
449                 }
450                 throw new HttpTransporterException(e.getStatusCode());
451             }
452         }
453     }
454 
455     @Override
456     protected void implPut(PutTask task) throws Exception {
457         PutTaskEntity entity = new PutTaskEntity(task);
458         HttpPut request = commonHeaders(entity(new HttpPut(resolve(task)), entity));
459         if (sendRfc9457Accept) {
460             ApacheRFC9457Reporter.INSTANCE.prepareRequest(request);
461         }
462         try {
463             execute(request, null, task.getListener());
464         } catch (HttpResponseException e) {
465             if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED && request.containsHeader(HttpHeaders.EXPECT)) {
466                 state.setExpectContinue(false);
467                 request = commonHeaders(entity(new HttpPut(request.getURI()), entity));
468                 execute(request, null, task.getListener());
469                 return;
470             }
471             throw new HttpTransporterException(e.getStatusCode());
472         }
473     }
474 
475     private void execute(HttpUriRequest request, EntityGetter getter, TransportListener listener) throws Exception {
476         execute(request, getter, listener, status -> false);
477     }
478 
479     /**
480      * @param discardedStatus the response statuses the caller retries with another request; such a response does
481      *                        not serve the transfer, so its transport properties are not reported
482      */
483     private void execute(
484             HttpUriRequest request, EntityGetter getter, TransportListener listener, IntPredicate discardedStatus)
485             throws Exception {
486         try {
487             SharingHttpContext context = new SharingHttpContext(state);
488             context.setAuthCache(authCache);
489             prepare(request, context);
490             try (CloseableHttpResponse response = client.execute(server, request, context)) {
491                 try {
492                     if (!discardedStatus.test(response.getStatusLine().getStatusCode())) {
493                         Map<TransferEvent.TransportPropertyKey, Object> transportProperties =
494                                 createTransportProperties(response, context);
495                         listener.transportPropertiesAvailable(transportProperties);
496                     }
497                     handleStatus(response);
498                     if (getter != null) {
499                         getter.handle(response);
500                     }
501                 } finally {
502                     EntityUtils.consumeQuietly(response.getEntity());
503                 }
504             }
505         } catch (IOException e) {
506             if (e.getCause() instanceof TransferCancelledException) {
507                 throw (Exception) e.getCause();
508             }
509             throw e;
510         }
511     }
512 
513     private void prepare(HttpUriRequest request, SharingHttpContext context) throws Exception {
514         final boolean put = HttpPut.METHOD_NAME.equalsIgnoreCase(request.getMethod());
515         if (preemptiveAuth || (preemptivePutAuth && put)) {
516             context.getAuthCache().put(server, new BasicScheme());
517         }
518         if (supportWebDav) {
519             if (state.getWebDav() == null && (put || isPayloadPresent(request))) {
520                 HttpOptions req = commonHeaders(new HttpOptions(request.getURI()));
521                 try (CloseableHttpResponse response = client.execute(server, req, context)) {
522                     state.setWebDav(response.containsHeader(HttpHeaders.DAV));
523                     EntityUtils.consumeQuietly(response.getEntity());
524                 } catch (IOException e) {
525                     LOGGER.debug("Failed to prepare HTTP context", e);
526                 }
527             }
528             if (put && Boolean.TRUE.equals(state.getWebDav())) {
529                 mkdirs(request.getURI(), context);
530             }
531         }
532     }
533 
534     private void mkdirs(URI uri, SharingHttpContext context) throws Exception {
535         List<URI> dirs = UriUtils.getDirectories(baseUri, uri);
536         int index = 0;
537         for (; index < dirs.size(); index++) {
538             try (CloseableHttpResponse response =
539                     client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))), context)) {
540                 try {
541                     int status = response.getStatusLine().getStatusCode();
542                     if (status < 300 || status == HttpStatus.SC_METHOD_NOT_ALLOWED) {
543                         break;
544                     } else if (status == HttpStatus.SC_CONFLICT) {
545                         continue;
546                     }
547                     handleStatus(response);
548                 } finally {
549                     EntityUtils.consumeQuietly(response.getEntity());
550                 }
551             } catch (IOException e) {
552                 LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e);
553                 return;
554             }
555         }
556         for (index--; index >= 0; index--) {
557             try (CloseableHttpResponse response =
558                     client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))), context)) {
559                 try {
560                     handleStatus(response);
561                 } finally {
562                     EntityUtils.consumeQuietly(response.getEntity());
563                 }
564             } catch (IOException e) {
565                 LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e);
566                 return;
567             }
568         }
569     }
570 
571     private <T extends HttpEntityEnclosingRequest> T entity(T request, HttpEntity entity) {
572         request.setEntity(entity);
573         return request;
574     }
575 
576     private boolean isPayloadPresent(HttpUriRequest request) {
577         if (request instanceof HttpEntityEnclosingRequest) {
578             HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
579             return entity != null && entity.getContentLength() != 0;
580         }
581         return false;
582     }
583 
584     private <T extends HttpUriRequest> T commonHeaders(T request) {
585         request.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store");
586         request.setHeader(HttpHeaders.PRAGMA, "no-cache");
587 
588         if (state.isExpectContinue() && isPayloadPresent(request)) {
589             request.setHeader(HttpHeaders.EXPECT, "100-continue");
590         }
591 
592         for (Map.Entry<?, ?> entry : headers.entrySet()) {
593             if (!(entry.getKey() instanceof String)) {
594                 continue;
595             }
596             if (entry.getValue() instanceof String) {
597                 request.setHeader(entry.getKey().toString(), entry.getValue().toString());
598             } else {
599                 request.removeHeaders(entry.getKey().toString());
600             }
601         }
602 
603         if (!state.isExpectContinue()) {
604             request.removeHeaders(HttpHeaders.EXPECT);
605         }
606         return request;
607     }
608 
609     private <T extends HttpUriRequest> void resume(T request, GetTask task) throws IOException {
610         long resumeOffset = task.getResumeOffset();
611         if (resumeOffset > 0L && task.getDataPath() != null) {
612             long lastModified = Files.getLastModifiedTime(task.getDataPath()).toMillis();
613             request.setHeader(HttpHeaders.RANGE, "bytes=" + resumeOffset + '-');
614             request.setHeader(
615                     HttpHeaders.IF_UNMODIFIED_SINCE, DateUtils.formatDate(new Date(lastModified - 60L * 1000L)));
616             request.setHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
617         }
618     }
619 
620     private void handleStatus(CloseableHttpResponse response) throws Exception {
621         int status = response.getStatusLine().getStatusCode();
622         if (status >= 300) {
623             ApacheRFC9457Reporter.INSTANCE.generateException(response, (statusCode, reasonPhrase) -> {
624                 throw new HttpResponseException(statusCode, reasonPhrase + " (" + statusCode + ")");
625             });
626         }
627     }
628 
629     @Override
630     protected void implClose() {
631         try {
632             client.close();
633         } catch (IOException e) {
634             throw new UncheckedIOException(e);
635         }
636         AuthenticationContext.close(repoAuthContext);
637         AuthenticationContext.close(proxyAuthContext);
638         state.close();
639     }
640 
641     private class EntityGetter {
642 
643         private final GetTask task;
644 
645         EntityGetter(GetTask task) {
646             this.task = task;
647         }
648 
649         public void handle(CloseableHttpResponse response) throws IOException, TransferCancelledException {
650             HttpEntity entity = response.getEntity();
651             if (entity == null) {
652                 entity = new ByteArrayEntity(new byte[0]);
653             }
654 
655             long offset = 0L, length = entity.getContentLength();
656             Header rangeHeader = response.getFirstHeader(HttpHeaders.CONTENT_RANGE);
657             String range = rangeHeader != null ? rangeHeader.getValue() : null;
658             if (range != null) {
659                 Matcher m = CONTENT_RANGE_PATTERN.matcher(range);
660                 if (!m.matches()) {
661                     throw new IOException("Invalid Content-Range header for partial download: " + range);
662                 }
663                 offset = Long.parseLong(m.group(1));
664                 length = Long.parseLong(m.group(2)) + 1L;
665                 if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) {
666                     throw new IOException("Invalid Content-Range header for partial download from offset "
667                             + task.getResumeOffset() + ": " + range);
668                 }
669             }
670 
671             final boolean resume = offset > 0L;
672             final Path dataFile = task.getDataPath();
673             if (dataFile == null) {
674                 try (InputStream is = entity.getContent()) {
675                     utilGet(task, is, true, length, resume);
676                     extractChecksums(response);
677                 }
678             } else {
679                 try (PathProcessor.CollocatedTempFile tempFile = pathProcessor.newTempFile(dataFile)) {
680                     task.setDataPath(tempFile.getPath(), resume);
681                     if (resume && Files.isRegularFile(dataFile)) {
682                         try (InputStream inputStream = Files.newInputStream(dataFile)) {
683                             Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
684                         }
685                     }
686                     try (InputStream is = entity.getContent()) {
687                         utilGet(task, is, true, length, resume);
688                     }
689                     tempFile.move();
690                 } finally {
691                     task.setDataPath(dataFile);
692                 }
693             }
694             if (task.getDataPath() != null) {
695                 Header lastModifiedHeader =
696                         response.getFirstHeader(HttpHeaders.LAST_MODIFIED); // note: Wagon also does first not last
697                 if (lastModifiedHeader != null) {
698                     Date lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
699                     if (lastModified != null) {
700                         pathProcessor.setLastModified(
701                                 task.getDataPath(),
702                                 HttpTransporterUtils.clampRemoteLastModified(lastModified.getTime()));
703                     }
704                 }
705             }
706             extractChecksums(response);
707         }
708 
709         private void extractChecksums(CloseableHttpResponse response) {
710             Map<String, String> checksums = checksumExtractor.extractChecksums(headerGetter(response));
711             if (checksums != null && !checksums.isEmpty()) {
712                 checksums.forEach(task::setChecksum);
713             }
714         }
715     }
716 
717     private static Map<TransferEvent.TransportPropertyKey, Object> createTransportProperties(
718             CloseableHttpResponse response, HttpCoreContext context) {
719         HttpTransportPropertiesBuilder builder =
720                 new HttpTransportPropertiesBuilder(toHttpVersion(response.getProtocolVersion()));
721         SSLSession sslSession = context.getAttribute(CONTEXT_ATTRIBUTE_NAME_SSL_SESSION, SSLSession.class);
722         if (sslSession != null) {
723             builder.withSslProtocol(sslSession.getProtocol());
724             builder.withSslCipherSuite(sslSession.getCipherSuite());
725         }
726         // content encoding is not available (see https://issues.apache.org/jira/browse/HTTPCORE-792)
727         return builder.build();
728     }
729 
730     static HttpVersion toHttpVersion(ProtocolVersion version) {
731         switch (version.getMajor()) {
732             case 1:
733                 if (version.getMinor() == 0) {
734                     return HttpVersion.HTTP_1_0;
735                 } else {
736                     return HttpVersion.HTTP_1_1;
737                 }
738             case 2:
739                 return HttpVersion.HTTP_2;
740             case 3:
741                 return HttpVersion.HTTP_3;
742             default:
743                 throw new IllegalArgumentException("Unknown version " + version.toString());
744         }
745     }
746 
747     private static Function<String, String> headerGetter(CloseableHttpResponse closeableHttpResponse) {
748         return s -> {
749             Header header = closeableHttpResponse.getFirstHeader(s);
750             return header != null ? header.getValue() : null;
751         };
752     }
753 
754     private class PutTaskEntity extends AbstractHttpEntity {
755 
756         private final PutTask task;
757 
758         PutTaskEntity(PutTask task) {
759             this.task = task;
760         }
761 
762         @Override
763         public boolean isRepeatable() {
764             return true;
765         }
766 
767         @Override
768         public boolean isStreaming() {
769             return false;
770         }
771 
772         @Override
773         public long getContentLength() {
774             return task.getDataLength();
775         }
776 
777         @Override
778         public InputStream getContent() throws IOException {
779             return task.newInputStream();
780         }
781 
782         @Override
783         public void writeTo(OutputStream os) throws IOException {
784             try {
785                 utilPut(task, os, false);
786             } catch (TransferCancelledException e) {
787                 throw (IOException) new InterruptedIOException().initCause(e);
788             }
789         }
790     }
791 
792     private static void logImmediateRetry(
793             HttpContext context, int executionCount, int retryCount, Throwable exception) {
794         HttpCoreContext coreContext = HttpCoreContext.adapt(context);
795         HttpRequest request = coreContext.getRequest();
796         String method = request.getRequestLine().getMethod();
797         URI uri = URIUtils.resolve(
798                 URI.create(coreContext.getTargetHost().toURI()),
799                 request.getRequestLine().getUri());
800         HttpTransporter.logImmediateRetry(LOGGER, method, uri, executionCount - 1, retryCount + 1, exception);
801     }
802 
803     private static void logRetry(
804             HttpContext context,
805             int executionCount,
806             int retryCount,
807             String reason,
808             long retryInterval,
809             String intervalReason) {
810         HttpCoreContext coreContext = HttpCoreContext.adapt(context);
811         HttpRequest request = coreContext.getRequest();
812         String method = request.getRequestLine().getMethod();
813         URI uri = URIUtils.resolve(
814                 URI.create(coreContext.getTargetHost().toURI()),
815                 request.getRequestLine().getUri());
816         HttpTransporter.logRetry(
817                 LOGGER, method, uri, executionCount - 1, retryCount + 1, reason, retryInterval, intervalReason);
818     }
819 
820     private static class ResolverServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy {
821         private final int retryCount;
822 
823         private final long retryInterval;
824 
825         private final long retryIntervalMax;
826 
827         private final Set<Integer> serviceUnavailableHttpCodes;
828 
829         /**
830          * Ugly, but forced by HttpClient API {@link ServiceUnavailableRetryStrategy}: the calls for
831          * {@link #retryRequest(HttpResponse, int, HttpContext)} and {@link #getRetryInterval()} are done by same
832          * thread and are actually done from spot that are very close to each other (almost subsequent calls).
833          */
834         private static final ThreadLocal<Long> RETRY_INTERVAL_HOLDER = new ThreadLocal<>();
835 
836         private ResolverServiceUnavailableRetryStrategy(
837                 int retryCount, long retryInterval, long retryIntervalMax, Set<Integer> serviceUnavailableHttpCodes) {
838             if (retryCount < 0) {
839                 throw new IllegalArgumentException("retryCount must be >= 0");
840             }
841             if (retryInterval < 0L) {
842                 throw new IllegalArgumentException("retryInterval must be >= 0");
843             }
844             if (retryIntervalMax < 0L) {
845                 throw new IllegalArgumentException("retryIntervalMax must be >= 0");
846             }
847             this.retryCount = retryCount;
848             this.retryInterval = retryInterval;
849             this.retryIntervalMax = retryIntervalMax;
850             this.serviceUnavailableHttpCodes = requireNonNull(serviceUnavailableHttpCodes);
851         }
852 
853         @Override
854         public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
855             final boolean retry = executionCount <= retryCount
856                     && (serviceUnavailableHttpCodes.contains(
857                             response.getStatusLine().getStatusCode()));
858             if (retry) {
859                 RETRY_INTERVAL_HOLDER.set(retryInterval(response, executionCount, context));
860                 return true;
861             }
862             RETRY_INTERVAL_HOLDER.remove();
863             return false;
864         }
865 
866         /**
867          * Calculates retry interval in milliseconds. If {@link HttpHeaders#RETRY_AFTER} header present, it obeys it.
868          * Otherwise, it returns {@link this#retryInterval} long value multiplied with {@code executionCount} (starts
869          * from 1 and goes 2, 3,...).
870          *
871          * @return long representing the retry interval as milliseconds, capped at {@link #retryIntervalMax}.
872          */
873         private long retryInterval(HttpResponse httpResponse, int executionCount, HttpContext httpContext) {
874             Long result = null;
875             String intervalReason = "";
876             Header header = httpResponse.getFirstHeader(HttpHeaders.RETRY_AFTER);
877             if (header != null && header.getValue() != null) {
878                 String headerValue = header.getValue();
879                 if (headerValue.contains(":")) { // is date when to retry
880                     Date when = DateUtils.parseDate(headerValue); // presumably future
881                     if (when != null) {
882                         result = Math.max(when.getTime() - System.currentTimeMillis(), 0L);
883                         intervalReason = "Retry-After header with date value " + headerValue;
884                     } else {
885                         LOGGER.warn(
886                                 "Invalid Retry-After header value {} for request to {}",
887                                 headerValue,
888                                 httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST));
889                     }
890                 } else {
891                     try {
892                         result = Long.parseLong(headerValue) * 1000L; // is in seconds
893                         intervalReason = "Retry-After header with seconds value " + headerValue;
894                     } catch (NumberFormatException e) {
895                         // fall through
896                         LOGGER.warn(
897                                 "Invalid Retry-After header value {} for request to {}",
898                                 headerValue,
899                                 httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST));
900                     }
901                 }
902             }
903             if (result == null) {
904                 result = executionCount * this.retryInterval;
905                 intervalReason =
906                         "retryInterval " + this.retryInterval + " ms multiplied by execution count " + executionCount;
907             }
908             if (result > retryIntervalMax) {
909                 intervalReason += ", capped at max value";
910                 result = retryIntervalMax;
911             }
912             logRetry(
913                     httpContext,
914                     executionCount,
915                     retryCount,
916                     "status " + httpResponse.getStatusLine().getStatusCode(),
917                     result,
918                     intervalReason);
919             return result;
920         }
921 
922         @Override
923         public long getRetryInterval() {
924             Long ri = RETRY_INTERVAL_HOLDER.get();
925             if (ri == null) {
926                 return 0L;
927             }
928             RETRY_INTERVAL_HOLDER.remove();
929             return ri;
930         }
931     }
932 
933     static class ConcurrentAuthCache implements AuthCache {
934         private final ConcurrentHashMap<HttpHost, AuthScheme> map = new ConcurrentHashMap<>();
935 
936         private static HttpHost normalize(HttpHost host) {
937             if (host.getPort() >= 0) {
938                 return host;
939             }
940             return new HttpHost(host.getHostName(), effectivePort(host), host.getSchemeName());
941         }
942 
943         @Override
944         public void put(HttpHost host, AuthScheme authScheme) {
945             if (host != null && authScheme != null) {
946                 map.put(normalize(host), authScheme);
947             }
948         }
949 
950         @Override
951         public AuthScheme get(HttpHost host) {
952             if (host == null) {
953                 return null;
954             }
955             return map.get(normalize(host));
956         }
957 
958         @Override
959         public void remove(HttpHost host) {
960             if (host != null) {
961                 map.remove(normalize(host));
962             }
963         }
964 
965         @Override
966         public void clear() {
967             map.clear();
968         }
969     }
970 }