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