package uk.ac.cam.gpe21.droidssl.mitm.socket.factory;

import uk.ac.cam.gpe21.droidssl.mitm.socket.SocketUtils;

import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public final class TproxySocketFactory extends SocketFactory {
	public TproxySocketFactory(SSLSocketFactory sslSocketFactory) {
		super(sslSocketFactory);
	}

	@Override
	public ServerSocket openServerSocket(InetSocketAddress address) throws IOException {
		ServerSocket socket = SocketUtils.openTproxyServerSocket();
		socket.bind(address);
		return socket;
	}

	@Override
	public Socket openSocket(InetSocketAddress source, InetSocketAddress destination) throws IOException {
		// TODO: this won't work for SNI yet, as we open a second socket while
		// the first socket is still open and they cannot share the same source
		// address.
		Socket socket = SocketUtils.openTproxySocket();
		socket.bind(source);
		socket.connect(destination);
		return socket;
	}
}

@@ -747,136 +747,320 @@
 %7B%0A%09%09
-// TODO: this won't work for SNI yet, as we open a second socke
+Socket socket = SocketUtils.openTproxySocket();%0A%0A%09%09/*%0A%09%09 * We open two connections in quick succession (the first is to detect%0A%09%09 * the use of SSL, the second is the actual connection tha
 t w
-h
 il
+l b
 e%0A%09%09
-// the first socket is still open and they cannot share
+ * used for the rest of the MITM.) Therefore we need to enable%0A%09%09 * SO_REUSEADDR to stop bind() from failing with
  the
@@ -1078,18 +1078,18 @@
 e%0A%09%09
-//
+ *
  address
 .%0A%09%09
@@ -1088,60 +1088,64 @@
 ress
-.%0A%09%09Socket socket = SocketUtils.openTproxySocket(
+ in TPROXY mode.%0A%09%09 */%0A%09%09socket.setReuseAddress(true
 );%0A
+%0A
 %09%09so

Fix TPROXY.