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.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.HashMap;
33  import java.util.Map;
34  import java.util.concurrent.ExecutionException;
35  import java.util.concurrent.TimeUnit;
36  import java.util.concurrent.atomic.AtomicBoolean;
37  import java.util.concurrent.atomic.AtomicReference;
38  import java.util.function.Function;
39  import java.util.regex.Matcher;
40  
41  import org.eclipse.aether.ConfigurationProperties;
42  import org.eclipse.aether.RepositorySystemSession;
43  import org.eclipse.aether.repository.AuthenticationContext;
44  import org.eclipse.aether.repository.RemoteRepository;
45  import org.eclipse.aether.spi.connector.transport.AbstractTransporter;
46  import org.eclipse.aether.spi.connector.transport.GetTask;
47  import org.eclipse.aether.spi.connector.transport.PeekTask;
48  import org.eclipse.aether.spi.connector.transport.PutTask;
49  import org.eclipse.aether.spi.connector.transport.TransportTask;
50  import org.eclipse.aether.spi.connector.transport.http.ChecksumExtractor;
51  import org.eclipse.aether.spi.connector.transport.http.HttpTransporter;
52  import org.eclipse.aether.spi.connector.transport.http.HttpTransporterException;
53  import org.eclipse.aether.spi.io.PathProcessor;
54  import org.eclipse.aether.transfer.NoTransporterException;
55  import org.eclipse.aether.transfer.TransferCancelledException;
56  import org.eclipse.aether.util.ConfigUtils;
57  import org.eclipse.aether.util.connector.transport.http.HttpTransporterUtils;
58  import org.eclipse.jetty.client.Authentication;
59  import org.eclipse.jetty.client.BasicAuthentication;
60  import org.eclipse.jetty.client.HttpClient;
61  import org.eclipse.jetty.client.HttpProxy;
62  import org.eclipse.jetty.client.InputStreamResponseListener;
63  import org.eclipse.jetty.client.Request;
64  import org.eclipse.jetty.client.Response;
65  import org.eclipse.jetty.client.transport.HttpClientConnectionFactory;
66  import org.eclipse.jetty.client.transport.HttpClientTransportDynamic;
67  import org.eclipse.jetty.http.HttpHeader;
68  import org.eclipse.jetty.http2.client.HTTP2Client;
69  import org.eclipse.jetty.http2.client.transport.ClientConnectionFactoryOverHTTP2;
70  import org.eclipse.jetty.io.ClientConnector;
71  import org.eclipse.jetty.util.ssl.SslContextFactory;
72  
73  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.ACCEPT_ENCODING;
74  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_LENGTH;
75  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE;
76  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.CONTENT_RANGE_PATTERN;
77  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.IF_UNMODIFIED_SINCE;
78  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.LAST_MODIFIED;
79  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.MULTIPLE_CHOICES;
80  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.PRECONDITION_FAILED;
81  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.RANGE;
82  import static org.eclipse.aether.spi.connector.transport.http.HttpConstants.USER_AGENT;
83  
84  /**
85   * A transporter for HTTP/HTTPS.
86   *
87   * @since 2.0.0
88   */
89  final class JettyTransporter extends AbstractTransporter implements HttpTransporter {
90      private static final long MODIFICATION_THRESHOLD = 60L * 1000L;
91  
92      private final RepositorySystemSession session;
93  
94      private final RemoteRepository repository;
95  
96      private final ChecksumExtractor checksumExtractor;
97  
98      private final PathProcessor pathProcessor;
99  
100     private final URI baseUri;
101 
102     private final HttpClient client;
103 
104     private final int connectTimeout;
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             this.baseUri = HttpTransporterUtils.getBaseUri(repository);
132         } catch (URISyntaxException e) {
133             throw new NoTransporterException(repository, e.getMessage(), e);
134         }
135 
136         HashMap<String, String> headers = new HashMap<>();
137         String userAgent = HttpTransporterUtils.getUserAgent(session, repository);
138         if (userAgent != null) {
139             headers.put(USER_AGENT, userAgent);
140         }
141         Map<String, String> configuredHeaders = HttpTransporterUtils.getHttpHeaders(session, repository);
142         if (configuredHeaders != null) {
143             headers.putAll(configuredHeaders);
144         }
145 
146         this.headers = headers;
147 
148         this.connectTimeout = HttpTransporterUtils.getHttpRequestTimeout(session, repository);
149         this.requestTimeout = HttpTransporterUtils.getHttpRequestTimeout(session, repository);
150         this.preemptiveAuth = HttpTransporterUtils.isHttpPreemptiveAuth(session, repository);
151         this.preemptivePutAuth = HttpTransporterUtils.isHttpPreemptivePutAuth(session, repository);
152         final String httpsSecurityMode = HttpTransporterUtils.getHttpsSecurityMode(session, repository);
153         this.insecure = ConfigurationProperties.HTTPS_SECURITY_MODE_INSECURE.equals(httpsSecurityMode);
154 
155         this.basicServerAuthenticationResult = new AtomicReference<>(null);
156         this.basicProxyAuthenticationResult = new AtomicReference<>(null);
157         this.client = createClient();
158     }
159 
160     private void mayApplyPreemptiveAuth(Request request) {
161         if (basicServerAuthenticationResult.get() != null) {
162             basicServerAuthenticationResult.get().apply(request);
163         }
164         if (basicProxyAuthenticationResult.get() != null) {
165             basicProxyAuthenticationResult.get().apply(request);
166         }
167     }
168 
169     private URI resolve(TransportTask task) {
170         return baseUri.resolve(task.getLocation());
171     }
172 
173     @Override
174     protected void implPeek(PeekTask task) throws Exception {
175         Request request = client.newRequest(resolve(task)).method("HEAD");
176         request.headers(m -> headers.forEach(m::add));
177         if (preemptiveAuth) {
178             mayApplyPreemptiveAuth(request);
179         }
180         Response response = request.send();
181         if (response.getStatus() >= MULTIPLE_CHOICES) {
182             throw new HttpTransporterException(response.getStatus());
183         }
184     }
185 
186     @Override
187     protected void implGet(GetTask task) throws Exception {
188         boolean resume = task.getResumeOffset() > 0L && task.getDataPath() != null;
189         Response response;
190         InputStreamResponseListener listener;
191 
192         while (true) {
193             Request request = client.newRequest(resolve(task)).method("GET");
194             request.headers(m -> headers.forEach(m::add));
195             if (preemptiveAuth) {
196                 mayApplyPreemptiveAuth(request);
197             }
198             JettyRFC9457Reporter.INSTANCE.prepareRequest(request);
199             if (resume) {
200                 long resumeOffset = task.getResumeOffset();
201                 long lastModified =
202                         Files.getLastModifiedTime(task.getDataPath()).toMillis();
203                 request.headers(h -> {
204                     h.add(RANGE, "bytes=" + resumeOffset + '-');
205                     h.addDateField(IF_UNMODIFIED_SINCE, lastModified - MODIFICATION_THRESHOLD);
206                     h.remove(HttpHeader.ACCEPT_ENCODING);
207                     h.add(ACCEPT_ENCODING, "identity");
208                 });
209             }
210 
211             listener = new InputStreamResponseListener();
212             request.send(listener);
213             try {
214                 response = listener.get(requestTimeout, TimeUnit.MILLISECONDS);
215             } catch (ExecutionException e) {
216                 Throwable t = e.getCause();
217                 if (t instanceof Exception) {
218                     throw (Exception) t;
219                 } else {
220                     throw new RuntimeException(t);
221                 }
222             }
223             if (response.getStatus() >= MULTIPLE_CHOICES) {
224                 if (resume && response.getStatus() == PRECONDITION_FAILED) {
225                     resume = false;
226                     continue;
227                 }
228                 JettyRFC9457Reporter.INSTANCE.generateException(listener, (statusCode, reasonPhrase) -> {
229                     throw new HttpTransporterException(statusCode);
230                 });
231             }
232             break;
233         }
234 
235         long offset = 0L, length = response.getHeaders().getLongField(CONTENT_LENGTH);
236         if (resume) {
237             String range = response.getHeaders().get(CONTENT_RANGE);
238             if (range != null) {
239                 Matcher m = CONTENT_RANGE_PATTERN.matcher(range);
240                 if (!m.matches()) {
241                     throw new IOException("Invalid Content-Range header for partial download: " + range);
242                 }
243                 offset = Long.parseLong(m.group(1));
244                 length = Long.parseLong(m.group(2)) + 1L;
245                 if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) {
246                     throw new IOException("Invalid Content-Range header for partial download from offset "
247                             + task.getResumeOffset() + ": " + range);
248                 }
249             }
250         }
251 
252         final boolean downloadResumed = offset > 0L;
253         final Path dataFile = task.getDataPath();
254         if (dataFile == null) {
255             try (InputStream is = listener.getInputStream()) {
256                 utilGet(task, is, true, length, downloadResumed);
257             }
258         } else {
259             try (PathProcessor.CollocatedTempFile tempFile = pathProcessor.newTempFile(dataFile)) {
260                 task.setDataPath(tempFile.getPath(), downloadResumed);
261                 if (downloadResumed && Files.isRegularFile(dataFile)) {
262                     try (InputStream inputStream = Files.newInputStream(dataFile)) {
263                         Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
264                     }
265                 }
266                 try (InputStream is = listener.getInputStream()) {
267                     utilGet(task, is, true, length, downloadResumed);
268                 }
269                 tempFile.move();
270             } finally {
271                 task.setDataPath(dataFile);
272             }
273         }
274         if (task.getDataPath() != null && response.getHeaders().getDateField(LAST_MODIFIED) != -1) {
275             long lastModified =
276                     response.getHeaders().getDateField(LAST_MODIFIED); // note: Wagon also does first not last
277             if (lastModified != -1) {
278                 pathProcessor.setLastModified(task.getDataPath(), lastModified);
279             }
280         }
281         Map<String, String> checksums = checksumExtractor.extractChecksums(headerGetter(response));
282         if (checksums != null && !checksums.isEmpty()) {
283             checksums.forEach(task::setChecksum);
284         }
285     }
286 
287     private static Function<String, String> headerGetter(Response response) {
288         return s -> response.getHeaders().get(s);
289     }
290 
291     @Override
292     protected void implPut(PutTask task) throws Exception {
293         Request request = client.newRequest(resolve(task)).method("PUT");
294         request.headers(m -> headers.forEach(m::add));
295         JettyRFC9457Reporter.INSTANCE.prepareRequest(request);
296         if (preemptiveAuth || preemptivePutAuth) {
297             mayApplyPreemptiveAuth(request);
298         }
299         request.body(PutTaskRequestContent.from(task));
300         AtomicBoolean started = new AtomicBoolean(false);
301         Response response;
302         InputStreamResponseListener listener = new InputStreamResponseListener();
303         try {
304             request.onRequestCommit(r -> {
305                         if (task.getDataLength() == 0) {
306                             if (started.compareAndSet(false, true)) {
307                                 try {
308                                     task.getListener().transportStarted(0, task.getDataLength());
309                                 } catch (TransferCancelledException e) {
310                                     r.abort(e);
311                                 }
312                             }
313                         }
314                     })
315                     .onRequestContent((r, b) -> {
316                         if (started.compareAndSet(false, true)) {
317                             try {
318                                 task.getListener().transportStarted(0, task.getDataLength());
319                             } catch (TransferCancelledException e) {
320                                 r.abort(e);
321                                 return;
322                             }
323                         }
324                         try {
325                             task.getListener().transportProgressed(b);
326                         } catch (TransferCancelledException e) {
327                             r.abort(e);
328                         }
329                     })
330                     .send(listener);
331             response = listener.get(requestTimeout, TimeUnit.MILLISECONDS);
332         } catch (ExecutionException e) {
333             Throwable t = e.getCause();
334             if (t instanceof IOException ioex) {
335                 if (ioex.getCause() instanceof TransferCancelledException) {
336                     throw (TransferCancelledException) ioex.getCause();
337                 } else {
338                     throw ioex;
339                 }
340             } else if (t instanceof Exception) {
341                 throw (Exception) t;
342             } else {
343                 throw new RuntimeException(t);
344             }
345         }
346 
347         if (response.getStatus() >= MULTIPLE_CHOICES) {
348             JettyRFC9457Reporter.INSTANCE.generateException(listener, (statusCode, reasonPhrase) -> {
349                 throw new HttpTransporterException(statusCode);
350             });
351             throw new HttpTransporterException(response.getStatus());
352         }
353     }
354 
355     @Override
356     protected void implClose() {
357         try {
358             this.client.stop();
359         } catch (Exception e) {
360             throw new RuntimeException(e);
361         }
362     }
363 
364     @SuppressWarnings("checkstyle:methodlength")
365     private HttpClient createClient() throws RuntimeException {
366         BasicAuthentication.BasicResult serverAuth = null;
367         BasicAuthentication.BasicResult proxyAuth = null;
368         SSLContext sslContext = null;
369         BasicAuthentication basicAuthentication = null;
370         try (AuthenticationContext repoAuthContext = AuthenticationContext.forRepository(session, repository)) {
371             if (repoAuthContext != null) {
372                 sslContext = repoAuthContext.get(AuthenticationContext.SSL_CONTEXT, SSLContext.class);
373 
374                 String username = repoAuthContext.get(AuthenticationContext.USERNAME);
375                 String password = repoAuthContext.get(AuthenticationContext.PASSWORD);
376 
377                 URI uri = URI.create(repository.getUrl());
378                 basicAuthentication = new BasicAuthentication(uri, Authentication.ANY_REALM, username, password);
379                 if (preemptiveAuth || preemptivePutAuth) {
380                     serverAuth = new BasicAuthentication.BasicResult(uri, HttpHeader.AUTHORIZATION, username, password);
381                 }
382             }
383         }
384 
385         if (sslContext == null) {
386             try {
387                 if (insecure) {
388                     sslContext = SSLContext.getInstance("TLS");
389                     X509TrustManager tm = new X509TrustManager() {
390                         @Override
391                         public void checkClientTrusted(X509Certificate[] chain, String authType) {}
392 
393                         @Override
394                         public void checkServerTrusted(X509Certificate[] chain, String authType) {}
395 
396                         @Override
397                         public X509Certificate[] getAcceptedIssuers() {
398                             return new X509Certificate[0];
399                         }
400                     };
401                     sslContext.init(null, new X509TrustManager[] {tm}, null);
402                 } else {
403                     sslContext = SSLContext.getDefault();
404                 }
405             } catch (Exception e) {
406                 if (e instanceof RuntimeException) {
407                     throw (RuntimeException) e;
408                 } else {
409                     throw new IllegalStateException("SSL Context setup failure", e);
410                 }
411             }
412         }
413 
414         SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
415         sslContextFactory.setSslContext(sslContext);
416         if (insecure) {
417             sslContextFactory.setEndpointIdentificationAlgorithm(null);
418             sslContextFactory.setHostnameVerifier((name, context) -> true);
419         }
420 
421         ClientConnector clientConnector = new ClientConnector();
422         clientConnector.setSslContextFactory(sslContextFactory);
423 
424         HTTP2Client http2Client = new HTTP2Client(clientConnector);
425         ClientConnectionFactoryOverHTTP2.HTTP2 http2 = new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client);
426 
427         HttpClientTransportDynamic transport;
428         if ("https".equalsIgnoreCase(repository.getProtocol())) {
429             transport = new HttpClientTransportDynamic(
430                     clientConnector, http2, HttpClientConnectionFactory.HTTP11); // HTTPS, prefer H2
431         } else {
432             transport = new HttpClientTransportDynamic(
433                     clientConnector, HttpClientConnectionFactory.HTTP11, http2); // plaintext HTTP, H2 cannot be used
434         }
435 
436         HttpClient httpClient = new HttpClient(transport);
437         httpClient.setConnectTimeout(connectTimeout);
438         httpClient.setIdleTimeout(requestTimeout);
439         httpClient.setFollowRedirects(ConfigUtils.getBoolean(
440                 session,
441                 JettyTransporterConfigurationKeys.DEFAULT_FOLLOW_REDIRECTS,
442                 JettyTransporterConfigurationKeys.CONFIG_PROP_FOLLOW_REDIRECTS));
443         httpClient.setMaxRedirects(ConfigUtils.getInteger(
444                 session,
445                 JettyTransporterConfigurationKeys.DEFAULT_MAX_REDIRECTS,
446                 JettyTransporterConfigurationKeys.CONFIG_PROP_MAX_REDIRECTS));
447 
448         httpClient.setUserAgentField(null); // we manage it
449 
450         if (basicAuthentication != null) {
451             httpClient.getAuthenticationStore().addAuthentication(basicAuthentication);
452         }
453 
454         if (repository.getProxy() != null) {
455             HttpProxy proxy = new HttpProxy(
456                     repository.getProxy().getHost(), repository.getProxy().getPort());
457 
458             httpClient.getProxyConfiguration().addProxy(proxy);
459             try (AuthenticationContext proxyAuthContext = AuthenticationContext.forProxy(session, repository)) {
460                 if (proxyAuthContext != null) {
461                     String username = proxyAuthContext.get(AuthenticationContext.USERNAME);
462                     String password = proxyAuthContext.get(AuthenticationContext.PASSWORD);
463 
464                     BasicAuthentication proxyAuthentication =
465                             new BasicAuthentication(proxy.getURI(), Authentication.ANY_REALM, username, password);
466 
467                     httpClient.getAuthenticationStore().addAuthentication(proxyAuthentication);
468                     if (preemptiveAuth || preemptivePutAuth) {
469                         proxyAuth = new BasicAuthentication.BasicResult(
470                                 proxy.getURI(), HttpHeader.PROXY_AUTHORIZATION, username, password);
471                     }
472                 }
473             }
474         }
475         if (serverAuth != null) {
476             this.basicServerAuthenticationResult.set(serverAuth);
477         }
478         if (proxyAuth != null) {
479             this.basicProxyAuthenticationResult.set(proxyAuth);
480         }
481 
482         try {
483             httpClient.start();
484             return httpClient;
485         } catch (Exception e) {
486             if (e instanceof RuntimeException) {
487                 throw (RuntimeException) e;
488             } else {
489                 throw new IllegalStateException("Jetty client start failure", e);
490             }
491         }
492     }
493 }