[LIB-13] Several options for working through a proxy server
[chesshog-scanner.git] / src / main / java / org / hedgecode / chess / scanner / proxy / client / SSLSocksSocketFactory.java
1 /*
2  * Copyright (c) 2019-2020. Developed by Hedgecode.
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  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.chess.scanner.proxy.client;
18
19 import java.io.IOException;
20 import java.net.InetSocketAddress;
21 import java.net.Proxy;
22 import java.net.Socket;
23
24 import org.apache.http.HttpHost;
25 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
26 import org.apache.http.protocol.HttpContext;
27 import org.apache.http.ssl.SSLContexts;
28
29 import org.hedgecode.chess.scanner.ScannerConstants;
30
31 /**
32  * SSLSocksSocketFactory
33  *
34  * @author Dmitry Samoshin aka gotty
35  */
36 public class SSLSocksSocketFactory extends SSLConnectionSocketFactory {
37
38     SSLSocksSocketFactory() {
39         super(
40                 SSLContexts.createSystemDefault()
41         );
42     }
43
44     @Override
45     public Socket createSocket(final HttpContext context) throws IOException {
46         Proxy proxy = new Proxy(
47                 Proxy.Type.SOCKS,
48                 (InetSocketAddress) context.getAttribute(ScannerConstants.PROXY_SOCKS_ADDRESS)
49         );
50         return new Socket(proxy);
51     }
52
53     @Override
54     public Socket connectSocket(
55             int connectTimeout, Socket socket, HttpHost host,
56             InetSocketAddress remoteAddress, InetSocketAddress localAddress,
57             HttpContext context
58     ) throws IOException {
59         InetSocketAddress unresolvedAddress = InetSocketAddress.createUnresolved(
60                 host.getHostName(), remoteAddress.getPort()
61         );
62         return super.connectSocket(
63                 connectTimeout, socket, host, unresolvedAddress, localAddress, context
64         );
65     }
66
67 }