SocksConnection.java

 1package eu.siacs.conversations.xmpp.jingle;
 2
 3import java.io.IOException;
 4import java.io.InputStream;
 5import java.io.OutputStream;
 6import java.net.Socket;
 7import java.net.UnknownHostException;
 8import java.security.MessageDigest;
 9import java.security.NoSuchAlgorithmException;
10import java.util.Arrays;
11
12import eu.siacs.conversations.utils.CryptoHelper;
13
14import android.util.Log;
15
16public class SocksConnection {
17	
18	private JingleConnection jingleConnection;
19	private Socket socket;
20	private String host;
21	private int port;
22	private String destination;
23	
24	public SocksConnection(JingleConnection jingleConnection, String host, int port) {
25		this.jingleConnection = jingleConnection;
26		this.host = host;
27		this.port = port;
28		try {
29			MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
30			StringBuilder destBuilder = new StringBuilder();
31			destBuilder.append(jingleConnection.getSessionId());
32			destBuilder.append(jingleConnection.getInitiator());
33			destBuilder.append(jingleConnection.getResponder());
34			mDigest.reset();
35			Log.d("xmppService","plain destination: "+destBuilder.toString());
36			this.destination = CryptoHelper.bytesToHex(mDigest.digest(destBuilder.toString().getBytes()));
37			Log.d("xmppService","host="+host+", port="+port+", destination: "+destination);
38		} catch (NoSuchAlgorithmException e) {
39			
40		}
41	}
42	
43	public boolean connect() {
44		try {
45			this.socket = new Socket(this.host, this.port);
46			InputStream is = socket.getInputStream();
47			OutputStream os = socket.getOutputStream();
48			byte[] login = {0x05, 0x01, 0x00};
49			byte[] expectedReply = {0x05,0x00};
50			byte[] reply = new byte[2];
51			os.write(login);
52			is.read(reply);
53			if (Arrays.equals(reply, expectedReply)) {
54				String connect = ""+'\u0005'+'\u0001'+'\u0000'+'\u0003'+'\u0028'+this.destination+'\u0000'+'\u0000';
55				os.write(connect.getBytes());
56				byte[] result = new byte[2];
57				is.read(result);
58				int status = result[0];
59				return (status==0);
60			} else {
61				socket.close();
62				return false;
63			}
64		} catch (UnknownHostException e) {
65			return false;
66		} catch (IOException e) {
67			return false;
68		}
69	}
70}