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