package dareka;

import dareka.common.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class TlsEndPoint {
    private final static File SITE_KEYSTORE_FILE = new File("certs/site.jks");
    private final static String KEYSTORE_PASSPHRASE = "NicoCache";
    private SSLSocketFactory tlsSocketFactory = null;
    private boolean ready = false;
    
	boolean init() {
        if (!SITE_KEYSTORE_FILE.exists()) {
			Logger.warning("Key store " + SITE_KEYSTORE_FILE.getPath() + " does not exist.");
			Logger.warning("TLS MitM feature is now disabled.");
            return false;
        }
        try {
            char[] passphrase = KEYSTORE_PASSPHRASE.toCharArray();
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(SITE_KEYSTORE_FILE), passphrase);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, passphrase);
            
            SSLContext tlsContext = SSLContext.getInstance("TLS");
            tlsContext.init(kmf.getKeyManagers(), null, null);
            
            tlsSocketFactory = tlsContext.getSocketFactory();
            ready = true;
			return true;
        } catch (Exception ex) {
            Logger.error(ex);
        }
		return false;
	}
    
    public boolean isReady() {
        return ready;
    }
    
    public SSLSocket upgrade(Socket socket) throws IOException {
        SSLSocket tlsSocket = (SSLSocket)tlsSocketFactory.createSocket(
                socket,
                socket.getInetAddress().getHostAddress(),
                socket.getPort(),
                true);
        tlsSocket.setUseClientMode(false);
        tlsSocket.startHandshake();
        return tlsSocket;
    }
}
