1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.transport.jetty;
20
21 import javax.net.ssl.SSLContext;
22 import javax.net.ssl.X509TrustManager;
23
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.nio.file.Files;
29 import java.nio.file.Path;
30 import java.nio.file.StandardCopyOption;
31 import java.security.cert.X509Certificate;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.Map;
35 import java.util.concurrent.ExecutionException;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.atomic.AtomicBoolean;
38 import java.util.concurrent.atomic.AtomicReference;
39 import java.util.function.Function;
40 import java.util.regex.Matcher;
41
42 import org.eclipse.aether.ConfigurationProperties;
43 import org.eclipse.aether.RepositorySystemSession;
44 import org.eclipse.aether.repository.AuthenticationContext;
45 import org.eclipse.aether.repository.RemoteRepository;
46 import org.eclipse.aether.spi.connector.transport.AbstractTransporter;
47 import org.eclipse.aether.spi.connector.transport.GetTask;
48 import org.eclipse.aether.spi.connector.transport.PeekTask;
49 import org.eclipse.aether.spi.connector.transport.PutTask;
50 import org.eclipse.aether.spi.connector.transport.TransportTask;
51 import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor;
52 import org.eclipse.aether.spi.connector.transport.http.HttpTransporter;
53 import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException;
54 import org.eclipse.aether.spi.io.PathProcessor;
55 import org.eclipse.aether.transfer.NoTransporterException;
56 import org.eclipse.aether.transfer.TransferCancelledException;
57 import org.eclipse.aether.util.ConfigUtils;
58 import org.eclipse.aether.util.FileUtils;
59 import org.eclipse.jetty.client.HttpClient;
60 import org.eclipse.jetty.client.HttpProxy;
61 import org.eclipse.jetty.client.api.Authentication;
62 import org.eclipse.jetty.client.api.Request;
63 import org.eclipse.jetty.client.api.Response;
64 import org.eclipse.jetty.client.dynamic.HttpClientTransportDynamic;
65 import org.eclipse.jetty.client.http.HttpClientConnectionFactory;
66 import org.eclipse.jetty.client.util.BasicAuthentication;
67 import org.eclipse.jetty.client.util.InputStreamResponseListener;
68 import org.eclipse.jetty.http.HttpHeader;
69 import org.eclipse.jetty.http2.client.HTTP2Client;
70 import org.eclipse.jetty.http2.client.http.ClientConnectionFactoryOverHTTP2;
71 import org.eclipse.jetty.io.ClientConnector;
72 import org.eclipse.jetty.util.ssl.SslContextFactory;
73
74 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.ACCEPT_ENCODING;
75 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_LENGTH;
76 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE;
77 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE_PATTERN;
78 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.IF_UNMODIFIED_SINCE;
79 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.LAST_MODIFIED;
80 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.MULTIPLE_CHOICES;
81 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.NOT_FOUND;
82 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.PRECONDITION_FAILED;
83 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.RANGE;
84 import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.USER_AGENT;
85
86
87
88
89
90
91 final class JettyTransporter extends AbstractTransporter implements HttpTransporter {
92 private static final long MODIFICATION_THRESHOLD = 60L * 1000L;
93
94 private final RepositorySystemSession session;
95
96 private final RemoteRepository repository;
97
98 private final ChecksumExtractor checksumExtractor;
99
100 private final PathProcessor pathProcessor;
101
102 private final URI baseUri;
103
104 private final HttpClient client;
105
106 private final int requestTimeout;
107
108 private final Map<String, String> headers;
109
110 private final boolean preemptiveAuth;
111
112 private final boolean preemptivePutAuth;
113
114 private final boolean insecure;
115
116 private final AtomicReference<BasicAuthentication.BasicResult> basicServerAuthenticationResult;
117
118 private final AtomicReference<BasicAuthentication.BasicResult> basicProxyAuthenticationResult;
119
120 JettyTransporter(
121 RepositorySystemSession session,
122 RemoteRepository repository,
123 ChecksumExtractor checksumExtractor,
124 PathProcessor pathProcessor)
125 throws NoTransporterException {
126 this.session = session;
127 this.repository = repository;
128 this.checksumExtractor = checksumExtractor;
129 this.pathProcessor = pathProcessor;
130 try {
131 URI uri = new URI(repository.getUrl()).parseServerAuthority();
132 if (uri.isOpaque()) {
133 throw new URISyntaxException(repository.getUrl(), "URL must not be opaque");
134 }
135 if (uri.getRawFragment() != null || uri.getRawQuery() != null) {
136 throw new URISyntaxException(repository.getUrl(), "URL must not have fragment or query");
137 }
138 String path = uri.getPath();
139 if (path == null) {
140 path = "/";
141 }
142 if (!path.startsWith("/")) {
143 path = "/" + path;
144 }
145 if (!path.endsWith("/")) {
146 path = path + "/";
147 }
148 this.baseUri = URI.create(uri.getScheme() + "://" + uri.getRawAuthority() + path);
149 } catch (URISyntaxException e) {
150 throw new NoTransporterException(repository, e.getMessage(), e);
151 }
152
153 HashMap<String, String> headers = new HashMap<>();
154 String userAgent = ConfigUtils.getString(
155 session, ConfigurationProperties.DEFAULT_USER_AGENT, ConfigurationProperties.USER_AGENT);
156 if (userAgent != null) {
157 headers.put(USER_AGENT, userAgent);
158 }
159 @SuppressWarnings("unchecked")
160 Map<Object, Object> configuredHeaders = (Map<Object, Object>) ConfigUtils.getMap(
161 session,
162 Collections.emptyMap(),
163 ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(),
164 ConfigurationProperties.HTTP_HEADERS);
165 if (configuredHeaders != null) {
166 configuredHeaders.forEach((k, v) -> headers.put(String.valueOf(k), v != null ? String.valueOf(v) : null));
167 }
168
169 this.headers = headers;
170
171 this.requestTimeout = ConfigUtils.getInteger(
172 session,
173 ConfigurationProperties.DEFAULT_REQUEST_TIMEOUT,
174 ConfigurationProperties.REQUEST_TIMEOUT + "." + repository.getId(),
175 ConfigurationProperties.REQUEST_TIMEOUT);
176 this.preemptiveAuth = ConfigUtils.getBoolean(
177 session,
178 ConfigurationProperties.DEFAULT_HTTP_PREEMPTIVE_AUTH,
179 ConfigurationProperties.HTTP_PREEMPTIVE_AUTH + "." + repository.getId(),
180 ConfigurationProperties.HTTP_PREEMPTIVE_AUTH);
181 this.preemptivePutAuth = ConfigUtils.getBoolean(
182 session,
183 ConfigurationProperties.DEFAULT_HTTP_PREEMPTIVE_PUT_AUTH,
184 ConfigurationProperties.HTTP_PREEMPTIVE_PUT_AUTH + "." + repository.getId(),
185 ConfigurationProperties.HTTP_PREEMPTIVE_PUT_AUTH);
186 final String httpsSecurityMode = ConfigUtils.getString(
187 session,
188 ConfigurationProperties.HTTPS_SECURITY_MODE_DEFAULT,
189 ConfigurationProperties.HTTPS_SECURITY_MODE + "." + repository.getId(),
190 ConfigurationProperties.HTTPS_SECURITY_MODE);
191
192 if (!ConfigurationProperties.HTTPS_SECURITY_MODE_DEFAULT.equals(httpsSecurityMode)
193 && !ConfigurationProperties.HTTPS_SECURITY_MODE_INSECURE.equals(httpsSecurityMode)) {
194 throw new IllegalArgumentException("Unsupported '" + httpsSecurityMode + "' HTTPS security mode.");
195 }
196 this.insecure = ConfigurationProperties.HTTPS_SECURITY_MODE_INSECURE.equals(httpsSecurityMode);
197
198 this.basicServerAuthenticationResult = new AtomicReference<>(null);
199 this.basicProxyAuthenticationResult = new AtomicReference<>(null);
200 try {
201 this.client = createClient();
202 } catch (Exception e) {
203 throw new NoTransporterException(repository, e);
204 }
205 }
206
207 private void mayApplyPreemptiveAuth(Request request) {
208 if (basicServerAuthenticationResult.get() != null) {
209 basicServerAuthenticationResult.get().apply(request);
210 }
211 if (basicProxyAuthenticationResult.get() != null) {
212 basicProxyAuthenticationResult.get().apply(request);
213 }
214 }
215
216 private URI resolve(TransportTask task) {
217 return baseUri.resolve(task.getLocation());
218 }
219
220 @Override
221 public int classify(Throwable error) {
222 if (error instanceof HttpTransporterException
223 && ((HttpTransporterException) error).getStatusCode() == NOT_FOUND) {
224 return ERROR_NOT_FOUND;
225 }
226 return ERROR_OTHER;
227 }
228
229 @Override
230 protected void implPeek(PeekTask task) throws Exception {
231 Request request = client.newRequest(resolve(task))
232 .timeout(requestTimeout, TimeUnit.MILLISECONDS)
233 .method("HEAD");
234 request.headers(m -> headers.forEach(m::add));
235 if (preemptiveAuth) {
236 mayApplyPreemptiveAuth(request);
237 }
238 Response response = request.send();
239 if (response.getStatus() >= MULTIPLE_CHOICES) {
240 throw new HttpTransporterException(response.getStatus());
241 }
242 }
243
244 @Override
245 protected void implGet(GetTask task) throws Exception {
246 boolean resume = task.getResumeOffset() > 0L && task.getDataPath() != null;
247 Response response;
248 InputStreamResponseListener listener;
249
250 while (true) {
251 Request request = client.newRequest(resolve(task))
252 .timeout(requestTimeout, TimeUnit.MILLISECONDS)
253 .method("GET");
254 request.headers(m -> headers.forEach(m::add));
255 if (preemptiveAuth) {
256 mayApplyPreemptiveAuth(request);
257 }
258
259 if (resume) {
260 long resumeOffset = task.getResumeOffset();
261 long lastModified =
262 Files.getLastModifiedTime(task.getDataPath()).toMillis();
263 request.headers(h -> {
264 h.add(RANGE, "bytes=" + resumeOffset + '-');
265 h.addDateField(IF_UNMODIFIED_SINCE, lastModified - MODIFICATION_THRESHOLD);
266 h.remove(HttpHeader.ACCEPT_ENCODING);
267 h.add(ACCEPT_ENCODING, "identity");
268 });
269 }
270
271 listener = new InputStreamResponseListener();
272 request.send(listener);
273 try {
274 response = listener.get(requestTimeout, TimeUnit.MILLISECONDS);
275 } catch (ExecutionException e) {
276 Throwable t = e.getCause();
277 if (t instanceof Exception) {
278 throw (Exception) t;
279 } else {
280 throw new RuntimeException(t);
281 }
282 }
283 if (response.getStatus() >= MULTIPLE_CHOICES) {
284 if (resume && response.getStatus() == PRECONDITION_FAILED) {
285 resume = false;
286 continue;
287 }
288 throw new HttpTransporterException(response.getStatus());
289 }
290 break;
291 }
292
293 long offset = 0L, length = response.getHeaders().getLongField(CONTENT_LENGTH);
294 if (resume) {
295 String range = response.getHeaders().get(CONTENT_RANGE);
296 if (range != null) {
297 Matcher m = CONTENT_RANGE_PATTERN.matcher(range);
298 if (!m.matches()) {
299 throw new IOException("Invalid Content-Range header for partial download: " + range);
300 }
301 offset = Long.parseLong(m.group(1));
302 length = Long.parseLong(m.group(2)) + 1L;
303 if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) {
304 throw new IOException("Invalid Content-Range header for partial download from offset "
305 + task.getResumeOffset() + ": " + range);
306 }
307 }
308 }
309
310 final boolean downloadResumed = offset > 0L;
311 final Path dataFile = task.getDataPath();
312 if (dataFile == null) {
313 try (InputStream is = listener.getInputStream()) {
314 utilGet(task, is, true, length, downloadResumed);
315 }
316 } else {
317 try (FileUtils.CollocatedTempFile tempFile = FileUtils.newTempFile(dataFile)) {
318 task.setDataPath(tempFile.getPath(), downloadResumed);
319 if (downloadResumed && Files.isRegularFile(dataFile)) {
320 try (InputStream inputStream = Files.newInputStream(dataFile)) {
321 Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
322 }
323 }
324 try (InputStream is = listener.getInputStream()) {
325 utilGet(task, is, true, length, downloadResumed);
326 }
327 tempFile.move();
328 } finally {
329 task.setDataPath(dataFile);
330 }
331 }
332 if (task.getDataPath() != null && response.getHeaders().getDateField(LAST_MODIFIED) != -1) {
333 long lastModified =
334 response.getHeaders().getDateField(LAST_MODIFIED);
335 if (lastModified != -1) {
336 pathProcessor.setLastModified(task.getDataPath(), lastModified);
337 }
338 }
339 Map<String, String> checksums = checksumExtractor.extractChecksums(headerGetter(response));
340 if (checksums != null && !checksums.isEmpty()) {
341 checksums.forEach(task::setChecksum);
342 }
343 }
344
345 private static Function<String, String> headerGetter(Response response) {
346 return s -> response.getHeaders().get(s);
347 }
348
349 @Override
350 protected void implPut(PutTask task) throws Exception {
351 Request request = client.newRequest(resolve(task)).method("PUT").timeout(requestTimeout, TimeUnit.MILLISECONDS);
352 request.headers(m -> headers.forEach(m::add));
353 if (preemptiveAuth || preemptivePutAuth) {
354 mayApplyPreemptiveAuth(request);
355 }
356 request.body(new PutTaskRequestContent(task));
357 AtomicBoolean started = new AtomicBoolean(false);
358 Response response;
359 try {
360 response = request.onRequestCommit(r -> {
361 if (task.getDataLength() == 0) {
362 if (started.compareAndSet(false, true)) {
363 try {
364 task.getListener().transportStarted(0, task.getDataLength());
365 } catch (TransferCancelledException e) {
366 r.abort(e);
367 }
368 }
369 }
370 })
371 .onRequestContent((r, b) -> {
372 if (started.compareAndSet(false, true)) {
373 try {
374 task.getListener().transportStarted(0, task.getDataLength());
375 } catch (TransferCancelledException e) {
376 r.abort(e);
377 return;
378 }
379 }
380 try {
381 task.getListener().transportProgressed(b);
382 } catch (TransferCancelledException e) {
383 r.abort(e);
384 }
385 })
386 .send();
387 } catch (ExecutionException e) {
388 Throwable t = e.getCause();
389 if (t instanceof IOException) {
390 IOException ioex = (IOException) t;
391 if (ioex.getCause() instanceof TransferCancelledException) {
392 throw (TransferCancelledException) ioex.getCause();
393 } else {
394 throw ioex;
395 }
396 } else if (t instanceof Exception) {
397 throw (Exception) t;
398 } else {
399 throw new RuntimeException(t);
400 }
401 }
402 if (response.getStatus() >= MULTIPLE_CHOICES) {
403 throw new HttpTransporterException(response.getStatus());
404 }
405 }
406
407 @Override
408 protected void implClose() {
409 try {
410 this.client.stop();
411 } catch (Exception e) {
412 throw new RuntimeException(e);
413 }
414 }
415
416 @SuppressWarnings("checkstyle:methodlength")
417 private HttpClient createClient() throws Exception {
418 BasicAuthentication.BasicResult serverAuth = null;
419 BasicAuthentication.BasicResult proxyAuth = null;
420 SSLContext sslContext = null;
421 BasicAuthentication basicAuthentication = null;
422 try (AuthenticationContext repoAuthContext = AuthenticationContext.forRepository(session, repository)) {
423 if (repoAuthContext != null) {
424 sslContext = repoAuthContext.get(AuthenticationContext.SSL_CONTEXT, SSLContext.class);
425
426 String username = repoAuthContext.get(AuthenticationContext.USERNAME);
427 String password = repoAuthContext.get(AuthenticationContext.PASSWORD);
428
429 URI uri = URI.create(repository.getUrl());
430 basicAuthentication = new BasicAuthentication(uri, Authentication.ANY_REALM, username, password);
431 if (preemptiveAuth || preemptivePutAuth) {
432 serverAuth = new BasicAuthentication.BasicResult(uri, HttpHeader.AUTHORIZATION, username, password);
433 }
434 }
435 }
436
437 if (sslContext == null) {
438 if (insecure) {
439 sslContext = SSLContext.getInstance("TLS");
440 X509TrustManager tm = new X509TrustManager() {
441 @Override
442 public void checkClientTrusted(X509Certificate[] chain, String authType) {}
443
444 @Override
445 public void checkServerTrusted(X509Certificate[] chain, String authType) {}
446
447 @Override
448 public X509Certificate[] getAcceptedIssuers() {
449 return new X509Certificate[0];
450 }
451 };
452 sslContext.init(null, new X509TrustManager[] {tm}, null);
453 } else {
454 sslContext = SSLContext.getDefault();
455 }
456 }
457
458 int connectTimeout = ConfigUtils.getInteger(
459 session,
460 ConfigurationProperties.DEFAULT_CONNECT_TIMEOUT,
461 ConfigurationProperties.CONNECT_TIMEOUT + "." + repository.getId(),
462 ConfigurationProperties.CONNECT_TIMEOUT);
463
464 SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
465 sslContextFactory.setSslContext(sslContext);
466 if (insecure) {
467 sslContextFactory.setEndpointIdentificationAlgorithm(null);
468 sslContextFactory.setHostnameVerifier((name, context) -> true);
469 }
470
471 ClientConnector clientConnector = new ClientConnector();
472 clientConnector.setSslContextFactory(sslContextFactory);
473
474 HTTP2Client http2Client = new HTTP2Client(clientConnector);
475 ClientConnectionFactoryOverHTTP2.HTTP2 http2 = new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client);
476
477 HttpClientTransportDynamic transport;
478 if ("https".equalsIgnoreCase(repository.getProtocol())) {
479 transport = new HttpClientTransportDynamic(
480 clientConnector, http2, HttpClientConnectionFactory.HTTP11);
481 } else {
482 transport = new HttpClientTransportDynamic(
483 clientConnector, HttpClientConnectionFactory.HTTP11, http2);
484 }
485
486 HttpClient httpClient = new HttpClient(transport);
487 httpClient.setConnectTimeout(connectTimeout);
488 httpClient.setFollowRedirects(ConfigUtils.getBoolean(
489 session,
490 JettyTransporterConfigurationKeys.DEFAULT_FOLLOW_REDIRECTS,
491 JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_REDIRECTS));
492 httpClient.setMaxRedirects(ConfigUtils.getInteger(
493 session,
494 JettyTransporterConfigurationKeys.DEFAULT_MAX_REDIRECTS,
495 JettyTransporterConfigurationKeys.CONFIG_PROP_MAX_REDIRECTS));
496
497 httpClient.setUserAgentField(null);
498
499 if (basicAuthentication != null) {
500 httpClient.getAuthenticationStore().addAuthentication(basicAuthentication);
501 }
502
503 if (repository.getProxy() != null) {
504 HttpProxy proxy = new HttpProxy(
505 repository.getProxy().getHost(), repository.getProxy().getPort());
506
507 httpClient.getProxyConfiguration().addProxy(proxy);
508 try (AuthenticationContext proxyAuthContext = AuthenticationContext.forProxy(session, repository)) {
509 if (proxyAuthContext != null) {
510 String username = proxyAuthContext.get(AuthenticationContext.USERNAME);
511 String password = proxyAuthContext.get(AuthenticationContext.PASSWORD);
512
513 BasicAuthentication proxyAuthentication =
514 new BasicAuthentication(proxy.getURI(), Authentication.ANY_REALM, username, password);
515
516 httpClient.getAuthenticationStore().addAuthentication(proxyAuthentication);
517 if (preemptiveAuth || preemptivePutAuth) {
518 proxyAuth = new BasicAuthentication.BasicResult(
519 proxy.getURI(), HttpHeader.PROXY_AUTHORIZATION, username, password);
520 }
521 }
522 }
523 }
524 if (serverAuth != null) {
525 this.basicServerAuthenticationResult.set(serverAuth);
526 }
527 if (proxyAuth != null) {
528 this.basicProxyAuthenticationResult.set(proxyAuth);
529 }
530
531 httpClient.start();
532 return httpClient;
533 }
534 }