View Javadoc
1   /*
2    * Copyright (c) 2002-2025 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.httpclient;
16  
17  import java.io.IOException;
18  import java.net.InetSocketAddress;
19  import java.net.Proxy;
20  import java.net.Socket;
21  
22  import org.apache.http.HttpHost;
23  import org.apache.http.conn.socket.PlainConnectionSocketFactory;
24  import org.apache.http.protocol.HttpContext;
25  
26  /**
27   * SOCKS aware {@link org.apache.http.conn.socket.ConnectionSocketFactory}.
28   *
29   * @author Ahmed Ashour
30   * @author Ronald Brill
31   * @author Marc Guillemot
32   */
33  public class SocksConnectionSocketFactory extends PlainConnectionSocketFactory {
34      private static final String SOCKS_PROXY = "htmlunit.socksproxy";
35  
36      /**
37       * Enables the socks proxy.
38       * @param context the HttpContext
39       * @param socksProxy the HttpHost
40       */
41      public static void setSocksProxy(final HttpContext context, final HttpHost socksProxy) {
42          context.setAttribute(SOCKS_PROXY, socksProxy);
43      }
44  
45      static HttpHost getSocksProxy(final HttpContext context) {
46          return (HttpHost) context.getAttribute(SOCKS_PROXY);
47      }
48  
49      static Socket createSocketWithSocksProxy(final HttpHost socksProxy) {
50          final InetSocketAddress address = new InetSocketAddress(socksProxy.getHostName(), socksProxy.getPort());
51          final Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
52          return new Socket(proxy);
53      }
54  
55      /**
56       * {@inheritDoc}
57       */
58      @Override
59      public Socket createSocket(final HttpContext context) throws IOException {
60          final HttpHost socksProxy = getSocksProxy(context);
61          if (socksProxy != null) {
62              return createSocketWithSocksProxy(socksProxy);
63          }
64          return super.createSocket(context);
65      }
66  }