View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit;
16  
17  import static org.htmlunit.BrowserVersionFeatures.HTTP_HEADER_CH_UA;
18  import static org.htmlunit.BrowserVersionFeatures.HTTP_HEADER_PRIORITY;
19  
20  import java.io.ByteArrayInputStream;
21  import java.io.ByteArrayOutputStream;
22  import java.io.EOFException;
23  import java.io.File;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.io.OutputStream;
27  import java.net.InetAddress;
28  import java.net.URI;
29  import java.net.URISyntaxException;
30  import java.net.URL;
31  import java.nio.charset.Charset;
32  import java.nio.file.Files;
33  import java.nio.file.Path;
34  import java.util.ArrayList;
35  import java.util.HashMap;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.WeakHashMap;
39  import java.util.concurrent.TimeUnit;
40  
41  import javax.net.ssl.HostnameVerifier;
42  import javax.net.ssl.SSLContext;
43  import javax.net.ssl.SSLPeerUnverifiedException;
44  import javax.net.ssl.SSLSocketFactory;
45  
46  import org.apache.commons.io.IOUtils;
47  import org.apache.commons.lang3.StringUtils;
48  import org.apache.commons.lang3.reflect.FieldUtils;
49  import org.apache.commons.logging.Log;
50  import org.apache.commons.logging.LogFactory;
51  import org.apache.http.ConnectionClosedException;
52  import org.apache.http.Header;
53  import org.apache.http.HttpEntity;
54  import org.apache.http.HttpEntityEnclosingRequest;
55  import org.apache.http.HttpException;
56  import org.apache.http.HttpHost;
57  import org.apache.http.HttpRequest;
58  import org.apache.http.HttpRequestInterceptor;
59  import org.apache.http.HttpResponse;
60  import org.apache.http.HttpResponseInterceptor;
61  import org.apache.http.auth.AuthScope;
62  import org.apache.http.auth.Credentials;
63  import org.apache.http.client.AuthCache;
64  import org.apache.http.client.CookieStore;
65  import org.apache.http.client.CredentialsProvider;
66  import org.apache.http.client.config.RequestConfig;
67  import org.apache.http.client.methods.CloseableHttpResponse;
68  import org.apache.http.client.methods.HttpGet;
69  import org.apache.http.client.methods.HttpHead;
70  import org.apache.http.client.methods.HttpPatch;
71  import org.apache.http.client.methods.HttpPost;
72  import org.apache.http.client.methods.HttpPut;
73  import org.apache.http.client.methods.HttpRequestBase;
74  import org.apache.http.client.methods.HttpTrace;
75  import org.apache.http.client.methods.HttpUriRequest;
76  import org.apache.http.client.protocol.HttpClientContext;
77  import org.apache.http.client.protocol.RequestAcceptEncoding;
78  import org.apache.http.client.protocol.RequestAddCookies;
79  import org.apache.http.client.protocol.RequestAuthCache;
80  import org.apache.http.client.protocol.RequestDefaultHeaders;
81  import org.apache.http.client.protocol.RequestExpectContinue;
82  import org.apache.http.client.protocol.ResponseProcessCookies;
83  import org.apache.http.client.utils.URLEncodedUtils;
84  import org.apache.http.config.ConnectionConfig;
85  import org.apache.http.config.RegistryBuilder;
86  import org.apache.http.config.SocketConfig;
87  import org.apache.http.conn.DnsResolver;
88  import org.apache.http.conn.routing.RouteInfo;
89  import org.apache.http.conn.socket.ConnectionSocketFactory;
90  import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
91  import org.apache.http.conn.ssl.DefaultHostnameVerifier;
92  import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
93  import org.apache.http.conn.util.PublicSuffixMatcher;
94  import org.apache.http.conn.util.PublicSuffixMatcherLoader;
95  import org.apache.http.cookie.CookieSpecProvider;
96  import org.apache.http.entity.ContentType;
97  import org.apache.http.entity.StringEntity;
98  import org.apache.http.entity.mime.MultipartEntityBuilder;
99  import org.apache.http.entity.mime.content.InputStreamBody;
100 import org.apache.http.impl.client.BasicAuthCache;
101 import org.apache.http.impl.client.CloseableHttpClient;
102 import org.apache.http.impl.client.HttpClientBuilder;
103 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
104 import org.apache.http.protocol.HttpContext;
105 import org.apache.http.protocol.HttpProcessorBuilder;
106 import org.apache.http.protocol.RequestContent;
107 import org.apache.http.protocol.RequestTargetHost;
108 import org.apache.http.ssl.SSLContexts;
109 import org.apache.http.util.TextUtils;
110 import org.htmlunit.WebRequest.HttpHint;
111 import org.htmlunit.http.HttpUtils;
112 import org.htmlunit.httpclient.HtmlUnitCookieSpecProvider;
113 import org.htmlunit.httpclient.HtmlUnitCookieStore;
114 import org.htmlunit.httpclient.HtmlUnitInsecureOriginCookieStore;
115 import org.htmlunit.httpclient.HtmlUnitSameSiteCookieStore;
116 import org.htmlunit.httpclient.HtmlUnitRedirectStrategie;
117 import org.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory;
118 import org.htmlunit.httpclient.HttpClientConverter;
119 import org.htmlunit.httpclient.SocksConnectionSocketFactory;
120 import org.htmlunit.util.KeyDataPair;
121 import org.htmlunit.util.MimeType;
122 import org.htmlunit.util.NameValuePair;
123 import org.htmlunit.util.UrlUtils;
124 
125 /**
126  * Default implementation of {@link WebConnection}, using the HttpClient library to perform HTTP requests.
127  *
128  * @author Mike Bowler
129  * @author Noboru Sinohara
130  * @author David D. Kilzer
131  * @author Marc Guillemot
132  * @author Brad Clarke
133  * @author Ahmed Ashour
134  * @author Nicolas Belisle
135  * @author Ronald Brill
136  * @author John J Murdoch
137  * @author Carsten Steul
138  * @author Hartmut Arlt
139  * @author Lai Quang Duong
140  */
141 public class HttpWebConnection implements WebConnection {
142 
143     private static final Log LOG = LogFactory.getLog(HttpWebConnection.class);
144 
145     private static final String HACKED_COOKIE_POLICY = "mine";
146 
147     // have one per thread because this is (re)configured for every call (see configureHttpProcessorBuilder)
148     // do not use a ThreadLocal because this in only accessed form this class, but we still need it synchronized
149     private final Map<Thread, HttpClientBuilder> httpClientBuilder_ = new WeakHashMap<>();
150     private final WebClient webClient_;
151 
152     private String virtualHost_;
153     private final HtmlUnitCookieSpecProvider htmlUnitCookieSpecProvider_;
154     private final WebClientOptions usedOptions_;
155     private PoolingHttpClientConnectionManager connectionManager_;
156 
157     /** Authentication cache shared among all threads of a web client. */
158     // BasicAuthCache is thread-safe (ConcurrentHashMap based)
159     private final AuthCache sharedAuthCache_ = new BasicAuthCache();
160 
161     /** Maintains a separate {@link HttpClientContext} object per HttpWebConnection and thread. */
162     private final Map<Thread, HttpClientContext> httpClientContextByThread_ = new WeakHashMap<>();
163 
164     /**
165      * Creates a new HTTP web connection instance.
166      * @param webClient the WebClient that is using this connection
167      */
168     public HttpWebConnection(final WebClient webClient) {
169         super();
170         webClient_ = webClient;
171         htmlUnitCookieSpecProvider_ = new HtmlUnitCookieSpecProvider(webClient.getBrowserVersion());
172         usedOptions_ = new WebClientOptions();
173     }
174 
175     /**
176      * {@inheritDoc}
177      */
178     @Override
179     public WebResponse getResponse(final WebRequest webRequest) throws IOException {
180         final HttpClientBuilder builder = reconfigureHttpClientIfNeeded(getHttpClientBuilder(), webRequest);
181 
182         HttpUriRequest httpMethod = null;
183         try {
184             try {
185                 httpMethod = makeHttpMethod(webRequest, builder);
186             }
187             catch (final URISyntaxException e) {
188                 throw new IOException("Unable to create URI from URL: " + webRequest.getUrl().toExternalForm()
189                         + " (reason: " + e.getMessage() + ")", e);
190             }
191 
192             final URL url = webRequest.getUrl();
193             final HttpHost httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
194             final long startTime = System.currentTimeMillis();
195 
196             final HttpContext httpContext = getHttpContext();
197             try {
198                 try (CloseableHttpClient closeableHttpClient = builder.build()) {
199                     try (CloseableHttpResponse httpResponse =
200                             closeableHttpClient.execute(httpHost, httpMethod, httpContext)) {
201                         return downloadResponse(httpMethod, webRequest, httpResponse, startTime);
202                     }
203                 }
204             }
205             catch (final SSLPeerUnverifiedException ex) {
206                 // Try to use only SSLv3 instead
207                 if (webClient_.getOptions().isUseInsecureSSL()) {
208                     HtmlUnitSSLConnectionSocketFactory.setUseSSL3Only(httpContext, true);
209                     try (CloseableHttpClient closeableHttpClient = builder.build()) {
210                         try (CloseableHttpResponse httpResponse =
211                                 closeableHttpClient.execute(httpHost, httpMethod, httpContext)) {
212                             return downloadResponse(httpMethod, webRequest, httpResponse, startTime);
213                         }
214                     }
215                 }
216                 throw ex;
217             }
218             catch (final Error e) {
219                 // in case a StackOverflowError occurs while the connection is leased, it won't get released.
220                 // Calling code may catch the StackOverflowError, but due to the leak, the httpClient_ may
221                 // come out of connections and throw a ConnectionPoolTimeoutException.
222                 // => best solution, discard the HttpClient instance.
223                 synchronized (httpClientBuilder_) {
224                     httpClientBuilder_.remove(Thread.currentThread());
225                 }
226                 throw e;
227             }
228         }
229         finally {
230             if (httpMethod != null) {
231                 onResponseGenerated(httpMethod);
232             }
233         }
234     }
235 
236     /**
237      * Called when the response has been generated. Default action is to release
238      * the HttpMethod's connection. Subclasses may override.
239      * @param httpMethod the httpMethod used (can be null)
240      */
241     protected void onResponseGenerated(final HttpUriRequest httpMethod) {
242         // nothing to do
243     }
244 
245     /**
246      * Returns the {@link HttpClientContext} for the current thread. Creates a new one if necessary.
247      */
248     private HttpContext getHttpContext() {
249         synchronized (httpClientContextByThread_) {
250             HttpClientContext httpClientContext = httpClientContextByThread_.get(Thread.currentThread());
251             if (httpClientContext == null) {
252                 httpClientContext = new HttpClientContext();
253 
254                 // set the shared authentication cache
255                 httpClientContext.setAttribute(HttpClientContext.AUTH_CACHE, sharedAuthCache_);
256 
257                 httpClientContextByThread_.put(Thread.currentThread(), httpClientContext);
258             }
259             return httpClientContext;
260         }
261     }
262 
263     private void setProxy(final HttpRequestBase httpRequest, final WebRequest webRequest) {
264         final InetAddress localAddress = webClient_.getOptions().getLocalAddress();
265         final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(getTimeout(webRequest), localAddress);
266 
267         if (webRequest.getProxyHost() == null) {
268             requestBuilder.setProxy(null);
269             httpRequest.setConfig(requestBuilder.build());
270             return;
271         }
272 
273         final HttpHost proxy = new HttpHost(webRequest.getProxyHost(),
274                                     webRequest.getProxyPort(), webRequest.getProxyScheme());
275         if (webRequest.isSocksProxy()) {
276             SocksConnectionSocketFactory.setSocksProxy(getHttpContext(), proxy);
277         }
278         else {
279             requestBuilder.setProxy(proxy);
280             httpRequest.setConfig(requestBuilder.build());
281         }
282     }
283 
284     /**
285      * Creates an <code>HttpMethod</code> instance according to the specified parameters.
286      * @param webRequest the request
287      * @param httpClientBuilder the httpClientBuilder that will be configured
288      * @return the <code>HttpMethod</code> instance constructed according to the specified parameters
289      * @throws URISyntaxException in case of syntax problems
290      */
291     private HttpUriRequest makeHttpMethod(final WebRequest webRequest, final HttpClientBuilder httpClientBuilder)
292         throws URISyntaxException {
293 
294         final HttpContext httpContext = getHttpContext();
295         final Charset charset = webRequest.getCharset();
296         // Make sure that the URL is fully encoded. IE actually sends some Unicode chars in request
297         // URLs; because of this we allow some Unicode chars in URLs. However, at this point we're
298         // handing things over the HttpClient, and HttpClient will blow up if we leave these Unicode
299         // chars in the URL.
300         final URL url = UrlUtils.encodeUrl(webRequest.getUrl(), charset);
301 
302         URI uri = UrlUtils.toURI(url, escapeQuery(url.getQuery()));
303         if (getVirtualHost() != null) {
304             uri = URI.create(getVirtualHost());
305         }
306         final HttpRequestBase httpMethod = buildHttpMethod(webRequest.getHttpMethod(), uri);
307         setProxy(httpMethod, webRequest);
308 
309         // developer note:
310         // this has to be in sync with org.htmlunit.WebRequest.getRequestParameters()
311 
312         // POST, PUT, PATCH, DELETE, OPTIONS
313         if (httpMethod instanceof HttpPost
314                 || httpMethod instanceof HttpPut
315                 || httpMethod instanceof HttpPatch
316                 || httpMethod instanceof org.htmlunit.httpclient.HttpDelete
317                 || httpMethod instanceof org.htmlunit.httpclient.HttpOptions) {
318 
319             final HttpEntityEnclosingRequest method = (HttpEntityEnclosingRequest) httpMethod;
320 
321             if (FormEncodingType.URL_ENCODED == webRequest.getEncodingType()) {
322                 if (webRequest.getRequestBody() == null) {
323                     final List<NameValuePair> pairs = webRequest.getRequestParameters();
324                     final String query = HttpUtils.toQueryFormFields(pairs, charset);
325 
326                     final StringEntity urlEncodedEntity;
327                     if (webRequest.hasHint(HttpHint.IncludeCharsetInContentTypeHeader)) {
328                         urlEncodedEntity = new StringEntity(query,
329                                 ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset));
330 
331                     }
332                     else {
333                         urlEncodedEntity = new StringEntity(query, charset);
334                         urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
335                     }
336                     method.setEntity(urlEncodedEntity);
337                 }
338                 else {
339                     final String body = StringUtils.defaultString(webRequest.getRequestBody());
340                     final StringEntity urlEncodedEntity = new StringEntity(body, charset);
341                     urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
342                     method.setEntity(urlEncodedEntity);
343                 }
344             }
345             else if (FormEncodingType.TEXT_PLAIN == webRequest.getEncodingType()) {
346                 if (webRequest.getRequestBody() == null) {
347                     final StringBuilder body = new StringBuilder();
348                     for (final NameValuePair pair : webRequest.getRequestParameters()) {
349                         body.append(StringUtils.remove(StringUtils.remove(pair.getName(), '\r'), '\n'))
350                             .append('=')
351                             .append(StringUtils.remove(StringUtils.remove(pair.getValue(), '\r'), '\n'))
352                             .append("\r\n");
353                     }
354                     final StringEntity bodyEntity = new StringEntity(body.toString(), charset);
355                     bodyEntity.setContentType(MimeType.TEXT_PLAIN);
356                     method.setEntity(bodyEntity);
357                 }
358                 else {
359                     final String body = StringUtils.defaultString(webRequest.getRequestBody());
360                     final StringEntity bodyEntity =
361                             new StringEntity(body, ContentType.create(MimeType.TEXT_PLAIN, charset));
362                     method.setEntity(bodyEntity);
363                 }
364             }
365             else if (FormEncodingType.MULTIPART == webRequest.getEncodingType()) {
366                 final Charset c = getCharset(charset, webRequest.getRequestParameters());
367                 final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode();
368                 builder.setCharset(c);
369 
370                 for (final NameValuePair pair : webRequest.getRequestParameters()) {
371                     if (pair instanceof KeyDataPair dataPair) {
372                         buildFilePart(dataPair, builder);
373                     }
374                     else {
375                         builder.addTextBody(pair.getName(), pair.getValue(),
376                                 ContentType.create(MimeType.TEXT_PLAIN, charset));
377                     }
378                 }
379                 method.setEntity(builder.build());
380             }
381             else {
382                 // for instance a PATCH request
383                 final String body = webRequest.getRequestBody();
384                 if (body != null) {
385                     method.setEntity(new StringEntity(body, charset));
386                 }
387             }
388         }
389         else {
390             // GET, TRACE, HEAD
391             final List<NameValuePair> pairs = webRequest.getRequestParameters();
392             if (!pairs.isEmpty()) {
393                 final String query = HttpUtils.toQueryFormFields(pairs, charset);
394                 uri = UrlUtils.toURI(url, query);
395                 httpMethod.setURI(uri);
396             }
397         }
398 
399         configureHttpProcessorBuilder(httpClientBuilder, webRequest);
400 
401         // Tell the client where to get its credentials from
402         // (it may have changed on the webClient since last call to getHttpClientFor(...))
403         final CredentialsProvider credentialsProvider = webClient_.getCredentialsProvider();
404 
405         // if the used url contains credentials, we have to add this
406         final Credentials requestUrlCredentials = webRequest.getUrlCredentials();
407         if (null != requestUrlCredentials) {
408             final URL requestUrl = webRequest.getUrl();
409             final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
410             // updating our client to keep the credentials for the next request
411             credentialsProvider.setCredentials(authScope, requestUrlCredentials);
412         }
413 
414         // if someone has set credentials to this request, we have to add this
415         final Credentials requestCredentials = webRequest.getCredentials();
416         if (null != requestCredentials) {
417             final URL requestUrl = webRequest.getUrl();
418             final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
419             // updating our client to keep the credentials for the next request
420             credentialsProvider.setCredentials(authScope, requestCredentials);
421         }
422         httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
423         httpContext.removeAttribute(HttpClientContext.CREDS_PROVIDER);
424         httpContext.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
425         return httpMethod;
426     }
427 
428     private static String escapeQuery(final String query) {
429         if (query == null) {
430             return null;
431         }
432         return query.replace("%%", "%25%25");
433     }
434 
435     private static Charset getCharset(final Charset charset, final List<NameValuePair> pairs) {
436         for (final NameValuePair pair : pairs) {
437             if (pair instanceof KeyDataPair pairWithFile) {
438                 if (pairWithFile.getData() == null && pairWithFile.getFile() != null) {
439                     final String fileName = pairWithFile.getFile().getName();
440                     final int length = fileName.length();
441                     for (int i = 0; i < length; i++) {
442                         if (fileName.codePointAt(i) > 127) {
443                             return charset;
444                         }
445                     }
446                 }
447             }
448         }
449         return null;
450     }
451 
452     void buildFilePart(final KeyDataPair pairWithFile, final MultipartEntityBuilder builder) {
453         String mimeType = pairWithFile.getMimeType();
454         if (mimeType == null) {
455             mimeType = MimeType.APPLICATION_OCTET_STREAM;
456         }
457 
458         final ContentType contentType = ContentType.create(mimeType);
459 
460         final File file = pairWithFile.getFile();
461         if (file != null) {
462             String filename = pairWithFile.getFileName();
463             if (filename == null) {
464                 filename = pairWithFile.getFile().getName();
465             }
466             builder.addBinaryBody(pairWithFile.getName(), file, contentType, filename);
467             return;
468         }
469 
470         final byte[] data = pairWithFile.getData();
471         if (data != null) {
472             String filename = pairWithFile.getFileName();
473             if (filename == null) {
474                 filename = pairWithFile.getValue();
475             }
476 
477             builder.addBinaryBody(pairWithFile.getName(), data, contentType, filename);
478             return;
479         }
480 
481         builder.addPart(pairWithFile.getName(),
482                 // Overridden in order not to have a chunked response.
483                 new InputStreamBody(new ByteArrayInputStream(new byte[0]), contentType, pairWithFile.getValue()) {
484                 @Override
485                 public long getContentLength() {
486                     return 0;
487                 }
488             });
489     }
490 
491     /**
492      * Creates and returns a new HttpClient HTTP method based on the specified parameters.
493      * @param submitMethod the submit method being used
494      * @param uri the uri being used
495      * @return a new HttpClient HTTP method based on the specified parameters
496      */
497     private static HttpRequestBase buildHttpMethod(final HttpMethod submitMethod, final URI uri) {
498         final HttpRequestBase method = switch (submitMethod) {
499             case GET -> new HttpGet(uri);
500             case POST -> new HttpPost(uri);
501             case PUT -> new HttpPut(uri);
502             case DELETE -> new org.htmlunit.httpclient.HttpDelete(uri);
503             case OPTIONS -> new org.htmlunit.httpclient.HttpOptions(uri);
504             case HEAD -> new HttpHead(uri);
505             case TRACE -> new HttpTrace(uri);
506             case PATCH -> new HttpPatch(uri);
507         };
508         return method;
509     }
510 
511     /**
512      * Lazily initializes the internal HTTP client.
513      *
514      * @return the initialized HTTP client
515      */
516     protected HttpClientBuilder getHttpClientBuilder() {
517         final Thread currentThread = Thread.currentThread();
518 
519         synchronized (httpClientBuilder_) {
520             HttpClientBuilder builder = httpClientBuilder_.get(currentThread);
521             if (builder == null) {
522                 builder = createHttpClientBuilder();
523 
524                 // this factory is required later
525                 // to be sure this is done, we do it outside the createHttpClient() call
526                 final RegistryBuilder<CookieSpecProvider> registeryBuilder
527                     = RegistryBuilder.<CookieSpecProvider>create()
528                                 .register(HACKED_COOKIE_POLICY, htmlUnitCookieSpecProvider_);
529                 builder.setDefaultCookieSpecRegistry(registeryBuilder.build());
530 
531                 builder.setDefaultCookieStore(new HtmlUnitCookieStore(webClient_.getCookieManager()));
532                 builder.setUserAgent(webClient_.getBrowserVersion().getUserAgent());
533                 httpClientBuilder_.put(currentThread, builder);
534             }
535 
536             return builder;
537         }
538     }
539 
540     /**
541      * Returns the timeout to use for socket and connection timeouts for HttpConnectionManager.
542      * Is overridden to 0 by StreamingWebConnection which keeps reading after a timeout and
543      * must have long running connections explicitly terminated.
544      * @param webRequest the request might have his own timeout
545      * @return the WebClient's timeout
546      */
547     protected int getTimeout(final WebRequest webRequest) {
548         if (webRequest == null || webRequest.getTimeout() < 0) {
549             return webClient_.getOptions().getTimeout();
550         }
551 
552         return webRequest.getTimeout();
553     }
554 
555     /**
556      * Creates the <code>HttpClientBuilder</code> that will be used by this WebClient.
557      * Extensions may override this method in order to create a customized
558      * <code>HttpClientBuilder</code> instance (e.g. with a custom
559      * {@link org.apache.http.conn.ClientConnectionManager} to perform
560      * some tracking; see feature request 1438216).
561      * @return the <code>HttpClientBuilder</code> that will be used by this WebConnection
562      */
563     protected HttpClientBuilder createHttpClientBuilder() {
564         final HttpClientBuilder builder = HttpClientBuilder.create();
565         builder.setRedirectStrategy(new HtmlUnitRedirectStrategie());
566         configureTimeout(builder, getTimeout(null));
567         configureHttpsScheme(builder);
568         builder.setMaxConnPerRoute(6);
569 
570         builder.setConnectionManagerShared(true);
571         return builder;
572     }
573 
574     private void configureTimeout(final HttpClientBuilder builder, final int timeout) {
575         final InetAddress localAddress = webClient_.getOptions().getLocalAddress();
576         final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(timeout, localAddress);
577         builder.setDefaultRequestConfig(requestBuilder.build());
578 
579         builder.setDefaultSocketConfig(createSocketConfigBuilder(timeout).build());
580 
581         getHttpContext().removeAttribute(HttpClientContext.REQUEST_CONFIG);
582         usedOptions_.setTimeout(timeout);
583     }
584 
585     private static RequestConfig.Builder createRequestConfigBuilder(final int timeout, final InetAddress localAddress) {
586         return RequestConfig.custom()
587                 .setCookieSpec(HACKED_COOKIE_POLICY)
588                 .setRedirectsEnabled(false)
589                 .setLocalAddress(localAddress)
590 
591                 // timeout
592                 .setConnectTimeout(timeout)
593                 .setConnectionRequestTimeout(timeout)
594                 .setSocketTimeout(timeout);
595     }
596 
597     private static SocketConfig.Builder createSocketConfigBuilder(final int timeout) {
598         return SocketConfig.custom()
599                 // timeout
600                 .setSoTimeout(timeout);
601     }
602 
603     /**
604      * React on changes that may have occurred on the WebClient settings.
605      * Registering as a listener would be probably better.
606      */
607     private HttpClientBuilder reconfigureHttpClientIfNeeded(final HttpClientBuilder httpClientBuilder,
608             final WebRequest webRequest) {
609         final WebClientOptions options = webClient_.getOptions();
610 
611         // register new SSL factory only if settings have changed
612         if (options.isUseInsecureSSL() != usedOptions_.isUseInsecureSSL()
613                 || options.getSSLClientCertificateStore() != usedOptions_.getSSLClientCertificateStore()
614                 || options.getSSLTrustStore() != usedOptions_.getSSLTrustStore()
615                 || options.getSSLClientCipherSuites() != usedOptions_.getSSLClientCipherSuites()
616                 || options.getSSLClientProtocols() != usedOptions_.getSSLClientProtocols()
617                 || options.getProxyConfig() != usedOptions_.getProxyConfig()) {
618             configureHttpsScheme(httpClientBuilder);
619 
620             if (connectionManager_ != null) {
621                 connectionManager_.shutdown();
622                 connectionManager_ = null;
623             }
624         }
625 
626         final int timeout = getTimeout(webRequest);
627         if (timeout != usedOptions_.getTimeout()) {
628             configureTimeout(httpClientBuilder, timeout);
629         }
630 
631         final long connectionTimeToLive = webClient_.getOptions().getConnectionTimeToLive();
632         if (connectionTimeToLive != usedOptions_.getConnectionTimeToLive()) {
633             httpClientBuilder.setConnectionTimeToLive(connectionTimeToLive, TimeUnit.MILLISECONDS);
634             usedOptions_.setConnectionTimeToLive(connectionTimeToLive);
635         }
636 
637         if (connectionManager_ == null) {
638             connectionManager_ = createConnectionManager(httpClientBuilder);
639         }
640         httpClientBuilder.setConnectionManager(connectionManager_);
641 
642         return httpClientBuilder;
643     }
644 
645     private void configureHttpsScheme(final HttpClientBuilder builder) {
646         final WebClientOptions options = webClient_.getOptions();
647 
648         final SSLConnectionSocketFactory socketFactory =
649                 HtmlUnitSSLConnectionSocketFactory.buildSSLSocketFactory(options);
650 
651         builder.setSSLSocketFactory(socketFactory);
652 
653         usedOptions_.setUseInsecureSSL(options.isUseInsecureSSL());
654         usedOptions_.setSSLClientCertificateKeyStore(options.getSSLClientCertificateStore(),
655                         options.getSSLClientCertificatePassword());
656         usedOptions_.setSSLTrustStore(options.getSSLTrustStore());
657         usedOptions_.setSSLClientCipherSuites(options.getSSLClientCipherSuites());
658         usedOptions_.setSSLClientProtocols(options.getSSLClientProtocols());
659         usedOptions_.setProxyConfig(options.getProxyConfig());
660     }
661 
662     private void configureHttpProcessorBuilder(final HttpClientBuilder builder, final WebRequest webRequest) {
663         final HttpProcessorBuilder b = HttpProcessorBuilder.create();
664         for (final HttpRequestInterceptor i : getHttpRequestInterceptors(webRequest)) {
665             b.add(i);
666         }
667 
668         // These are the headers used in HttpClientBuilder, excluding the already added ones
669         // (RequestClientConnControl and RequestAddCookies)
670         b.addAll(new RequestDefaultHeaders(null),
671                 new RequestContent(),
672                 new RequestTargetHost(),
673                 new RequestExpectContinue());
674         b.add(new RequestAcceptEncoding());
675         b.add(new RequestAuthCache());
676 
677         if (!webRequest.hasHint(HttpHint.BlockCookies)) {
678             if (HttpClientConverter.isSecureCookieOrigin(HttpClientConverter.buildCookieOrigin(webRequest.getUrl()))) {
679                 b.add(new ResponseProcessCookies());
680             }
681             else {
682                 b.add(new InsecureOriginResponseProcessCookies());
683             }
684         }
685         builder.setHttpProcessor(b.build());
686     }
687 
688     /**
689      * Sets the virtual host.
690      * @param virtualHost the virtualHost to set
691      */
692     public void setVirtualHost(final String virtualHost) {
693         virtualHost_ = virtualHost;
694     }
695 
696     /**
697      * Gets the virtual host.
698      * @return virtualHost The current virtualHost
699      */
700     public String getVirtualHost() {
701         return virtualHost_;
702     }
703 
704     /**
705      * Converts an HttpMethod into a {@link WebResponse}.
706      * @param httpResponse the web server's response
707      * @param webRequest the {@link WebRequest}
708      * @param responseBody the {@link DownloadedContent}
709      * @param loadTime the download time
710      * @return a wrapper for the downloaded body.
711      */
712     protected WebResponse makeWebResponse(final HttpResponse httpResponse,
713             final WebRequest webRequest, final DownloadedContent responseBody, final long loadTime) {
714 
715         String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
716         if (statusMessage == null) {
717             statusMessage = "Unknown status message";
718         }
719         final int statusCode = httpResponse.getStatusLine().getStatusCode();
720         final List<NameValuePair> headers = new ArrayList<>();
721         for (final Header header : httpResponse.getAllHeaders()) {
722             headers.add(new NameValuePair(header.getName(), header.getValue()));
723         }
724         final WebResponseData responseData = new WebResponseData(responseBody, statusCode, statusMessage, headers);
725         return newWebResponseInstance(responseData, loadTime, webRequest);
726     }
727 
728     /**
729      * Downloads the response.
730      * This calls {@link #downloadResponseBody(HttpResponse)} and constructs the {@link WebResponse}.
731      * @param httpMethod the HttpUriRequest
732      * @param webRequest the {@link WebRequest}
733      * @param httpResponse the web server's response
734      * @param startTime the download start time
735      * @return a wrapper for the downloaded body.
736      * @throws IOException in case of problem reading/saving the body
737      */
738     protected WebResponse downloadResponse(final HttpUriRequest httpMethod,
739             final WebRequest webRequest, final HttpResponse httpResponse,
740             final long startTime) throws IOException {
741 
742         final DownloadedContent downloadedBody = downloadResponseBody(httpResponse);
743         final long endTime = System.currentTimeMillis();
744 
745         return makeWebResponse(httpResponse, webRequest, downloadedBody, endTime - startTime);
746     }
747 
748     /**
749      * Downloads the response body.
750      * @param httpResponse the web server's response
751      * @return a wrapper for the downloaded body.
752      * @throws IOException in case of problem reading/saving the body
753      */
754     protected DownloadedContent downloadResponseBody(final HttpResponse httpResponse) throws IOException {
755         final HttpEntity httpEntity = httpResponse.getEntity();
756         if (httpEntity == null) {
757             return new DownloadedContent.InMemory(null);
758         }
759 
760         try (InputStream is = httpEntity.getContent()) {
761             return downloadContent(is, webClient_.getOptions().getMaxInMemory(),
762                         webClient_.getOptions().getTempFileDirectory());
763         }
764     }
765 
766     /**
767      * Reads the content of the stream and saves it in memory or on the file system.
768      * @param is the stream to read
769      * @param maxInMemory the maximumBytes to store in memory, after which save to a local file
770      * @param tempFileDirectory the directory to be used or null for the system default
771      * @return a wrapper around the downloaded content
772      * @throws IOException in case of read issues
773      */
774     public static DownloadedContent downloadContent(final InputStream is, final int maxInMemory,
775             final File tempFileDirectory) throws IOException {
776         if (is == null) {
777             return new DownloadedContent.InMemory(null);
778         }
779 
780         try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
781             final byte[] buffer = new byte[1024];
782             int nbRead;
783             try {
784                 while ((nbRead = is.read(buffer)) != -1) {
785                     bos.write(buffer, 0, nbRead);
786                     if (maxInMemory > 0 && bos.size() > maxInMemory) {
787                         // we have exceeded the max for memory, let's write everything to a temporary file;
788                         // Files.createTempFile() restricts the access to the owner of the file
789                         final Path path = tempFileDirectory == null
790                                 ? Files.createTempFile("htmlunit", ".tmp")
791                                 : Files.createTempFile(tempFileDirectory.toPath(), "htmlunit", ".tmp");
792                         final File file = path.toFile();
793                         file.deleteOnExit();
794                         try (OutputStream fos = Files.newOutputStream(path)) {
795                             bos.writeTo(fos); // what we have already read
796                             IOUtils.copyLarge(is, fos); // what remains from the server response
797                         }
798                         return new DownloadedContent.OnFile(file, true);
799                     }
800                 }
801             }
802             catch (final ConnectionClosedException e) {
803                 LOG.warn("Connection was closed while reading from stream.", e);
804                 return new DownloadedContent.InMemory(bos.toByteArray());
805             }
806             catch (final EOFException e) {
807                 // this might happen with broken gzip content
808                 LOG.warn("EOFException while reading from stream.", e);
809                 return new DownloadedContent.InMemory(bos.toByteArray());
810             }
811 
812             return new DownloadedContent.InMemory(bos.toByteArray());
813         }
814     }
815 
816     /**
817      * Constructs an appropriate WebResponse.
818      * May be overridden by subclasses to return a specialized WebResponse.
819      * @param responseData Data that was sent back
820      * @param webRequest the request used to get this response
821      * @param loadTime How long the response took to be sent
822      * @return the new WebResponse
823      */
824     protected WebResponse newWebResponseInstance(
825             final WebResponseData responseData,
826             final long loadTime,
827             final WebRequest webRequest) {
828         return new WebResponse(responseData, webRequest, loadTime);
829     }
830 
831     /**
832      * Returns the {@code Sec-Fetch-Mode} value to use for this request: the explicit
833      * override set on the request if any, otherwise the default mode implied by its
834      * {@link WebRequest.FetchDestination}.
835      * @param webRequest the request
836      * @return the {@code Sec-Fetch-Mode} header value
837      */
838     private static String computeSecFetchMode(final WebRequest webRequest) {
839         final WebRequest.FetchMode override = webRequest.getFetchModeOverride();
840         if (override != null) {
841             return override.getValue();
842         }
843         return defaultFetchModeFor(webRequest.getFetchDestination()).getValue();
844     }
845 
846     /**
847      * The default {@link WebRequest.FetchMode} implied by a given
848      * {@link WebRequest.FetchDestination}, absent an explicit override.
849      * @param destination the destination
850      * @return the default mode for that destination
851      */
852     private static WebRequest.FetchMode defaultFetchModeFor(final WebRequest.FetchDestination destination) {
853         switch (destination) {
854             case DOCUMENT:
855             case IFRAME:
856             case FRAME:
857                 return WebRequest.FetchMode.NAVIGATE;
858 
859             // fonts are always fetched in CORS mode regardless of crossorigin attribute;
860             // XHR/fetch() default to CORS mode too (fetch() can override to no-cors/same-origin,
861             // via WebRequest.setFetchModeOverride)
862             case FONT:
863             case MANIFEST:
864             case EMPTY:
865                 return WebRequest.FetchMode.CORS;
866 
867             // workers can never be cross-origin
868             case WORKER:
869             case SHARED_WORKER:
870             case SERVICE_WORKER:
871                 return WebRequest.FetchMode.SAME_ORIGIN;
872 
873             case WEBSOCKET:
874                 return WebRequest.FetchMode.WEBSOCKET;
875 
876             // image, script, style, object, embed, audio, video, track, report
877             default:
878                 return WebRequest.FetchMode.NO_CORS;
879         }
880     }
881 
882     /**
883      * Computes the {@code Sec-Fetch-Site} value for this request by comparing the
884      * request's {@link WebRequest#getRequestingUrl() initiator} against the target
885      * URL.
886      * @param webRequest the request
887      * @param targetUrl the target URL (passed separately since callers already have it)
888      * @return one of {@code none}, {@code same-origin}, {@code same-site} or {@code cross-site}
889      */
890     private static String computeSecFetchSite(final WebRequest webRequest, final URL targetUrl) {
891         final URL requestingUrl = webRequest.getRequestingUrl();
892         if (requestingUrl == null) {
893             // no initiator - e.g. a typed URL, bookmark, or other browser-chrome-initiated navigation
894             return "none";
895         }
896         if (isSameOrigin(requestingUrl, targetUrl)) {
897             return "same-origin";
898         }
899         if (HttpClientConverter.isSameSite(requestingUrl, targetUrl)) {
900             return "same-site";
901         }
902         return "cross-site";
903     }
904 
905     private static boolean isSameOrigin(final URL a, final URL b) {
906         return a.getProtocol().equals(b.getProtocol())
907                 && a.getHost().equalsIgnoreCase(b.getHost())
908                 && effectivePort(a) == effectivePort(b);
909     }
910 
911     private static int effectivePort(final URL url) {
912         final int port = url.getPort();
913         return port == -1 ? url.getDefaultPort() : port;
914     }
915 
916     private List<HttpRequestInterceptor> getHttpRequestInterceptors(final WebRequest webRequest) {
917         final List<HttpRequestInterceptor> list = new ArrayList<>();
918         final Map<String, String> requestHeaders = new HashMap<>(webRequest.getAdditionalHeaders());
919         final URL url = webRequest.getUrl();
920         final StringBuilder host = new StringBuilder(url.getHost());
921 
922         final BrowserVersion browserVersion = webClient_.getBrowserVersion();
923 
924         final int port = url.getPort();
925         if (port > 0 && port != url.getDefaultPort()) {
926             host.append(':').append(port);
927         }
928 
929         // Both Sec-Fetch-* (https://www.w3.org/TR/fetch-metadata/) and Client Hints
930         // (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA) are
931         // only sent to potentially-trustworthy target origins; computed once up front.
932         final boolean isSecureContext = UrlUtils.isPotentiallyTrustworthy(url);
933 
934         // computed unconditionally: also drives Upgrade-Insecure-Requests below,
935         // which is not gated by origin trustworthiness the way Sec-Fetch-*/Client
936         // Hints are
937         final String secFetchMode = computeSecFetchMode(webRequest);
938 
939         // make sure the headers are added in the right order
940         final String[] headerNames = browserVersion.getHeaderNamesOrdered();
941         for (final String header : headerNames) {
942             if (HttpHeader.HOST.equals(header)) {
943                 list.add(new HostHeaderHttpRequestInterceptor(host.toString()));
944             }
945             else if (HttpHeader.USER_AGENT.equals(header)) {
946                 String headerValue = webRequest.getAdditionalHeader(HttpHeader.USER_AGENT);
947                 if (headerValue == null) {
948                     headerValue = browserVersion.getUserAgent();
949                 }
950                 list.add(new UserAgentHeaderHttpRequestInterceptor(headerValue));
951                 requestHeaders.remove(HttpHeader.USER_AGENT);
952             }
953             else if (HttpHeader.ACCEPT.equals(header)) {
954                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.ACCEPT);
955                 if (headerValue != null) {
956                     list.add(new AcceptHeaderHttpRequestInterceptor(headerValue));
957                     requestHeaders.remove(HttpHeader.ACCEPT);
958                 }
959             }
960             else if (HttpHeader.ACCEPT_LANGUAGE.equals(header)) {
961                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.ACCEPT_LANGUAGE);
962                 if (headerValue != null) {
963                     list.add(new AcceptLanguageHeaderHttpRequestInterceptor(headerValue));
964                     requestHeaders.remove(HttpHeader.ACCEPT_LANGUAGE);
965                 }
966             }
967             else if (HttpHeader.ACCEPT_ENCODING.equals(header)) {
968                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.ACCEPT_ENCODING);
969                 if (headerValue != null) {
970                     list.add(new AcceptEncodingHeaderHttpRequestInterceptor(headerValue));
971                     requestHeaders.remove(HttpHeader.ACCEPT_ENCODING);
972                 }
973             }
974             else if (HttpHeader.SEC_FETCH_DEST.equals(header)) {
975                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.SEC_FETCH_DEST);
976                 if (headerValue != null) {
977                     list.add(new SecFetchDestHeaderHttpRequestInterceptor(headerValue));
978                     requestHeaders.remove(HttpHeader.SEC_FETCH_DEST);
979                 }
980                 else if (isSecureContext) {
981                     list.add(new SecFetchDestHeaderHttpRequestInterceptor(webRequest.getFetchDestination().getValue()));
982                 }
983             }
984             else if (HttpHeader.SEC_FETCH_MODE.equals(header)) {
985                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.SEC_FETCH_MODE);
986                 if (headerValue != null) {
987                     list.add(new SecFetchModeHeaderHttpRequestInterceptor(headerValue));
988                     requestHeaders.remove(HttpHeader.SEC_FETCH_MODE);
989                 }
990                 else if (isSecureContext) {
991                     list.add(new SecFetchModeHeaderHttpRequestInterceptor(secFetchMode));
992                 }
993             }
994             else if (HttpHeader.SEC_FETCH_SITE.equals(header)) {
995                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.SEC_FETCH_SITE);
996                 if (headerValue != null) {
997                     list.add(new SecFetchSiteHeaderHttpRequestInterceptor(headerValue));
998                     requestHeaders.remove(HttpHeader.SEC_FETCH_SITE);
999                 }
1000                 else if (isSecureContext) {
1001                     list.add(new SecFetchSiteHeaderHttpRequestInterceptor(computeSecFetchSite(webRequest, url)));
1002                 }
1003             }
1004             else if (HttpHeader.SEC_FETCH_USER.equals(header)) {
1005                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.SEC_FETCH_USER);
1006                 if (headerValue != null) {
1007                     list.add(new SecFetchUserHeaderHttpRequestInterceptor(headerValue));
1008                     requestHeaders.remove(HttpHeader.SEC_FETCH_USER);
1009                 }
1010 
1011                 // Per spec, sent only for navigations backed by real user activation;
1012                 // real browsers omit it entirely otherwise (never send "?0").
1013                 else if (isSecureContext
1014                         && WebRequest.FetchMode.NAVIGATE.getValue().equals(secFetchMode)
1015                         && webRequest.isUserActivation()) {
1016                     list.add(new SecFetchUserHeaderHttpRequestInterceptor("?1"));
1017                 }
1018             }
1019             else if (HttpHeader.SEC_CH_UA.equals(header)) {
1020                 // Client Hints require a secure context, same as Sec-Fetch-*
1021                 // (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA)
1022                 if (isSecureContext) {
1023                     String headerValue = webRequest.getAdditionalHeader(HttpHeader.SEC_CH_UA);
1024                     if (headerValue != null) {
1025                         list.add(new SecClientHintUserAgentHeaderHttpRequestInterceptor(headerValue));
1026                         requestHeaders.remove(HttpHeader.SEC_CH_UA);
1027                     }
1028                     else {
1029                         if (browserVersion.hasFeature(HTTP_HEADER_CH_UA)) {
1030                             headerValue = browserVersion.getSecClientHintUserAgentHeader();
1031                             list.add(new SecClientHintUserAgentHeaderHttpRequestInterceptor(headerValue));
1032                         }
1033                     }
1034                 }
1035             }
1036             else if (HttpHeader.SEC_CH_UA_MOBILE.equals(header)) {
1037                 if (isSecureContext) {
1038                     final String headerValue = webRequest.getAdditionalHeader(HttpHeader.SEC_CH_UA_MOBILE);
1039                     if (headerValue != null) {
1040                         list.add(new SecClientHintUserAgentMobileHeaderHttpRequestInterceptor(headerValue));
1041                         requestHeaders.remove(HttpHeader.SEC_CH_UA_MOBILE);
1042                     }
1043                     else {
1044                         if (browserVersion.hasFeature(HTTP_HEADER_CH_UA)) {
1045                             list.add(new SecClientHintUserAgentMobileHeaderHttpRequestInterceptor("?0"));
1046                         }
1047                     }
1048                 }
1049             }
1050             else if (HttpHeader.SEC_CH_UA_PLATFORM.equals(header)) {
1051                 if (isSecureContext) {
1052                     String headerValue = webRequest.getAdditionalHeader(HttpHeader.SEC_CH_UA_PLATFORM);
1053                     if (headerValue != null) {
1054                         list.add(new SecClientHintUserAgentPlatformHeaderHttpRequestInterceptor(headerValue));
1055                         requestHeaders.remove(HttpHeader.SEC_CH_UA_PLATFORM);
1056                     }
1057                     else {
1058                         if (browserVersion.hasFeature(HTTP_HEADER_CH_UA)) {
1059                             headerValue = browserVersion.getSecClientHintUserAgentPlatformHeader();
1060                             list.add(new SecClientHintUserAgentPlatformHeaderHttpRequestInterceptor(headerValue));
1061                         }
1062                     }
1063                 }
1064             }
1065             else if (HttpHeader.PRIORITY.equals(header)) {
1066                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.PRIORITY);
1067                 if (headerValue != null) {
1068                     list.add(new PriorityHeaderHttpRequestInterceptor(headerValue));
1069                     requestHeaders.remove(HttpHeader.PRIORITY);
1070                 }
1071                 else {
1072                     if (browserVersion.hasFeature(HTTP_HEADER_PRIORITY)) {
1073                         list.add(new PriorityHeaderHttpRequestInterceptor("u=0, i"));
1074                     }
1075                 }
1076             }
1077             else if (HttpHeader.UPGRADE_INSECURE_REQUESTS.equals(header)) {
1078                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.UPGRADE_INSECURE_REQUESTS);
1079                 if (headerValue != null) {
1080                     list.add(new UpgradeInsecureRequestHeaderHttpRequestInterceptor(headerValue));
1081                     requestHeaders.remove(HttpHeader.UPGRADE_INSECURE_REQUESTS);
1082                 }
1083 
1084                 // Real browsers only send this for navigations (top-level, iframe, frame),
1085                 // never for subresource fetches (image/script/style/xhr/...).
1086                 else if (WebRequest.FetchMode.NAVIGATE.getValue().equals(secFetchMode)
1087                             && HttpMethod.OPTIONS != webRequest.getHttpMethod()) {
1088                     list.add(new UpgradeInsecureRequestHeaderHttpRequestInterceptor("1"));
1089                 }
1090             }
1091             else if (HttpHeader.REFERER.equals(header)) {
1092                 final String headerValue = webRequest.getAdditionalHeader(HttpHeader.REFERER);
1093                 if (headerValue != null) {
1094                     list.add(new RefererHeaderHttpRequestInterceptor(headerValue));
1095                     requestHeaders.remove(HttpHeader.REFERER);
1096                 }
1097             }
1098             else if (HttpHeader.CONNECTION.equals(header)) {
1099                 list.add(new RequestClientConnControl());
1100             }
1101             else if (HttpHeader.COOKIE.equals(header)) {
1102                 if (!webRequest.hasHint(HttpHint.BlockCookies)) {
1103                     // top-level navigations: the initiator decides (Lax);
1104                     // other requests: the site for cookies of the initiating document
1105                     // (the top-level document if all ancestors are same-site)
1106                     URL siteForCookies = webRequest.getRequestingUrl();
1107                     if (webRequest.getFetchDestination() != WebRequest.FetchDestination.DOCUMENT
1108                             && webRequest.getSiteForCookies() != null) {
1109                         siteForCookies = webRequest.getSiteForCookies();
1110                     }
1111                     if (siteForCookies != null && !HttpClientConverter.isSameSite(siteForCookies, url)) {
1112                         list.add(new CrossSiteRequestAddCookies(webRequest));
1113                     }
1114                     else {
1115                         list.add(new RequestAddCookies());
1116                     }
1117                 }
1118             }
1119             else if (HttpHeader.DNT.equals(header) && webClient_.getOptions().isDoNotTrackEnabled()) {
1120                 list.add(new DntHeaderHttpRequestInterceptor("1"));
1121             }
1122         }
1123 
1124         // not all browser versions have DNT by default as part of getHeaderNamesOrdered()
1125         // so we add it again, in case
1126         if (webClient_.getOptions().isDoNotTrackEnabled()) {
1127             list.add(new DntHeaderHttpRequestInterceptor("1"));
1128         }
1129 
1130         synchronized (requestHeaders) {
1131             list.add(new MultiHttpRequestInterceptor(new HashMap<>(requestHeaders)));
1132         }
1133         return list;
1134     }
1135 
1136     /** We must have a separate class per header, because of org.apache.http.protocol.ChainBuilder. */
1137     private static final class HostHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1138         private final String value_;
1139 
1140         HostHeaderHttpRequestInterceptor(final String value) {
1141             value_ = value;
1142         }
1143 
1144         @Override
1145         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1146             request.setHeader(HttpHeader.HOST, value_);
1147         }
1148     }
1149 
1150     private static final class UserAgentHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1151         private final String value_;
1152 
1153         UserAgentHeaderHttpRequestInterceptor(final String value) {
1154             value_ = value;
1155         }
1156 
1157         @Override
1158         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1159             request.setHeader(HttpHeader.USER_AGENT, value_);
1160         }
1161     }
1162 
1163     private static final class AcceptHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1164         private final String value_;
1165 
1166         AcceptHeaderHttpRequestInterceptor(final String value) {
1167             value_ = value;
1168         }
1169 
1170         @Override
1171         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1172             request.setHeader(HttpHeader.ACCEPT, value_);
1173         }
1174     }
1175 
1176     private static final class AcceptLanguageHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1177         private final String value_;
1178 
1179         AcceptLanguageHeaderHttpRequestInterceptor(final String value) {
1180             value_ = value;
1181         }
1182 
1183         @Override
1184         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1185             request.setHeader(HttpHeader.ACCEPT_LANGUAGE, value_);
1186         }
1187     }
1188 
1189     private static final class UpgradeInsecureRequestHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1190         private final String value_;
1191 
1192         UpgradeInsecureRequestHeaderHttpRequestInterceptor(final String value) {
1193             value_ = value;
1194         }
1195 
1196         @Override
1197         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1198             request.setHeader(HttpHeader.UPGRADE_INSECURE_REQUESTS, value_);
1199         }
1200     }
1201 
1202     private static final class AcceptEncodingHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1203         private final String value_;
1204 
1205         AcceptEncodingHeaderHttpRequestInterceptor(final String value) {
1206             value_ = value;
1207         }
1208 
1209         @Override
1210         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1211             request.setHeader("Accept-Encoding", value_);
1212         }
1213     }
1214 
1215     private static final class RefererHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1216         private final String value_;
1217 
1218         RefererHeaderHttpRequestInterceptor(final String value) {
1219             value_ = value;
1220         }
1221 
1222         @Override
1223         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1224             request.setHeader(HttpHeader.REFERER, value_);
1225         }
1226     }
1227 
1228     private static final class DntHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1229         private final String value_;
1230 
1231         DntHeaderHttpRequestInterceptor(final String value) {
1232             value_ = value;
1233         }
1234 
1235         @Override
1236         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1237             request.setHeader(HttpHeader.DNT, value_);
1238         }
1239     }
1240 
1241     private static final class SecFetchModeHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1242         private final String value_;
1243 
1244         SecFetchModeHeaderHttpRequestInterceptor(final String value) {
1245             value_ = value;
1246         }
1247 
1248         @Override
1249         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1250             request.setHeader(HttpHeader.SEC_FETCH_MODE, value_);
1251         }
1252     }
1253 
1254     /**
1255      * Processes the cookies of a response from an insecure origin; cookies that would overwrite
1256      * or shadow a secure cookie are ignored (see {@link HtmlUnitInsecureOriginCookieStore}).
1257      */
1258     private static final class InsecureOriginResponseProcessCookies implements HttpResponseInterceptor {
1259         private final ResponseProcessCookies delegate_ = new ResponseProcessCookies();
1260 
1261         @Override
1262         public void process(final HttpResponse response, final HttpContext context)
1263                 throws HttpException, IOException {
1264             final HttpClientContext clientContext = HttpClientContext.adapt(context);
1265             final CookieStore cookieStore = clientContext.getCookieStore();
1266             if (cookieStore == null) {
1267                 delegate_.process(response, context);
1268                 return;
1269             }
1270 
1271             clientContext.setCookieStore(new HtmlUnitInsecureOriginCookieStore(cookieStore));
1272             try {
1273                 delegate_.process(response, context);
1274             }
1275             finally {
1276                 clientContext.setCookieStore(cookieStore);
1277             }
1278         }
1279     }
1280 
1281     /**
1282      * Adds the cookies to a cross-site request; the cookies are filtered based on
1283      * their SameSite attribute (see {@link HtmlUnitSameSiteCookieStore}).
1284      */
1285     private static final class CrossSiteRequestAddCookies implements HttpRequestInterceptor {
1286         private final RequestAddCookies delegate_ = new RequestAddCookies();
1287         private final boolean topLevelNavigation_;
1288         private final boolean safeMethod_;
1289 
1290         CrossSiteRequestAddCookies(final WebRequest webRequest) {
1291             topLevelNavigation_ = webRequest.getFetchDestination() == WebRequest.FetchDestination.DOCUMENT;
1292 
1293             final HttpMethod method = webRequest.getHttpMethod();
1294             safeMethod_ = method == HttpMethod.GET
1295                     || method == HttpMethod.HEAD
1296                     || method == HttpMethod.OPTIONS
1297                     || method == HttpMethod.TRACE;
1298         }
1299 
1300         @Override
1301         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1302             final HttpClientContext clientContext = HttpClientContext.adapt(context);
1303             final CookieStore cookieStore = clientContext.getCookieStore();
1304             if (cookieStore == null) {
1305                 delegate_.process(request, context);
1306                 return;
1307             }
1308 
1309             clientContext.setCookieStore(
1310                     new HtmlUnitSameSiteCookieStore(cookieStore, topLevelNavigation_, safeMethod_));
1311             try {
1312                 delegate_.process(request, context);
1313             }
1314             finally {
1315                 clientContext.setCookieStore(cookieStore);
1316             }
1317         }
1318     }
1319 
1320     private static final class SecFetchSiteHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1321         private final String value_;
1322 
1323         SecFetchSiteHeaderHttpRequestInterceptor(final String value) {
1324             value_ = value;
1325         }
1326 
1327         @Override
1328         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1329             request.setHeader(HttpHeader.SEC_FETCH_SITE, value_);
1330         }
1331     }
1332 
1333     private static final class SecFetchUserHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1334         private final String value_;
1335 
1336         SecFetchUserHeaderHttpRequestInterceptor(final String value) {
1337             value_ = value;
1338         }
1339 
1340         @Override
1341         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1342             request.setHeader(HttpHeader.SEC_FETCH_USER, value_);
1343         }
1344     }
1345 
1346     private static final class SecFetchDestHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1347         private final String value_;
1348 
1349         SecFetchDestHeaderHttpRequestInterceptor(final String value) {
1350             value_ = value;
1351         }
1352 
1353         @Override
1354         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1355             request.setHeader(HttpHeader.SEC_FETCH_DEST, value_);
1356         }
1357     }
1358 
1359     private static final class SecClientHintUserAgentHeaderHttpRequestInterceptor implements HttpRequestInterceptor {
1360         private final String value_;
1361 
1362         SecClientHintUserAgentHeaderHttpRequestInterceptor(final String value) {
1363             value_ = value;
1364         }
1365 
1366         @Override
1367         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1368             request.setHeader(HttpHeader.SEC_CH_UA, value_);
1369         }
1370     }
1371 
1372     private static final class SecClientHintUserAgentMobileHeaderHttpRequestInterceptor
1373             implements HttpRequestInterceptor {
1374         private final String value_;
1375 
1376         SecClientHintUserAgentMobileHeaderHttpRequestInterceptor(final String value) {
1377             value_ = value;
1378         }
1379 
1380         @Override
1381         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1382             request.setHeader(HttpHeader.SEC_CH_UA_MOBILE, value_);
1383         }
1384     }
1385 
1386     private static final class SecClientHintUserAgentPlatformHeaderHttpRequestInterceptor
1387             implements HttpRequestInterceptor {
1388         private final String value_;
1389 
1390         SecClientHintUserAgentPlatformHeaderHttpRequestInterceptor(final String value) {
1391             value_ = value;
1392         }
1393 
1394         @Override
1395         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1396             request.setHeader(HttpHeader.SEC_CH_UA_PLATFORM, value_);
1397         }
1398     }
1399 
1400     private static final class PriorityHeaderHttpRequestInterceptor
1401             implements HttpRequestInterceptor {
1402         private final String value_;
1403 
1404         PriorityHeaderHttpRequestInterceptor(final String value) {
1405             value_ = value;
1406         }
1407 
1408         @Override
1409         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
1410             request.setHeader(HttpHeader.PRIORITY, value_);
1411         }
1412     }
1413 
1414     private static class MultiHttpRequestInterceptor implements HttpRequestInterceptor {
1415         private final Map<String, String> map_;
1416 
1417         MultiHttpRequestInterceptor(final Map<String, String> map) {
1418             map_ = map;
1419         }
1420 
1421         @Override
1422         public void process(final HttpRequest request, final HttpContext context)
1423             throws HttpException, IOException {
1424             for (final Map.Entry<String, String> entry : map_.entrySet()) {
1425                 request.setHeader(entry.getKey(), entry.getValue());
1426             }
1427         }
1428     }
1429 
1430     private static class RequestClientConnControl implements HttpRequestInterceptor {
1431 
1432         private static final String PROXY_CONN_DIRECTIVE = "Proxy-Connection";
1433         private static final String CONN_DIRECTIVE = "Connection";
1434         private static final String CONN_KEEP_ALIVE = "keep-alive";
1435 
1436         /**
1437          * Ctor.
1438          */
1439         RequestClientConnControl() {
1440             super();
1441         }
1442 
1443         @Override
1444         public void process(final HttpRequest request, final HttpContext context)
1445             throws HttpException, IOException {
1446             final String method = request.getRequestLine().getMethod();
1447             if ("CONNECT".equalsIgnoreCase(method)) {
1448                 request.setHeader(PROXY_CONN_DIRECTIVE, CONN_KEEP_ALIVE);
1449                 return;
1450             }
1451 
1452             final HttpClientContext clientContext = HttpClientContext.adapt(context);
1453 
1454             // Obtain the client connection (required)
1455             final RouteInfo route = clientContext.getHttpRoute();
1456             if (route == null) {
1457                 return;
1458             }
1459 
1460             if ((route.getHopCount() == 1 || route.isTunnelled())
1461                     && !request.containsHeader(CONN_DIRECTIVE)) {
1462                 request.addHeader(CONN_DIRECTIVE, CONN_KEEP_ALIVE);
1463             }
1464             if (route.getHopCount() == 2
1465                     && !route.isTunnelled()
1466                     && !request.containsHeader(PROXY_CONN_DIRECTIVE)) {
1467                 request.addHeader(PROXY_CONN_DIRECTIVE, CONN_KEEP_ALIVE);
1468             }
1469         }
1470     }
1471 
1472     /**
1473      * {@inheritDoc}
1474      */
1475     @Override
1476     public void close() {
1477         synchronized (httpClientBuilder_) {
1478             httpClientBuilder_.clear();
1479         }
1480         sharedAuthCache_.clear();
1481         synchronized (httpClientContextByThread_) {
1482             httpClientContextByThread_.clear();
1483         }
1484 
1485         if (connectionManager_ != null) {
1486             connectionManager_.shutdown();
1487             connectionManager_ = null;
1488         }
1489     }
1490 
1491     /**
1492      * Has the exact logic in {@link HttpClientBuilder#build()} which sets the {@code connManager} part,
1493      * but with the ability to configure {@code socketFactory}.
1494      */
1495     private static PoolingHttpClientConnectionManager createConnectionManager(final HttpClientBuilder builder) {
1496         try {
1497             PublicSuffixMatcher publicSuffixMatcher = getField(builder, "publicSuffixMatcher");
1498             if (publicSuffixMatcher == null) {
1499                 publicSuffixMatcher = PublicSuffixMatcherLoader.getDefault();
1500             }
1501 
1502             LayeredConnectionSocketFactory sslSocketFactory = getField(builder, "sslSocketFactory");
1503             final SocketConfig defaultSocketConfig = getField(builder, "defaultSocketConfig");
1504             final ConnectionConfig defaultConnectionConfig = getField(builder, "defaultConnectionConfig");
1505             final boolean systemProperties = getField(builder, "systemProperties");
1506             final int maxConnTotal = getField(builder, "maxConnTotal");
1507             final int maxConnPerRoute = getField(builder, "maxConnPerRoute");
1508             HostnameVerifier hostnameVerifier = getField(builder, "hostnameVerifier");
1509             final SSLContext sslcontext = getField(builder, "sslContext");
1510             final DnsResolver dnsResolver = getField(builder, "dnsResolver");
1511             final long connTimeToLive = getField(builder, "connTimeToLive");
1512             final TimeUnit connTimeToLiveTimeUnit = getField(builder, "connTimeToLiveTimeUnit");
1513 
1514             if (sslSocketFactory == null) {
1515                 final String[] supportedProtocols = systemProperties
1516                         ? split(System.getProperty("https.protocols")) : null;
1517                 final String[] supportedCipherSuites = systemProperties
1518                         ? split(System.getProperty("https.cipherSuites")) : null;
1519                 if (hostnameVerifier == null) {
1520                     hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
1521                 }
1522                 if (sslcontext == null) {
1523                     if (systemProperties) {
1524                         sslSocketFactory = new SSLConnectionSocketFactory(
1525                                 (SSLSocketFactory) SSLSocketFactory.getDefault(),
1526                                 supportedProtocols, supportedCipherSuites, hostnameVerifier);
1527                     }
1528                     else {
1529                         sslSocketFactory = new SSLConnectionSocketFactory(
1530                                 SSLContexts.createDefault(),
1531                                 hostnameVerifier);
1532                     }
1533                 }
1534                 else {
1535                     sslSocketFactory = new SSLConnectionSocketFactory(
1536                             sslcontext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
1537                 }
1538             }
1539 
1540             final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager(
1541                     RegistryBuilder.<ConnectionSocketFactory>create()
1542                         .register("http", new SocksConnectionSocketFactory())
1543                         .register("https", sslSocketFactory)
1544                         .build(),
1545                         null,
1546                         null,
1547                         dnsResolver,
1548                         connTimeToLive,
1549                         connTimeToLiveTimeUnit != null ? connTimeToLiveTimeUnit : TimeUnit.MILLISECONDS);
1550             if (defaultSocketConfig != null) {
1551                 poolingmgr.setDefaultSocketConfig(defaultSocketConfig);
1552             }
1553             if (defaultConnectionConfig != null) {
1554                 poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig);
1555             }
1556             if (systemProperties) {
1557                 String s = System.getProperty("http.keepAlive", "true");
1558                 if ("true".equalsIgnoreCase(s)) {
1559                     s = System.getProperty("http.maxConnections", "5");
1560                     final int max = Integer.parseInt(s);
1561                     poolingmgr.setDefaultMaxPerRoute(max);
1562                     poolingmgr.setMaxTotal(2 * max);
1563                 }
1564             }
1565             if (maxConnTotal > 0) {
1566                 poolingmgr.setMaxTotal(maxConnTotal);
1567             }
1568             if (maxConnPerRoute > 0) {
1569                 poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
1570             }
1571             return poolingmgr;
1572         }
1573         catch (final IllegalAccessException e) {
1574             throw new RuntimeException(e);
1575         }
1576     }
1577 
1578     private static String[] split(final String s) {
1579         if (TextUtils.isBlank(s)) {
1580             return null;
1581         }
1582         return s.split(" *, *");
1583     }
1584 
1585     @SuppressWarnings("unchecked")
1586     private static <T> T getField(final Object target, final String fieldName) throws IllegalAccessException {
1587         return (T) FieldUtils.readDeclaredField(target, fieldName, true);
1588     }
1589 }