SocksSocketFactory.java

 1package eu.siacs.conversations.utils;
 2
 3import java.io.IOException;
 4import java.io.InputStream;
 5import java.io.OutputStream;
 6import java.net.InetAddress;
 7import java.net.InetSocketAddress;
 8import java.net.Socket;
 9import java.nio.ByteBuffer;
10
11import eu.siacs.conversations.Config;
12
13public class SocksSocketFactory {
14
15	private static final byte[] LOCALHOST = new byte[]{127,0,0,1};
16
17	public static void createSocksConnection(Socket socket, String destination, int port) throws IOException {
18		InputStream proxyIs = socket.getInputStream();
19		OutputStream proxyOs = socket.getOutputStream();
20		proxyOs.write(new byte[]{0x05, 0x01, 0x00});
21		byte[] response = new byte[2];
22		proxyIs.read(response);
23		byte[] dest = destination.getBytes();
24		ByteBuffer request = ByteBuffer.allocate(7 + dest.length);
25		request.put(new byte[]{0x05, 0x01, 0x00, 0x03});
26		request.put((byte) dest.length);
27		request.put(dest);
28		request.putShort((short) port);
29		proxyOs.write(request.array());
30		response = new byte[7 + dest.length];
31		proxyIs.read(response);
32		if (response[1] != 0x00) {
33			throw new SocksConnectionException();
34		}
35	}
36
37	public static Socket createSocket(InetSocketAddress address, String destination, int port) throws IOException {
38		Socket socket = new Socket();
39		try {
40			socket.connect(address, Config.CONNECT_TIMEOUT * 1000);
41		} catch (IOException e) {
42			throw new SocksProxyNotFoundException();
43		}
44		createSocksConnection(socket, destination, port);
45		return socket;
46	}
47
48	public static Socket createSocketOverTor(String destination, int port) throws IOException {
49		return createSocket(new InetSocketAddress(InetAddress.getByAddress(LOCALHOST), 9050), destination, port);
50	}
51
52	static class SocksConnectionException extends IOException {
53
54	}
55
56	public static class SocksProxyNotFoundException extends IOException {
57
58	}
59}