/************************************************
* Columbia University CS Department
* Network Security Lab
*
* Open and Survivable Embedded Systems (OASES)
*
* Structured Policy Command Language (SPCL)
*
*
* This software is provided as is without any
* warranty or guarantee of merchantibility
* or fitness for a particular purpose. This
* software is released under the terms of the
* GNU General Public License (GPL).
*
* Last updated: March 26, 2003
*
***********************************************/

package spcl.policyengine;

import java.net.*;
import java.io.*;

/** 
 * A basic utility for communicating with
 * the policyengine. Starts up on a
 * port to listen for remote shutdown requests.
 *
 * @author locasto@cs.columbia.edu
 *
*/
public class PolicyEngineConsole implements Runnable{

	private Socket client;
	private ServerSocket server;
	private Thread listener;
	private boolean stop=false;
	private int port;
	private String message;
	private PolicyEngine policyEngine;

	public PolicyEngineConsole(){}

	public void setPolicyEngine( PolicyEngine pe ){ this.policyEngine = pe; }
	public void setPort( int p ){ port = p; }
	public void setMessage( String s ){ message=s; }

	void init() throws Exception{
	  server = new ServerSocket( port, 2, InetAddress.getLocalHost() );
	  listener = new Thread( this );
	  listener.start();
	}

	public void run(){
		String s;
		ObjectInputStream ois;
		ObjectOutputStream oos;

	  //wait for connections telling you to shutdown
	  while( !stop ){
	    listener.yield();

		try{
			
			listener.sleep( 15 );
			client = server.accept();
			ois = new ObjectInputStream( client.getInputStream() );
			oos = new ObjectOutputStream( client.getOutputStream() );
			oos.flush();

				s = (String)ois.readObject();
				if( s.equals( message ) ){
					stop = true;
					policyEngine.shutDown();
				}else{
				  //log attempt and continue
				  System.err.println( "PolicyEngineConsole::run() bad commend="+s );
				}

			ois.close();
			oos.close();
			client.close();
		}catch( Exception e ){
			ois=null;
			oos=null;
			client=null;
		}
	  }
		try{server.close();}catch( Exception ex ){}
	}





}
