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