//
//  Copyright (C) 2002 Constantin Kaplinsky, Inc.  All Rights Reserved.
//  Copyright 2007 MIT Student Information Processing Board
//
//  This is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This software is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this software; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
//  USA.
//

//
// VNCProxyConnectSocketFactory.java together with VNCProxyConnectSocket.java
// implement an alternate way to connect to VNC servers via one or two
// VNCProxy proxies supporting the VNCProxy CONNECT method.
//

import java.applet.*;
import java.net.*;
import javax.net.ssl.*;
import java.io.*;

class VNCProxyConnectSocketFactory implements SocketFactory {

    SSLSocketFactory factory;
    
    public VNCProxyConnectSocketFactory() {
	try {
	    SSLContext c = SSLContext.getInstance("SSL");
	    c.init(null,
		   new TrustManager[] { new SIPBTrustManager() },
		   null);
	    factory =
		(SSLSocketFactory)c.getSocketFactory();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

  public Socket createSocket(String host, int port, Applet applet)
    throws IOException {

    return createSocket(host, port,
			applet.getParameter("VMNAME"),
			applet.getParameter("AUTHTOKEN"));
  }

  public Socket createSocket(String host, int port, String[] args)
    throws IOException {

    return createSocket(host, port,
			readArg(args, "VMNAME"),
			readArg(args, "AUTHTOKEN"));
  }

  public Socket createSocket(String host, int port,
			     String vmname, String authtoken)
    throws IOException {

    if (vmname == null || authtoken == null) {
      System.out.println("Incomplete parameter list for VNCProxyConnectSocket");
      return new Socket(host, port);
    }

    System.out.println("VNCProxy CONNECT via proxy " + host +
		       " port " + port + " to vm " + vmname);
    SSLSocket ssls = (SSLSocket)factory.createSocket(host, port);
    ssls.startHandshake();
    VNCProxyConnectSocketWrapper s =
      new VNCProxyConnectSocketWrapper(ssls, vmname, authtoken);

    return (Socket)s;
  }

  private String readArg(String[] args, String name) {

    for (int i = 0; i < args.length; i += 2) {
      if (args[i].equalsIgnoreCase(name)) {
	try {
	  return args[i+1];
	} catch (Exception e) {
	  return null;
	}
      }
    }
    return null;
  }
}

