1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.util.Collections;
35 import java.util.Date;
36 import java.util.HashSet;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42
43 import org.apache.http.Header;
44 import org.apache.http.HttpEntity;
45 import org.apache.http.HttpEntityEnclosingRequest;
46 import org.apache.http.HttpHeaders;
47 import org.apache.http.HttpHost;
48 import org.apache.http.HttpResponse;
49 import org.apache.http.HttpStatus;
50 import org.apache.http.auth.AuthSchemeProvider;
51 import org.apache.http.auth.AuthScope;
52 import org.apache.http.client.CredentialsProvider;
53 import org.apache.http.client.HttpRequestRetryHandler;
54 import org.apache.http.client.HttpResponseException;
55 import org.apache.http.client.ServiceUnavailableRetryStrategy;
56 import org.apache.http.client.config.AuthSchemes;
57 import org.apache.http.client.config.CookieSpecs;
58 import org.apache.http.client.config.RequestConfig;
59 import org.apache.http.client.methods.CloseableHttpResponse;
60 import org.apache.http.client.methods.HttpGet;
61 import org.apache.http.client.methods.HttpHead;
62 import org.apache.http.client.methods.HttpOptions;
63 import org.apache.http.client.methods.HttpPut;
64 import org.apache.http.client.methods.HttpUriRequest;
65 import org.apache.http.client.utils.DateUtils;
66 import org.apache.http.client.utils.URIUtils;
67 import org.apache.http.config.Registry;
68 import org.apache.http.config.RegistryBuilder;
69 import org.apache.http.config.SocketConfig;
70 import org.apache.http.entity.AbstractHttpEntity;
71 import org.apache.http.entity.ByteArrayEntity;
72 import org.apache.http.impl.NoConnectionReuseStrategy;
73 import org.apache.http.impl.auth.BasicScheme;
74 import org.apache.http.impl.auth.BasicSchemeFactory;
75 import org.apache.http.impl.auth.DigestSchemeFactory;
76 import org.apache.http.impl.auth.KerberosSchemeFactory;
77 import org.apache.http.impl.auth.NTLMSchemeFactory;
78 import org.apache.http.impl.auth.SPNegoSchemeFactory;
79 import org.apache.http.impl.client.CloseableHttpClient;
80 import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
81 import org.apache.http.impl.client.HttpClientBuilder;
82 import org.apache.http.impl.client.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
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 =
215 ConfigUtils.getBoolean(
216 session, true, PREEMPTIVE_PUT_AUTH + "." + repository.getId(), PREEMPTIVE_PUT_AUTH);
217 this.supportWebDav =
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 .setCookieSpec(CookieSpecs.STANDARD)
282 .setSocketTimeout(requestTimeout)
283 .build();
284
285 HttpRequestRetryHandler retryHandler;
286 if (HTTP_RETRY_HANDLER_NAME_STANDARD.equals(retryHandlerName)) {
287 retryHandler = new StandardHttpRequestRetryHandler(retryCount, retryHandlerRequestSentEnabled);
288 } else if (HTTP_RETRY_HANDLER_NAME_DEFAULT.equals(retryHandlerName)) {
289 retryHandler = new DefaultHttpRequestRetryHandler(retryCount, retryHandlerRequestSentEnabled);
290 } else {
291 throw new IllegalArgumentException(
292 "Unsupported parameter " + HTTP_RETRY_HANDLER_NAME + " value: " + retryHandlerName);
293 }
294 Set<Integer> serviceUnavailableCodes = new HashSet<>();
295 try {
296 for (String code : ConfigUtils.parseCommaSeparatedUniqueNames(serviceUnavailableCodesString)) {
297 serviceUnavailableCodes.add(Integer.parseInt(code));
298 }
299 } catch (NumberFormatException e) {
300 throw new IllegalArgumentException(
301 "Illegal HTTP codes for " + ConfigurationProperties.HTTP_RETRY_HANDLER_SERVICE_UNAVAILABLE
302 + " (list of integers): " + serviceUnavailableCodesString);
303 }
304 ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new ResolverServiceUnavailableRetryStrategy(
305 retryCount, retryInterval, retryIntervalMax, serviceUnavailableCodes);
306
307 HttpClientBuilder builder = HttpClientBuilder.create()
308 .setUserAgent(userAgent)
309 .setDefaultSocketConfig(socketConfig)
310 .setDefaultRequestConfig(requestConfig)
311 .setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
312 .setRetryHandler(retryHandler)
313 .setDefaultAuthSchemeRegistry(authSchemeRegistry)
314 .setConnectionManager(state.getConnectionManager())
315 .setConnectionManagerShared(true)
316 .setDefaultCredentialsProvider(toCredentialsProvider(server, repoAuthContext, proxy, proxyAuthContext))
317 .setProxy(proxy);
318 final boolean useSystemProperties = ConfigUtils.getBoolean(
319 session, false, USE_SYSTEM_PROPERTIES + "." + repository.getId(), USE_SYSTEM_PROPERTIES);
320 if (useSystemProperties) {
321 LOGGER.warn(
322 "Transport used Apache HttpClient is instructed to use system properties: this may yield in unwanted side-effects!");
323 LOGGER.warn("Please use documented means to configure resolver transport.");
324 builder.useSystemProperties();
325 }
326
327 final String expectContinue = ConfigUtils.getString(
328 session,
329 null,
330 ConfigurationProperties.HTTP_EXPECT_CONTINUE + "." + repository.getId(),
331 ConfigurationProperties.HTTP_EXPECT_CONTINUE);
332 if (expectContinue != null) {
333 state.setExpectContinue(Boolean.parseBoolean(expectContinue));
334 }
335
336 final boolean reuseConnections = ConfigUtils.getBoolean(
337 session,
338 ConfigurationProperties.DEFAULT_HTTP_REUSE_CONNECTIONS,
339 ConfigurationProperties.HTTP_REUSE_CONNECTIONS + "." + repository.getId(),
340 ConfigurationProperties.HTTP_REUSE_CONNECTIONS);
341 if (!reuseConnections) {
342 builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
343 }
344
345 this.client = builder.build();
346 }
347
348
349
350
351 private InetAddress getBindAddress(RepositorySystemSession session, RemoteRepository repository) {
352 String bindAddress =
353 ConfigUtils.getString(session, null, BIND_ADDRESS + "." + repository.getId(), BIND_ADDRESS);
354 if (bindAddress == null) {
355 return null;
356 }
357 try {
358 return InetAddress.getByName(bindAddress);
359 } catch (UnknownHostException uhe) {
360 throw new IllegalArgumentException(
361 "Given bind address (" + bindAddress + ") cannot be resolved for remote repository " + repository,
362 uhe);
363 }
364 }
365
366 private static HttpHost toHost(Proxy proxy) {
367 HttpHost host = null;
368 if (proxy != null) {
369 host = new HttpHost(proxy.getHost(), proxy.getPort());
370 }
371 return host;
372 }
373
374 private static CredentialsProvider toCredentialsProvider(
375 HttpHost server, AuthenticationContext serverAuthCtx, HttpHost proxy, AuthenticationContext proxyAuthCtx) {
376 CredentialsProvider provider = toCredentialsProvider(server.getHostName(), AuthScope.ANY_PORT, serverAuthCtx);
377 if (proxy != null) {
378 CredentialsProvider p = toCredentialsProvider(proxy.getHostName(), proxy.getPort(), proxyAuthCtx);
379 provider = new DemuxCredentialsProvider(provider, p, proxy);
380 }
381 return provider;
382 }
383
384 private static CredentialsProvider toCredentialsProvider(String host, int port, AuthenticationContext ctx) {
385 DeferredCredentialsProvider provider = new DeferredCredentialsProvider();
386 if (ctx != null) {
387 AuthScope basicScope = new AuthScope(host, port);
388 provider.setCredentials(basicScope, new DeferredCredentialsProvider.BasicFactory(ctx));
389
390 AuthScope ntlmScope = new AuthScope(host, port, AuthScope.ANY_REALM, "ntlm");
391 provider.setCredentials(ntlmScope, new DeferredCredentialsProvider.NtlmFactory(ctx));
392 }
393 return provider;
394 }
395
396 LocalState getState() {
397 return state;
398 }
399
400 private URI resolve(TransportTask task) {
401 return UriUtils.resolve(baseUri, task.getLocation());
402 }
403
404 @Override
405 public int classify(Throwable error) {
406 if (error instanceof HttpResponseException
407 && ((HttpResponseException) error).getStatusCode() == HttpStatus.SC_NOT_FOUND) {
408 return ERROR_NOT_FOUND;
409 }
410 return ERROR_OTHER;
411 }
412
413 @Override
414 protected void implPeek(PeekTask task) throws Exception {
415 HttpHead request = commonHeaders(new HttpHead(resolve(task)));
416 execute(request, null);
417 }
418
419 @Override
420 protected void implGet(GetTask task) throws Exception {
421 boolean resume = true;
422 boolean applyChecksumExtractors = true;
423
424 EntityGetter getter = new EntityGetter(task);
425 HttpGet request = commonHeaders(new HttpGet(resolve(task)));
426 while (true) {
427 try {
428 if (resume) {
429 resume(request, task);
430 }
431 if (applyChecksumExtractors) {
432 for (ChecksumExtractor checksumExtractor : checksumExtractors.values()) {
433 checksumExtractor.prepareRequest(request);
434 }
435 }
436 execute(request, getter);
437 break;
438 } catch (HttpResponseException e) {
439 if (resume
440 && e.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED
441 && request.containsHeader(HttpHeaders.RANGE)) {
442 request = commonHeaders(new HttpGet(resolve(task)));
443 resume = false;
444 continue;
445 }
446 if (applyChecksumExtractors) {
447 boolean retryWithoutExtractors = false;
448 for (ChecksumExtractor checksumExtractor : checksumExtractors.values()) {
449 if (checksumExtractor.retryWithoutExtractor(e)) {
450 retryWithoutExtractors = true;
451 break;
452 }
453 }
454 if (retryWithoutExtractors) {
455 request = commonHeaders(new HttpGet(resolve(task)));
456 applyChecksumExtractors = false;
457 continue;
458 }
459 }
460 throw e;
461 }
462 }
463 }
464
465 @Override
466 protected void implPut(PutTask task) throws Exception {
467 PutTaskEntity entity = new PutTaskEntity(task);
468 HttpPut request = commonHeaders(entity(new HttpPut(resolve(task)), entity));
469 try {
470 execute(request, null);
471 } catch (HttpResponseException e) {
472 if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED && request.containsHeader(HttpHeaders.EXPECT)) {
473 state.setExpectContinue(false);
474 request = commonHeaders(entity(new HttpPut(request.getURI()), entity));
475 execute(request, null);
476 return;
477 }
478 throw e;
479 }
480 }
481
482 private void execute(HttpUriRequest request, EntityGetter getter) throws Exception {
483 try {
484 SharingHttpContext context = new SharingHttpContext(state);
485 prepare(request, context);
486 try (CloseableHttpResponse response = client.execute(server, request, context)) {
487 try {
488 context.close();
489 handleStatus(response);
490 if (getter != null) {
491 getter.handle(response);
492 }
493 } finally {
494 EntityUtils.consumeQuietly(response.getEntity());
495 }
496 }
497 } catch (IOException e) {
498 if (e.getCause() instanceof TransferCancelledException) {
499 throw (Exception) e.getCause();
500 }
501 throw e;
502 }
503 }
504
505 private void prepare(HttpUriRequest request, SharingHttpContext context) {
506 final boolean put = HttpPut.METHOD_NAME.equalsIgnoreCase(request.getMethod());
507 if (preemptiveAuth || (preemptivePutAuth && put)) {
508 context.getAuthCache().put(server, new BasicScheme());
509 }
510 if (supportWebDav) {
511 if (state.getWebDav() == null && (put || isPayloadPresent(request))) {
512 HttpOptions req = commonHeaders(new HttpOptions(request.getURI()));
513 try (CloseableHttpResponse response = client.execute(server, req, context)) {
514 state.setWebDav(response.containsHeader(HttpHeaders.DAV));
515 EntityUtils.consumeQuietly(response.getEntity());
516 } catch (IOException e) {
517 LOGGER.debug("Failed to prepare HTTP context", e);
518 }
519 }
520 if (put && Boolean.TRUE.equals(state.getWebDav())) {
521 mkdirs(request.getURI(), context);
522 }
523 }
524 }
525
526 @SuppressWarnings("checkstyle:magicnumber")
527 private void mkdirs(URI uri, SharingHttpContext context) {
528 List<URI> dirs = UriUtils.getDirectories(baseUri, uri);
529 int index = 0;
530 for (; index < dirs.size(); index++) {
531 try (CloseableHttpResponse response =
532 client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))), context)) {
533 try {
534 int status = response.getStatusLine().getStatusCode();
535 if (status < 300 || status == HttpStatus.SC_METHOD_NOT_ALLOWED) {
536 break;
537 } else if (status == HttpStatus.SC_CONFLICT) {
538 continue;
539 }
540 handleStatus(response);
541 } finally {
542 EntityUtils.consumeQuietly(response.getEntity());
543 }
544 } catch (IOException e) {
545 LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e);
546 return;
547 }
548 }
549 for (index--; index >= 0; index--) {
550 try (CloseableHttpResponse response =
551 client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))), context)) {
552 try {
553 handleStatus(response);
554 } finally {
555 EntityUtils.consumeQuietly(response.getEntity());
556 }
557 } catch (IOException e) {
558 LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e);
559 return;
560 }
561 }
562 }
563
564 private <T extends HttpEntityEnclosingRequest> T entity(T request, HttpEntity entity) {
565 request.setEntity(entity);
566 return request;
567 }
568
569 private boolean isPayloadPresent(HttpUriRequest request) {
570 if (request instanceof HttpEntityEnclosingRequest) {
571 HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
572 return entity != null && entity.getContentLength() != 0;
573 }
574 return false;
575 }
576
577 private <T extends HttpUriRequest> T commonHeaders(T request) {
578 request.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store");
579 request.setHeader(HttpHeaders.PRAGMA, "no-cache");
580
581 if (state.isExpectContinue() && isPayloadPresent(request)) {
582 request.setHeader(HttpHeaders.EXPECT, "100-continue");
583 }
584
585 for (Map.Entry<?, ?> entry : headers.entrySet()) {
586 if (!(entry.getKey() instanceof String)) {
587 continue;
588 }
589 if (entry.getValue() instanceof String) {
590 request.setHeader(entry.getKey().toString(), entry.getValue().toString());
591 } else {
592 request.removeHeaders(entry.getKey().toString());
593 }
594 }
595
596 if (!state.isExpectContinue()) {
597 request.removeHeaders(HttpHeaders.EXPECT);
598 }
599
600 return request;
601 }
602
603 @SuppressWarnings("checkstyle:magicnumber")
604 private <T extends HttpUriRequest> T resume(T request, GetTask task) {
605 long resumeOffset = task.getResumeOffset();
606 if (resumeOffset > 0L && task.getDataFile() != null) {
607 request.setHeader(HttpHeaders.RANGE, "bytes=" + resumeOffset + '-');
608 request.setHeader(
609 HttpHeaders.IF_UNMODIFIED_SINCE,
610 DateUtils.formatDate(new Date(task.getDataFile().lastModified() - 60L * 1000L)));
611 request.setHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
612 }
613 return request;
614 }
615
616 @SuppressWarnings("checkstyle:magicnumber")
617 private void handleStatus(CloseableHttpResponse response) throws HttpResponseException {
618 int status = response.getStatusLine().getStatusCode();
619 if (status >= 300) {
620 throw new HttpResponseException(status, response.getStatusLine().getReasonPhrase() + " (" + status + ")");
621 }
622 }
623
624 @Override
625 protected void implClose() {
626 try {
627 client.close();
628 } catch (IOException e) {
629 throw new UncheckedIOException(e);
630 }
631 AuthenticationContext.close(repoAuthContext);
632 AuthenticationContext.close(proxyAuthContext);
633 state.close();
634 }
635
636 private class EntityGetter {
637
638 private final GetTask task;
639
640 EntityGetter(GetTask task) {
641 this.task = task;
642 }
643
644 public void handle(CloseableHttpResponse response) throws IOException, TransferCancelledException {
645 HttpEntity entity = response.getEntity();
646 if (entity == null) {
647 entity = new ByteArrayEntity(new byte[0]);
648 }
649
650 long offset = 0L, length = entity.getContentLength();
651 Header rangeHeader = response.getFirstHeader(HttpHeaders.CONTENT_RANGE);
652 String range = rangeHeader != null ? rangeHeader.getValue() : null;
653 if (range != null) {
654 Matcher m = CONTENT_RANGE_PATTERN.matcher(range);
655 if (!m.matches()) {
656 throw new IOException("Invalid Content-Range header for partial download: " + range);
657 }
658 offset = Long.parseLong(m.group(1));
659 length = Long.parseLong(m.group(2)) + 1L;
660 if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) {
661 throw new IOException("Invalid Content-Range header for partial download from offset "
662 + task.getResumeOffset() + ": " + range);
663 }
664 }
665
666 final boolean resume = offset > 0L;
667 final File dataFile = task.getDataFile();
668 if (dataFile == null) {
669 try (InputStream is = entity.getContent()) {
670 utilGet(task, is, true, length, resume);
671 extractChecksums(response);
672 }
673 } else {
674 try (FileUtils.CollocatedTempFile tempFile = FileUtils.newTempFile(dataFile.toPath())) {
675 task.setDataFile(tempFile.getPath().toFile(), resume);
676 if (resume && Files.isRegularFile(dataFile.toPath())) {
677 try (InputStream inputStream = Files.newInputStream(dataFile.toPath())) {
678 Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
679 }
680 }
681 try (InputStream is = entity.getContent()) {
682 utilGet(task, is, true, length, resume);
683 }
684 tempFile.move();
685 } finally {
686 task.setDataFile(dataFile);
687 }
688 }
689 if (task.getDataFile() != null) {
690 Header lastModifiedHeader =
691 response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
692 if (lastModifiedHeader != null) {
693 Date lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
694 if (lastModified != null) {
695 task.getDataFile().setLastModified(lastModified.getTime());
696 }
697 }
698 }
699 extractChecksums(response);
700 }
701
702 private void extractChecksums(CloseableHttpResponse response) {
703 for (Map.Entry<String, ChecksumExtractor> extractorEntry : checksumExtractors.entrySet()) {
704 Map<String, String> checksums = extractorEntry.getValue().extractChecksums(response);
705 if (checksums != null) {
706 checksums.forEach(task::setChecksum);
707 return;
708 }
709 }
710 }
711 }
712
713 private class PutTaskEntity extends AbstractHttpEntity {
714
715 private final PutTask task;
716
717 PutTaskEntity(PutTask task) {
718 this.task = task;
719 }
720
721 @Override
722 public boolean isRepeatable() {
723 return true;
724 }
725
726 @Override
727 public boolean isStreaming() {
728 return false;
729 }
730
731 @Override
732 public long getContentLength() {
733 return task.getDataLength();
734 }
735
736 @Override
737 public InputStream getContent() throws IOException {
738 return task.newInputStream();
739 }
740
741 @Override
742 public void writeTo(OutputStream os) throws IOException {
743 try {
744 utilPut(task, os, false);
745 } catch (TransferCancelledException e) {
746 throw (IOException) new InterruptedIOException().initCause(e);
747 }
748 }
749 }
750
751 private static class ResolverServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy {
752 private final int retryCount;
753
754 private final long retryInterval;
755
756 private final long retryIntervalMax;
757
758 private final Set<Integer> serviceUnavailableHttpCodes;
759
760
761
762
763
764
765 private static final ThreadLocal<Long> RETRY_INTERVAL_HOLDER = new ThreadLocal<>();
766
767 private ResolverServiceUnavailableRetryStrategy(
768 int retryCount, long retryInterval, long retryIntervalMax, Set<Integer> serviceUnavailableHttpCodes) {
769 if (retryCount < 0) {
770 throw new IllegalArgumentException("retryCount must be >= 0");
771 }
772 if (retryInterval < 0L) {
773 throw new IllegalArgumentException("retryInterval must be >= 0");
774 }
775 if (retryIntervalMax < 0L) {
776 throw new IllegalArgumentException("retryIntervalMax must be >= 0");
777 }
778 this.retryCount = retryCount;
779 this.retryInterval = retryInterval;
780 this.retryIntervalMax = retryIntervalMax;
781 this.serviceUnavailableHttpCodes = requireNonNull(serviceUnavailableHttpCodes);
782 }
783
784 @Override
785 public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
786 final boolean retry = executionCount <= retryCount
787 && (serviceUnavailableHttpCodes.contains(
788 response.getStatusLine().getStatusCode()));
789 if (retry) {
790 Long retryInterval = retryInterval(response, executionCount, context);
791 if (retryInterval != null) {
792 RETRY_INTERVAL_HOLDER.set(retryInterval);
793 return true;
794 }
795 }
796 RETRY_INTERVAL_HOLDER.remove();
797 return false;
798 }
799
800
801
802
803
804
805
806
807 private Long retryInterval(HttpResponse httpResponse, int executionCount, HttpContext httpContext) {
808 Long result = null;
809 Header header = httpResponse.getFirstHeader(HttpHeaders.RETRY_AFTER);
810 if (header != null && header.getValue() != null) {
811 String headerValue = header.getValue();
812 if (headerValue.contains(":")) {
813 Date when = DateUtils.parseDate(headerValue);
814 if (when != null) {
815 result = Math.max(when.getTime() - System.currentTimeMillis(), 0L);
816 }
817 } else {
818 try {
819 result = Long.parseLong(headerValue) * 1000L;
820 } catch (NumberFormatException e) {
821
822 }
823 }
824 }
825 if (result == null) {
826 result = executionCount * this.retryInterval;
827 }
828 if (result > retryIntervalMax) {
829 return null;
830 }
831 return result;
832 }
833
834 @Override
835 public long getRetryInterval() {
836 Long ri = RETRY_INTERVAL_HOLDER.get();
837 if (ri == null) {
838 return 0L;
839 }
840 RETRY_INTERVAL_HOLDER.remove();
841 return ri;
842 }
843 }
844 }