// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package socket.ssl.binary.traditional;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;

public class MultiServer {
    public static class ClientHandler extends Thread {
        private SSLSocket s;
        public ClientHandler(SSLSocket s) {
            this.s = s;
        }
        @Override
        public void run() {
            try {
                System.out.printf("(handler in thread %d)\n", Thread.currentThread().getId());
                // get streams
                DataInputStream dis = new DataInputStream(s.getInputStream());
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                // read a and b
                int a = dis.readInt();
                int b = dis.readInt();
                // calculate c and send
                int c = a + b;
                dos.writeInt(c);
                dos.flush();
                // read v
                int buflen = dis.readByte();
                byte[] buf = new byte[buflen];
                int ix = 0;
                while(ix < buf.length) {
                    ix += dis.read(buf, ix, buf.length - ix);
                }
                String v = new String(buf, "UTF-8");
                // calculate v2 and send
                String v2 = v + v;
                byte[] v2b = v2.getBytes("UTF-8");
                dos.writeByte(v2b.length);
                dos.write(v2b);
                dos.flush();
                // close connection
                dis.close();
                dos.close();
                s.close();
            } catch (IOException e) {
                // TODO
                e.printStackTrace();
            }
        }
    }
    private static SSLContext setupSSLContext(String keystore, String passphrase) throws Exception {
        KeyStore ks = KeyStore.getInstance("pkcs12");
        InputStream is = new FileInputStream(keystore);
        ks.load(is, passphrase.toCharArray());
        is.close();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, passphrase.toCharArray());
        SSLContext sslctx = SSLContext.getInstance("TLSv1.2");
        sslctx.init(kmf.getKeyManagers(), null, null);
        return sslctx;
    }
    private static final int PORT = 12345;
    public static void main(String[] args) {
        try {
            // get SSL context
            SSLContext sslctx = setupSSLContext("/work/sslserver.pfx", "topsecret");
            // listen on port
            SSLServerSocket ss = (SSLServerSocket) sslctx.getServerSocketFactory().createServerSocket(PORT);
            // only use TLS 1.2
            ss.setEnabledProtocols(new String[] { "TLSv1.2" });
            // do not use client certificate
            ss.setNeedClientAuth(false);
            ss.setWantClientAuth(false);
            while(true) {
                // accept connection
                SSLSocket s = (SSLSocket) ss.accept();
                System.out.printf("(connection from %s)\n", s.getRemoteSocketAddress());
                // start new thread to handle connection
                (new ClientHandler(s)).start();
            }
        } catch (Exception e) {
            // TODO
            e.printStackTrace();
        }
    }
}
