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