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 java.io.IOException;
22  import java.io.InputStream;
23  import java.io.InterruptedIOException;
24  import java.io.OutputStream;
25  import java.io.UncheckedIOException;
26  import java.net.InetAddress;
27  import java.net.URI;
28  import java.net.URISyntaxException;
29  import java.net.UnknownHostException;
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.Collections;
35  import java.util.Date;
36  import java.util.HashSet;
37  import java.util.List;
38  import java.util.Map;
39  import java.util.Set;
40  import java.util.function.Function;
41  import java.util.regex.Matcher;
42  
43  import org.apache.http.Header;
44  import org.apache.http.HttpEntity;
45  import org.apache.http.HttpEntityEnclosingRequest;
46  import org.apache.http.HttpHeaders;
47  import org.apache.http.HttpHost;
48  import org.apache.http.HttpResponse;
49  import org.apache.http.HttpStatus;
50  import org.apache.http.auth.AuthSchemeProvider;
51  import org.apache.http.auth.AuthScope;
52  import org.apache.http.client.CredentialsProvider;
53  import org.apache.http.client.HttpRequestRetryHandler;
54  import org.apache.http.client.HttpResponseException;
55  import org.apache.http.client.ServiceUnavailableRetryStrategy;
56  import org.apache.http.client.config.AuthSchemes;
57  import org.apache.http.client.config.CookieSpecs;
58  import org.apache.http.client.config.RequestConfig;
59  import org.apache.http.client.methods.CloseableHttpResponse;
60  import org.apache.http.client.methods.HttpGet;
61  import org.apache.http.client.methods.HttpHead;
62  import org.apache.http.client.methods.HttpOptions;
63  import org.apache.http.client.methods.HttpPut;
64  import org.apache.http.client.methods.HttpUriRequest;
65  import org.apache.http.client.utils.DateUtils;
66  import org.apache.http.client.utils.URIUtils;
67  import org.apache.http.config.Registry;
68  import org.apache.http.config.RegistryBuilder;
69  import org.apache.http.config.SocketConfig;
70  import org.apache.http.entity.AbstractHttpEntity;
71  import org.apache.http.entity.ByteArrayEntity;
72  import org.apache.http.impl.NoConnectionReuseStrategy;
73  import org.apache.http.impl.auth.BasicScheme;
74  import org.apache.http.impl.auth.BasicSchemeFactory;
75  import org.apache.http.impl.auth.DigestSchemeFactory;
76  import org.apache.http.impl.auth.KerberosSchemeFactory;
77  import org.apache.http.impl.auth.NTLMSchemeFactory;
78  import org.apache.http.impl.auth.SPNegoSchemeFactory;
79  import org.apache.http.impl.client.CloseableHttpClient;
80  import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
81  import org.apache.http.impl.client.HttpClientBuilder;
82  import org.apache.http.impl.client.LaxRedirectStrategy;
83  import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
84  import org.apache.http.protocol.HttpContext;
85  import org.apache.http.util.EntityUtils;
86  import org.eclipse.aether.ConfigurationProperties;
87  import org.eclipse.aether.RepositorySystemSession;
88  import org.eclipse.aether.repository.AuthenticationContext;
89  import org.eclipse.aether.repository.Proxy;
90  import org.eclipse.aether.repository.RemoteRepository;
91  import org.eclipse.aether.spi.connector.transport.AbstractTransporter;
92  import org.eclipse.aether.spi.connector.transport.GetTask;
93  import org.eclipse.aether.spi.connector.transport.PeekTask;
94  import org.eclipse.aether.spi.connector.transport.PutTask;
95  import org.eclipse.aether.spi.connector.transport.TransportTask;
96  import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor;
97  import org.eclipse.aether.spi.connector.transport.http.HttpTransporter;
98  import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException;
99  import org.eclipse.aether.spi.io.PathProcessor;
100 import org.eclipse.aether.transfer.NoTransporterException;
101 import org.eclipse.aether.transfer.TransferCancelledException;
102 import org.eclipse.aether.util.ConfigUtils;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
105 
106 import static java.util.Objects.requireNonNull;
107 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE_PATTERN;
108 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_REDIRECTS;
109 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_HTTP_RETRY_HANDLER_NAME;
110 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED;
111 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_MAX_REDIRECTS;
112 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.CONFIG_PROP_USE_SYSTEM_PROPERTIES;
113 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_FOLLOW_REDIRECTS;
114 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED;
115 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_MAX_REDIRECTS;
116 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.DEFAULT_USE_SYSTEM_PROPERTIES;
117 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.HTTP_RETRY_HANDLER_NAME_DEFAULT;
118 import static org.eclipse.aether.transport.apache.ApacheTransporterConfigurationKeys.HTTP_RETRY_HANDLER_NAME_STANDARD;
119 
120 /**
121  * A transporter for HTTP/HTTPS.
122  */
123 final class ApacheTransporter extends AbstractTransporter implements HttpTransporter {
124     private static final Logger LOGGER = LoggerFactory.getLogger(ApacheTransporter.class);
125 
126     private final ChecksumExtractor checksumExtractor;
127 
128     private final PathProcessor pathProcessor;
129 
130     private final AuthenticationContext repoAuthContext;
131 
132     private final AuthenticationContext proxyAuthContext;
133 
134     private final URI baseUri;
135 
136     private final HttpHost server;
137 
138     private final HttpHost proxy;
139 
140     private final CloseableHttpClient client;
141 
142     private final Map<?, ?> headers;
143 
144     private final LocalState state;
145 
146     private final boolean preemptiveAuth;
147 
148     private final boolean preemptivePutAuth;
149 
150     private final boolean supportWebDav;
151 
152     @SuppressWarnings("checkstyle:methodlength")
153     ApacheTransporter(
154             RemoteRepository repository,
155             RepositorySystemSession session,
156             ChecksumExtractor checksumExtractor,
157             PathProcessor pathProcessor)
158             throws NoTransporterException {
159         this.checksumExtractor = checksumExtractor;
160         this.pathProcessor = pathProcessor;
161         try {
162             this.baseUri = new URI(repository.getUrl()).parseServerAuthority();
163             if (baseUri.isOpaque()) {
164                 throw new URISyntaxException(repository.getUrl(), "URL must not be opaque");
165             }
166             this.server = URIUtils.extractHost(baseUri);
167             if (server == null) {
168                 throw new URISyntaxException(repository.getUrl(), "URL lacks host name");
169             }
170         } catch (URISyntaxException e) {
171             throw new NoTransporterException(repository, e.getMessage(), e);
172         }
173         this.proxy = toHost(repository.getProxy());
174 
175         this.repoAuthContext = AuthenticationContext.forRepository(session, repository);
176         this.proxyAuthContext = AuthenticationContext.forProxy(session, repository);
177 
178         String httpsSecurityMode = ConfigUtils.getString(
179                 session,
180                 ConfigurationProperties.HTTPS_SECURITY_MODE_DEFAULT,
181                 ConfigurationProperties.HTTPS_SECURITY_MODE + "." + repository.getId(),
182                 ConfigurationProperties.HTTPS_SECURITY_MODE);
183         final int connectionMaxTtlSeconds = ConfigUtils.getInteger(
184                 session,
185                 ConfigurationProperties.DEFAULT_HTTP_CONNECTION_MAX_TTL,
186                 ConfigurationProperties.HTTP_CONNECTION_MAX_TTL + "." + repository.getId(),
187                 ConfigurationProperties.HTTP_CONNECTION_MAX_TTL);
188         final int maxConnectionsPerRoute = ConfigUtils.getInteger(
189                 session,
190                 ConfigurationProperties.DEFAULT_HTTP_MAX_CONNECTIONS_PER_ROUTE,
191                 ConfigurationProperties.HTTP_MAX_CONNECTIONS_PER_ROUTE + "." + repository.getId(),
192                 ConfigurationProperties.HTTP_MAX_CONNECTIONS_PER_ROUTE);
193         this.state = new LocalState(
194                 session,
195                 repository,
196                 new ConnMgrConfig(
197                         session, repoAuthContext, httpsSecurityMode, connectionMaxTtlSeconds, maxConnectionsPerRoute));
198 
199         this.headers = ConfigUtils.getMap(
200                 session,
201                 Collections.emptyMap(),
202                 ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(),
203                 ConfigurationProperties.HTTP_HEADERS);
204 
205         this.preemptiveAuth = ConfigUtils.getBoolean(
206                 session,
207                 ConfigurationProperties.DEFAULT_HTTP_PREEMPTIVE_AUTH,
208                 ConfigurationProperties.HTTP_PREEMPTIVE_AUTH + "." + repository.getId(),
209                 ConfigurationProperties.HTTP_PREEMPTIVE_AUTH);
210         this.preemptivePutAuth = ConfigUtils.getBoolean(
211                 session,
212                 ConfigurationProperties.DEFAULT_HTTP_PREEMPTIVE_PUT_AUTH,
213                 ConfigurationProperties.HTTP_PREEMPTIVE_PUT_AUTH + "." + repository.getId(),
214                 ConfigurationProperties.HTTP_PREEMPTIVE_PUT_AUTH);
215         this.supportWebDav = ConfigUtils.getBoolean(
216                 session,
217                 ConfigurationProperties.DEFAULT_HTTP_SUPPORT_WEBDAV,
218                 ConfigurationProperties.HTTP_SUPPORT_WEBDAV + "." + repository.getId(),
219                 ConfigurationProperties.HTTP_SUPPORT_WEBDAV);
220         String credentialEncoding = ConfigUtils.getString(
221                 session,
222                 ConfigurationProperties.DEFAULT_HTTP_CREDENTIAL_ENCODING,
223                 ConfigurationProperties.HTTP_CREDENTIAL_ENCODING + "." + repository.getId(),
224                 ConfigurationProperties.HTTP_CREDENTIAL_ENCODING);
225         int connectTimeout = ConfigUtils.getInteger(
226                 session,
227                 ConfigurationProperties.DEFAULT_CONNECT_TIMEOUT,
228                 ConfigurationProperties.CONNECT_TIMEOUT + "." + repository.getId(),
229                 ConfigurationProperties.CONNECT_TIMEOUT);
230         int requestTimeout = ConfigUtils.getInteger(
231                 session,
232                 ConfigurationProperties.DEFAULT_REQUEST_TIMEOUT,
233                 ConfigurationProperties.REQUEST_TIMEOUT + "." + repository.getId(),
234                 ConfigurationProperties.REQUEST_TIMEOUT);
235         int retryCount = ConfigUtils.getInteger(
236                 session,
237                 ConfigurationProperties.DEFAULT_HTTP_RETRY_HANDLER_COUNT,
238                 ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT + "." + repository.getId(),
239                 ConfigurationProperties.HTTP_RETRY_HANDLER_COUNT);
240         long retryInterval = ConfigUtils.getLong(
241                 session,
242                 ConfigurationProperties.DEFAULT_HTTP_RETRY_HANDLER_INTERVAL,
243                 ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL + "." + repository.getId(),
244                 ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL);
245         long retryIntervalMax = ConfigUtils.getLong(
246                 session,
247                 ConfigurationProperties.DEFAULT_HTTP_RETRY_HANDLER_INTERVAL_MAX,
248                 ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL_MAX + "." + repository.getId(),
249                 ConfigurationProperties.HTTP_RETRY_HANDLER_INTERVAL_MAX);
250         String serviceUnavailableCodesString = ConfigUtils.getString(
251                 session,
252                 ConfigurationProperties.DEFAULT_HTTP_RETRY_HANDLER_SERVICE_UNAVAILABLE,
253                 ConfigurationProperties.HTTP_RETRY_HANDLER_SERVICE_UNAVAILABLE + "." + repository.getId(),
254                 ConfigurationProperties.HTTP_RETRY_HANDLER_SERVICE_UNAVAILABLE);
255         String retryHandlerName = ConfigUtils.getString(
256                 session,
257                 HTTP_RETRY_HANDLER_NAME_STANDARD,
258                 CONFIG_PROP_HTTP_RETRY_HANDLER_NAME + "." + repository.getId(),
259                 CONFIG_PROP_HTTP_RETRY_HANDLER_NAME);
260         boolean retryHandlerRequestSentEnabled = ConfigUtils.getBoolean(
261                 session,
262                 DEFAULT_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED,
263                 CONFIG_PROP_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED + "." + repository.getId(),
264                 CONFIG_PROP_HTTP_RETRY_HANDLER_REQUEST_SENT_ENABLED);
265         int maxRedirects = ConfigUtils.getInteger(
266                 session,
267                 DEFAULT_MAX_REDIRECTS,
268                 CONFIG_PROP_MAX_REDIRECTS + "." + repository.getId(),
269                 CONFIG_PROP_MAX_REDIRECTS);
270         boolean followRedirects = ConfigUtils.getBoolean(
271                 session,
272                 DEFAULT_FOLLOW_REDIRECTS,
273                 CONFIG_PROP_FOLLOW_REDIRECTS + "." + repository.getId(),
274                 CONFIG_PROP_FOLLOW_REDIRECTS);
275         String userAgent = ConfigUtils.getString(
276                 session, ConfigurationProperties.DEFAULT_USER_AGENT, ConfigurationProperties.USER_AGENT);
277 
278         Charset credentialsCharset = Charset.forName(credentialEncoding);
279         Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
280                 .register(AuthSchemes.BASIC, new BasicSchemeFactory(credentialsCharset))
281                 .register(AuthSchemes.DIGEST, new DigestSchemeFactory(credentialsCharset))
282                 .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
283                 .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
284                 .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())
285                 .build();
286         SocketConfig socketConfig =
287                 // the time to establish connection (low level)
288                 SocketConfig.custom().setSoTimeout(requestTimeout).build();
289         RequestConfig requestConfig = RequestConfig.custom()
290                 .setMaxRedirects(maxRedirects)
291                 .setRedirectsEnabled(followRedirects)
292                 .setRelativeRedirectsAllowed(followRedirects)
293                 // the time waiting for data; max time between two data packets
294                 .setSocketTimeout(requestTimeout)
295                 // the time to establish the connection (high level)
296                 .setConnectTimeout(connectTimeout)
297                 // the time to wait for a connection from the connection manager/pool
298                 .setConnectionRequestTimeout(connectTimeout)
299                 .setLocalAddress(getHttpLocalAddress(session, repository))
300                 .setCookieSpec(CookieSpecs.STANDARD)
301                 .build();
302 
303         HttpRequestRetryHandler retryHandler;
304         if (HTTP_RETRY_HANDLER_NAME_STANDARD.equals(retryHandlerName)) {
305             retryHandler = new StandardHttpRequestRetryHandler(retryCount, retryHandlerRequestSentEnabled);
306         } else if (HTTP_RETRY_HANDLER_NAME_DEFAULT.equals(retryHandlerName)) {
307             retryHandler = new DefaultHttpRequestRetryHandler(retryCount, retryHandlerRequestSentEnabled);
308         } else {
309             throw new IllegalArgumentException(
310                     "Unsupported parameter " + CONFIG_PROP_HTTP_RETRY_HANDLER_NAME + " value: " + retryHandlerName);
311         }
312         Set<Integer> serviceUnavailableCodes = new HashSet<>();
313         try {
314             for (String code : ConfigUtils.parseCommaSeparatedUniqueNames(serviceUnavailableCodesString)) {
315                 serviceUnavailableCodes.add(Integer.parseInt(code));
316             }
317         } catch (NumberFormatException e) {
318             throw new IllegalArgumentException(
319                     "Illegal HTTP codes for " + ConfigurationProperties.HTTP_RETRY_HANDLER_SERVICE_UNAVAILABLE
320                             + " (list of integers): " + serviceUnavailableCodesString);
321         }
322         ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new ResolverServiceUnavailableRetryStrategy(
323                 retryCount, retryInterval, retryIntervalMax, serviceUnavailableCodes);
324 
325         HttpClientBuilder builder = HttpClientBuilder.create()
326                 .setUserAgent(userAgent)
327                 .setRedirectStrategy(LaxRedirectStrategy.INSTANCE)
328                 .setDefaultSocketConfig(socketConfig)
329                 .setDefaultRequestConfig(requestConfig)
330                 .setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
331                 .setRetryHandler(retryHandler)
332                 .setDefaultAuthSchemeRegistry(authSchemeRegistry)
333                 .setConnectionManager(state.getConnectionManager())
334                 .setConnectionManagerShared(true)
335                 .setDefaultCredentialsProvider(toCredentialsProvider(server, repoAuthContext, proxy, proxyAuthContext))
336                 .setProxy(proxy);
337         final boolean useSystemProperties = ConfigUtils.getBoolean(
338                 session,
339                 DEFAULT_USE_SYSTEM_PROPERTIES,
340                 CONFIG_PROP_USE_SYSTEM_PROPERTIES + "." + repository.getId(),
341                 CONFIG_PROP_USE_SYSTEM_PROPERTIES);
342         if (useSystemProperties) {
343             LOGGER.warn(
344                     "Transport used Apache HttpClient is instructed to use system properties: this may yield in unwanted side-effects!");
345             LOGGER.warn("Please use documented means to configure resolver transport.");
346             builder.useSystemProperties();
347         }
348 
349         final String expectContinue = ConfigUtils.getString(
350                 session,
351                 null,
352                 ConfigurationProperties.HTTP_EXPECT_CONTINUE + "." + repository.getId(),
353                 ConfigurationProperties.HTTP_EXPECT_CONTINUE);
354         if (expectContinue != null) {
355             state.setExpectContinue(Boolean.parseBoolean(expectContinue));
356         }
357 
358         final boolean reuseConnections = ConfigUtils.getBoolean(
359                 session,
360                 ConfigurationProperties.DEFAULT_HTTP_REUSE_CONNECTIONS,
361                 ConfigurationProperties.HTTP_REUSE_CONNECTIONS + "." + repository.getId(),
362                 ConfigurationProperties.HTTP_REUSE_CONNECTIONS);
363         if (!reuseConnections) {
364             builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
365         }
366 
367         this.client = builder.build();
368     }
369 
370     /**
371      * Returns non-null {@link InetAddress} if set in configuration, {@code null} otherwise.
372      */
373     private InetAddress getHttpLocalAddress(RepositorySystemSession session, RemoteRepository repository) {
374         String bindAddress = ConfigUtils.getString(
375                 session,
376                 null,
377                 ConfigurationProperties.HTTP_LOCAL_ADDRESS + "." + repository.getId(),
378                 ConfigurationProperties.HTTP_LOCAL_ADDRESS);
379         if (bindAddress == null) {
380             return null;
381         }
382         try {
383             return InetAddress.getByName(bindAddress);
384         } catch (UnknownHostException uhe) {
385             throw new IllegalArgumentException(
386                     "Given bind address (" + bindAddress + ") cannot be resolved for remote repository " + repository,
387                     uhe);
388         }
389     }
390 
391     private static HttpHost toHost(Proxy proxy) {
392         HttpHost host = null;
393         if (proxy != null) {
394             // in Maven, the proxy.protocol is used for proxy matching against remote repository protocol; no TLS proxy
395             // support
396             // https://github.com/apache/maven/issues/2519
397             // https://github.com/apache/maven-resolver/issues/745
398             host = new HttpHost(proxy.getHost(), proxy.getPort());
399         }
400         return host;
401     }
402 
403     private static CredentialsProvider toCredentialsProvider(
404             HttpHost server, AuthenticationContext serverAuthCtx, HttpHost proxy, AuthenticationContext proxyAuthCtx) {
405         CredentialsProvider provider = toCredentialsProvider(server.getHostName(), AuthScope.ANY_PORT, serverAuthCtx);
406         if (proxy != null) {
407             CredentialsProvider p = toCredentialsProvider(proxy.getHostName(), proxy.getPort(), proxyAuthCtx);
408             provider = new DemuxCredentialsProvider(provider, p, proxy);
409         }
410         return provider;
411     }
412 
413     private static CredentialsProvider toCredentialsProvider(String host, int port, AuthenticationContext ctx) {
414         DeferredCredentialsProvider provider = new DeferredCredentialsProvider();
415         if (ctx != null) {
416             AuthScope basicScope = new AuthScope(host, port);
417             provider.setCredentials(basicScope, new DeferredCredentialsProvider.BasicFactory(ctx));
418 
419             AuthScope ntlmScope = new AuthScope(host, port, AuthScope.ANY_REALM, "ntlm");
420             provider.setCredentials(ntlmScope, new DeferredCredentialsProvider.NtlmFactory(ctx));
421         }
422         return provider;
423     }
424 
425     LocalState getState() {
426         return state;
427     }
428 
429     private URI resolve(TransportTask task) {
430         return UriUtils.resolve(baseUri, task.getLocation());
431     }
432 
433     @Override
434     public int classify(Throwable error) {
435         if (error instanceof HttpTransporterException
436                 && ((HttpTransporterException) error).getStatusCode() == HttpStatus.SC_NOT_FOUND) {
437             return ERROR_NOT_FOUND;
438         }
439         return ERROR_OTHER;
440     }
441 
442     @Override
443     protected void implPeek(PeekTask task) throws Exception {
444         HttpHead request = commonHeaders(new HttpHead(resolve(task)));
445         try {
446             execute(request, null);
447         } catch (HttpResponseException e) {
448             throw new HttpTransporterException(e.getStatusCode());
449         }
450     }
451 
452     @Override
453     protected void implGet(GetTask task) throws Exception {
454         boolean resume = true;
455 
456         EntityGetter getter = new EntityGetter(task);
457         HttpGet request = commonHeaders(new HttpGet(resolve(task)));
458         while (true) {
459             try {
460                 if (resume) {
461                     resume(request, task);
462                 }
463                 execute(request, getter);
464                 break;
465             } catch (HttpResponseException e) {
466                 if (resume
467                         && e.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED
468                         && request.containsHeader(HttpHeaders.RANGE)) {
469                     request = commonHeaders(new HttpGet(resolve(task)));
470                     resume = false;
471                     continue;
472                 }
473                 throw new HttpTransporterException(e.getStatusCode());
474             }
475         }
476     }
477 
478     @Override
479     protected void implPut(PutTask task) throws Exception {
480         PutTaskEntity entity = new PutTaskEntity(task);
481         HttpPut request = commonHeaders(entity(new HttpPut(resolve(task)), entity));
482         try {
483             execute(request, null);
484         } catch (HttpResponseException e) {
485             if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED && request.containsHeader(HttpHeaders.EXPECT)) {
486                 state.setExpectContinue(false);
487                 request = commonHeaders(entity(new HttpPut(request.getURI()), entity));
488                 execute(request, null);
489                 return;
490             }
491             throw new HttpTransporterException(e.getStatusCode());
492         }
493     }
494 
495     private void execute(HttpUriRequest request, EntityGetter getter) throws Exception {
496         try {
497             SharingHttpContext context = new SharingHttpContext(state);
498             prepare(request, context);
499             try (CloseableHttpResponse response = client.execute(server, request, context)) {
500                 try {
501                     context.close();
502                     handleStatus(response);
503                     if (getter != null) {
504                         getter.handle(response);
505                     }
506                 } finally {
507                     EntityUtils.consumeQuietly(response.getEntity());
508                 }
509             }
510         } catch (IOException e) {
511             if (e.getCause() instanceof TransferCancelledException) {
512                 throw (Exception) e.getCause();
513             }
514             throw e;
515         }
516     }
517 
518     private void prepare(HttpUriRequest request, SharingHttpContext context) throws Exception {
519         final boolean put = HttpPut.METHOD_NAME.equalsIgnoreCase(request.getMethod());
520         if (preemptiveAuth || (preemptivePutAuth && put)) {
521             context.getAuthCache().put(server, new BasicScheme());
522         }
523         if (supportWebDav) {
524             if (state.getWebDav() == null && (put || isPayloadPresent(request))) {
525                 HttpOptions req = commonHeaders(new HttpOptions(request.getURI()));
526                 try (CloseableHttpResponse response = client.execute(server, req, context)) {
527                     state.setWebDav(response.containsHeader(HttpHeaders.DAV));
528                     EntityUtils.consumeQuietly(response.getEntity());
529                 } catch (IOException e) {
530                     LOGGER.debug("Failed to prepare HTTP context", e);
531                 }
532             }
533             if (put && Boolean.TRUE.equals(state.getWebDav())) {
534                 mkdirs(request.getURI(), context);
535             }
536         }
537     }
538 
539     private void mkdirs(URI uri, SharingHttpContext context) throws Exception {
540         List<URI> dirs = UriUtils.getDirectories(baseUri, uri);
541         int index = 0;
542         for (; index < dirs.size(); index++) {
543             try (CloseableHttpResponse response =
544                     client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))), context)) {
545                 try {
546                     int status = response.getStatusLine().getStatusCode();
547                     if (status < 300 || status == HttpStatus.SC_METHOD_NOT_ALLOWED) {
548                         break;
549                     } else if (status == HttpStatus.SC_CONFLICT) {
550                         continue;
551                     }
552                     handleStatus(response);
553                 } finally {
554                     EntityUtils.consumeQuietly(response.getEntity());
555                 }
556             } catch (IOException e) {
557                 LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e);
558                 return;
559             }
560         }
561         for (index--; index >= 0; index--) {
562             try (CloseableHttpResponse response =
563                     client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))), context)) {
564                 try {
565                     handleStatus(response);
566                 } finally {
567                     EntityUtils.consumeQuietly(response.getEntity());
568                 }
569             } catch (IOException e) {
570                 LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e);
571                 return;
572             }
573         }
574     }
575 
576     private <T extends HttpEntityEnclosingRequest> T entity(T request, HttpEntity entity) {
577         request.setEntity(entity);
578         return request;
579     }
580 
581     private boolean isPayloadPresent(HttpUriRequest request) {
582         if (request instanceof HttpEntityEnclosingRequest) {
583             HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
584             return entity != null && entity.getContentLength() != 0;
585         }
586         return false;
587     }
588 
589     private <T extends HttpUriRequest> T commonHeaders(T request) {
590         request.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store");
591         request.setHeader(HttpHeaders.PRAGMA, "no-cache");
592 
593         if (state.isExpectContinue() && isPayloadPresent(request)) {
594             request.setHeader(HttpHeaders.EXPECT, "100-continue");
595         }
596 
597         for (Map.Entry<?, ?> entry : headers.entrySet()) {
598             if (!(entry.getKey() instanceof String)) {
599                 continue;
600             }
601             if (entry.getValue() instanceof String) {
602                 request.setHeader(entry.getKey().toString(), entry.getValue().toString());
603             } else {
604                 request.removeHeaders(entry.getKey().toString());
605             }
606         }
607 
608         if (!state.isExpectContinue()) {
609             request.removeHeaders(HttpHeaders.EXPECT);
610         }
611 
612         return request;
613     }
614 
615     private <T extends HttpUriRequest> void resume(T request, GetTask task) throws IOException {
616         long resumeOffset = task.getResumeOffset();
617         if (resumeOffset > 0L && task.getDataPath() != null) {
618             long lastModified = Files.getLastModifiedTime(task.getDataPath()).toMillis();
619             request.setHeader(HttpHeaders.RANGE, "bytes=" + resumeOffset + '-');
620             request.setHeader(
621                     HttpHeaders.IF_UNMODIFIED_SINCE, DateUtils.formatDate(new Date(lastModified - 60L * 1000L)));
622             request.setHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
623         }
624     }
625 
626     private void handleStatus(CloseableHttpResponse response) throws Exception {
627         int status = response.getStatusLine().getStatusCode();
628         if (status >= 300) {
629             ApacheRFC9457Reporter.INSTANCE.generateException(response, (statusCode, reasonPhrase) -> {
630                 throw new HttpResponseException(statusCode, reasonPhrase + " (" + statusCode + ")");
631             });
632         }
633     }
634 
635     @Override
636     protected void implClose() {
637         try {
638             client.close();
639         } catch (IOException e) {
640             throw new UncheckedIOException(e);
641         }
642         AuthenticationContext.close(repoAuthContext);
643         AuthenticationContext.close(proxyAuthContext);
644         state.close();
645     }
646 
647     private class EntityGetter {
648 
649         private final GetTask task;
650 
651         EntityGetter(GetTask task) {
652             this.task = task;
653         }
654 
655         public void handle(CloseableHttpResponse response) throws IOException, TransferCancelledException {
656             HttpEntity entity = response.getEntity();
657             if (entity == null) {
658                 entity = new ByteArrayEntity(new byte[0]);
659             }
660 
661             long offset = 0L, length = entity.getContentLength();
662             Header rangeHeader = response.getFirstHeader(HttpHeaders.CONTENT_RANGE);
663             String range = rangeHeader != null ? rangeHeader.getValue() : null;
664             if (range != null) {
665                 Matcher m = CONTENT_RANGE_PATTERN.matcher(range);
666                 if (!m.matches()) {
667                     throw new IOException("Invalid Content-Range header for partial download: " + range);
668                 }
669                 offset = Long.parseLong(m.group(1));
670                 length = Long.parseLong(m.group(2)) + 1L;
671                 if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) {
672                     throw new IOException("Invalid Content-Range header for partial download from offset "
673                             + task.getResumeOffset() + ": " + range);
674                 }
675             }
676 
677             final boolean resume = offset > 0L;
678             final Path dataFile = task.getDataPath();
679             if (dataFile == null) {
680                 try (InputStream is = entity.getContent()) {
681                     utilGet(task, is, true, length, resume);
682                     extractChecksums(response);
683                 }
684             } else {
685                 try (PathProcessor.CollocatedTempFile tempFile = pathProcessor.newTempFile(dataFile)) {
686                     task.setDataPath(tempFile.getPath(), resume);
687                     if (resume && Files.isRegularFile(dataFile)) {
688                         try (InputStream inputStream = Files.newInputStream(dataFile)) {
689                             Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
690                         }
691                     }
692                     try (InputStream is = entity.getContent()) {
693                         utilGet(task, is, true, length, resume);
694                     }
695                     tempFile.move();
696                 } finally {
697                     task.setDataPath(dataFile);
698                 }
699             }
700             if (task.getDataPath() != null) {
701                 Header lastModifiedHeader =
702                         response.getFirstHeader(HttpHeaders.LAST_MODIFIED); // note: Wagon also does first not last
703                 if (lastModifiedHeader != null) {
704                     Date lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
705                     if (lastModified != null) {
706                         pathProcessor.setLastModified(task.getDataPath(), lastModified.getTime());
707                     }
708                 }
709             }
710             extractChecksums(response);
711         }
712 
713         private void extractChecksums(CloseableHttpResponse response) {
714             Map<String, String> checksums = checksumExtractor.extractChecksums(headerGetter(response));
715             if (checksums != null && !checksums.isEmpty()) {
716                 checksums.forEach(task::setChecksum);
717             }
718         }
719     }
720 
721     private static Function<String, String> headerGetter(CloseableHttpResponse closeableHttpResponse) {
722         return s -> {
723             Header header = closeableHttpResponse.getFirstHeader(s);
724             return header != null ? header.getValue() : null;
725         };
726     }
727 
728     private class PutTaskEntity extends AbstractHttpEntity {
729 
730         private final PutTask task;
731 
732         PutTaskEntity(PutTask task) {
733             this.task = task;
734         }
735 
736         @Override
737         public boolean isRepeatable() {
738             return true;
739         }
740 
741         @Override
742         public boolean isStreaming() {
743             return false;
744         }
745 
746         @Override
747         public long getContentLength() {
748             return task.getDataLength();
749         }
750 
751         @Override
752         public InputStream getContent() throws IOException {
753             return task.newInputStream();
754         }
755 
756         @Override
757         public void writeTo(OutputStream os) throws IOException {
758             try {
759                 utilPut(task, os, false);
760             } catch (TransferCancelledException e) {
761                 throw (IOException) new InterruptedIOException().initCause(e);
762             }
763         }
764     }
765 
766     private static class ResolverServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy {
767         private final int retryCount;
768 
769         private final long retryInterval;
770 
771         private final long retryIntervalMax;
772 
773         private final Set<Integer> serviceUnavailableHttpCodes;
774 
775         /**
776          * Ugly, but forced by HttpClient API {@link ServiceUnavailableRetryStrategy}: the calls for
777          * {@link #retryRequest(HttpResponse, int, HttpContext)} and {@link #getRetryInterval()} are done by same
778          * thread and are actually done from spot that are very close to each other (almost subsequent calls).
779          */
780         private static final ThreadLocal<Long> RETRY_INTERVAL_HOLDER = new ThreadLocal<>();
781 
782         private ResolverServiceUnavailableRetryStrategy(
783                 int retryCount, long retryInterval, long retryIntervalMax, Set<Integer> serviceUnavailableHttpCodes) {
784             if (retryCount < 0) {
785                 throw new IllegalArgumentException("retryCount must be >= 0");
786             }
787             if (retryInterval < 0L) {
788                 throw new IllegalArgumentException("retryInterval must be >= 0");
789             }
790             if (retryIntervalMax < 0L) {
791                 throw new IllegalArgumentException("retryIntervalMax must be >= 0");
792             }
793             this.retryCount = retryCount;
794             this.retryInterval = retryInterval;
795             this.retryIntervalMax = retryIntervalMax;
796             this.serviceUnavailableHttpCodes = requireNonNull(serviceUnavailableHttpCodes);
797         }
798 
799         @Override
800         public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
801             final boolean retry = executionCount <= retryCount
802                     && (serviceUnavailableHttpCodes.contains(
803                             response.getStatusLine().getStatusCode()));
804             if (retry) {
805                 Long retryInterval = retryInterval(response, executionCount, context);
806                 if (retryInterval != null) {
807                     RETRY_INTERVAL_HOLDER.set(retryInterval);
808                     return true;
809                 }
810             }
811             RETRY_INTERVAL_HOLDER.remove();
812             return false;
813         }
814 
815         /**
816          * Calculates retry interval in milliseconds. If {@link HttpHeaders#RETRY_AFTER} header present, it obeys it.
817          * Otherwise, it returns {@link this#retryInterval} long value multiplied with {@code executionCount} (starts
818          * from 1 and goes 2, 3,...).
819          *
820          * @return Long representing the retry interval as millis, or {@code null} if the request should be failed.
821          */
822         private Long retryInterval(HttpResponse httpResponse, int executionCount, HttpContext httpContext) {
823             Long result = null;
824             Header header = httpResponse.getFirstHeader(HttpHeaders.RETRY_AFTER);
825             if (header != null && header.getValue() != null) {
826                 String headerValue = header.getValue();
827                 if (headerValue.contains(":")) { // is date when to retry
828                     Date when = DateUtils.parseDate(headerValue); // presumably future
829                     if (when != null) {
830                         result = Math.max(when.getTime() - System.currentTimeMillis(), 0L);
831                     }
832                 } else {
833                     try {
834                         result = Long.parseLong(headerValue) * 1000L; // is in seconds
835                     } catch (NumberFormatException e) {
836                         // fall through
837                     }
838                 }
839             }
840             if (result == null) {
841                 result = executionCount * this.retryInterval;
842             }
843             if (result > retryIntervalMax) {
844                 return null;
845             }
846             return result;
847         }
848 
849         @Override
850         public long getRetryInterval() {
851             Long ri = RETRY_INTERVAL_HOLDER.get();
852             if (ri == null) {
853                 return 0L;
854             }
855             RETRY_INTERVAL_HOLDER.remove();
856             return ri;
857         }
858     }
859 }