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