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