Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 195644 | Differences between
and this patch

Collapse All | Expand All

(-)src/org/eclipse/tptp/platform/execution/util/internal/Constants.java (+7 lines)
Lines 103-108 Link Here
103
	public static final long CONNECT_DATA              	=0x10000000;
103
	public static final long CONNECT_DATA              	=0x10000000;
104
	public static final long DATA_CONNECTION_COMPLETE  	=0x20000000;
104
	public static final long DATA_CONNECTION_COMPLETE  	=0x20000000;
105
	public static final long DATA_CONNECTION_REFUSED   	=0x40000000;
105
	public static final long DATA_CONNECTION_REFUSED   	=0x40000000;
106
	
107
	public static final long SECURITY_REQUIRED   		=0x00010000;
108
	public static final long AUTHENTICATE   			=0x00020000;
109
	public static final long AUTHENTICATION_FAILED   	=0x00040000;
110
	public static final long AUTHENTICATION_SUCCESSFUL  =0x00080000;
111
	
106
	public static final long DATA_PATH_SEND				=0x00000001;
112
	public static final long DATA_PATH_SEND				=0x00000001;
107
	public static final long DATA_PATH_RECEIVE 			=0x00000002;
113
	public static final long DATA_PATH_RECEIVE 			=0x00000002;
108
	public static final long DATA_PATH_TWO_WAY 			= DATA_PATH_SEND | DATA_PATH_RECEIVE;
114
	public static final long DATA_PATH_TWO_WAY 			= DATA_PATH_SEND | DATA_PATH_RECEIVE;
Lines 204-209 Link Here
204
	public static final int PROCESS_LAUNCH_TIMEOUT_TRY_COUNT	= 50;
210
	public static final int PROCESS_LAUNCH_TIMEOUT_TRY_COUNT	= 50;
205
	public static final int DSSRVR_LAUNCH_TIMEOUT_TRY_COUNT		= 1000;
211
	public static final int DSSRVR_LAUNCH_TIMEOUT_TRY_COUNT		= 1000;
206
	public static final int CONNECT_TIMEOUT_TRY_COUNT = 32;
212
	public static final int CONNECT_TIMEOUT_TRY_COUNT = 32;
213
	public static final int WAIT_RESPONCE_TIMEOUT = 10000;
207
	
214
	
208
	public static final boolean TPTP_AC					= true;
215
	public static final boolean TPTP_AC					= true;
209
216
(-)src/org/eclipse/tptp/platform/execution/util/internal/AgentControllerPool.java (-91 / +35 lines)
Lines 17-25 Link Here
17
import org.eclipse.tptp.platform.execution.client.core.IAgentController;
17
import org.eclipse.tptp.platform.execution.client.core.IAgentController;
18
import org.eclipse.tptp.platform.execution.client.core.INode;
18
import org.eclipse.tptp.platform.execution.client.core.INode;
19
import org.eclipse.tptp.platform.execution.client.core.NodeFactory;
19
import org.eclipse.tptp.platform.execution.client.core.NodeFactory;
20
import org.eclipse.tptp.platform.execution.client.core.internal.AgentController;
21
import org.eclipse.tptp.platform.execution.exceptions.AgentControllerUnavailableException;
20
import org.eclipse.tptp.platform.execution.exceptions.AgentControllerUnavailableException;
21
import org.eclipse.tptp.platform.execution.exceptions.LoginFailedException;
22
import org.eclipse.tptp.platform.execution.exceptions.NotConnectedException;
22
import org.eclipse.tptp.platform.execution.exceptions.NotConnectedException;
23
import org.eclipse.tptp.platform.execution.client.core.internal.AgentController;
24
import org.eclipse.tptp.platform.execution.exceptions.SecureConnectionRequiredException;
25
import org.eclipse.tptp.platform.execution.security.User;
23
26
24
/**
27
/**
25
 * This delegate is used to keep track of connections with Agent Controller.
28
 * This delegate is used to keep track of connections with Agent Controller.
Lines 29-35 Link Here
29
 * 
32
 * 
30
 * @author Ali Mehregani
33
 * @author Ali Mehregani
31
 */
34
 */
32
public class AgentControllerPool {
35
public class AgentControllerPool {	// may be inherited to provide UI
33
	/**
36
	/**
34
	 * The incremental wait times
37
	 * The incremental wait times
35
	 */
38
	 */
Lines 41-48 Link Here
41
	public static final int TOTAL_WAIT = 100;
44
	public static final int TOTAL_WAIT = 100;
42
45
43
	/* The instance of this class */
46
	/* The instance of this class */
44
	private static AgentControllerPool instance = new AgentControllerPool();
47
	protected static AgentControllerPool instance;
45
48
49
	private IAgentControllerFactory acFactory = null;
46
	/*
50
	/*
47
	 * Keeps track of the connections to Agent Controller KEY = hostname VALUE =
51
	 * Keeps track of the connections to Agent Controller KEY = hostname VALUE =
48
	 * The connection
52
	 * The connection
Lines 61-75 Link Here
61
	/**
65
	/**
62
	 * Hide the construtor
66
	 * Hide the construtor
63
	 */
67
	 */
64
	private AgentControllerPool() {
68
	protected AgentControllerPool() {
65
	}
69
	}
66
70
67
	/**
71
	/**
68
	 * Return the instance of this singleton class
72
	 * Return the instance of this singleton class 
69
	 * 
73
	 * 
70
	 * @return The instance of this class
74
	 * @return The instance of this class
71
	 */
75
	 */
72
	public static AgentControllerPool getInstance() {
76
	public static AgentControllerPool getInstance() {
77
		if (instance == null) instance = new AgentControllerPool();
73
		return instance;
78
		return instance;
74
	}
79
	}
75
80
Lines 94-105 Link Here
94
	 */
99
	 */
95
	public IAgentController getConnection(String hostName, int portNumber,
100
	public IAgentController getConnection(String hostName, int portNumber,
96
			boolean reuseExistingConnection) throws Exception {
101
			boolean reuseExistingConnection) throws Exception {
97
98
		String hostKeyName = AgentStatePool.getUnifiedHostName(hostName);
99
		
102
		
103
		String hostKeyName = AgentStatePool.getUnifiedHostName(hostName);
104
	
100
		/* Attempt to lookup the connection */
105
		/* Attempt to lookup the connection */
101
		IAgentController ac = (IAgentController) connectionPool.get(hostKeyName);
106
		IAgentController ac = (IAgentController) connectionPool.get(hostKeyName);
102
103
		if (ac != null && ac instanceof AgentController) {
107
		if (ac != null && ac instanceof AgentController) {
104
			if (!((AgentController)ac).isConnected()) {
108
			if (!((AgentController)ac).isConnected()) {
105
				connectionPool.remove(hostKeyName);
109
				connectionPool.remove(hostKeyName);
Lines 115-121 Link Here
115
			if (portNumber == connectionInfo.getPort()) {
119
			if (portNumber == connectionInfo.getPort()) {
116
				/* Poke the connection to make sure that it's still alive */
120
				/* Poke the connection to make sure that it's still alive */
117
				isConnectionAlive = false;
121
				isConnectionAlive = false;
118
122
				
119
				try {
123
				try {
120
					final IAgentController agentController = ac;
124
					final IAgentController agentController = ac;
121
					Thread thread = new Thread(new Runnable() {
125
					Thread thread = new Thread(new Runnable() {
Lines 128-134 Link Here
128
							}
132
							}
129
						}
133
						}
130
					});
134
					});
131
					
135
132
					thread.start();
136
					thread.start();
133
					thread.join(TOTAL_WAIT*INCREMENTAL_WAIT);
137
					thread.join(TOTAL_WAIT*INCREMENTAL_WAIT);
134
				} catch (Exception e) {}
138
				} catch (Exception e) {}
Lines 138-237 Link Here
138
				/* Connection is dead - remove it from the connection pool. */
142
				/* Connection is dead - remove it from the connection pool. */
139
				connectionPool.remove(hostKeyName);
143
				connectionPool.remove(hostKeyName);
140
			}
144
			}
141
142
		}
145
		}
143
146
144
		/*
147
		/*
145
		 * A match was not found in our connection pool. Establish a new
148
		 * A match was not found in our connection pool. Establish a new
146
		 * connection
149
		 * connection
147
		 */
150
		 */
148
		final INode node = NodeFactory.createNode(hostName);
149
		final ConnectionInfo connInfo = new ConnectionInfo();
150
151
		connInfo.setHostName(hostName);
152
		connInfo.setPort(portNumber);
153
154
		/*
155
		 * The establishment of the connection should be done in a separate
156
		 * thread.
157
		 */
158
		class EstablishConnection implements Runnable {
159
			private Exception e;
160
			private IAgentController ac;
161
162
			public void run() {
163
				try {
164
					ac = node.connect(connInfo);
165
166
					/* Notify that the connection is done */
167
					synchronized (AgentControllerPool.this) {
168
						AgentControllerPool.this.notify();
169
					}
170
				} catch (Exception e) {
171
					/*
172
					 * For some reason Sun JDK 1.5_06 has problems resolving the
173
					 * hostname "localhost". As a workaround change it to
174
					 * 127.0.0.1
175
					 */
176
					if ("localhost".equals(connInfo.getHostName())) {
177
						connInfo.setHostName("127.0.0.1");
178
					}
179
					try {
180
						ac = node.connect(connInfo);
181
182
						/* Notify that the connection is done */
183
						synchronized (AgentControllerPool.this) {
184
							AgentControllerPool.this.notify();
185
						}
186
					} catch (Exception ex) {
187
					}
188
					this.e = e;
189
				}
190
			}
191
192
			public Exception getException() {
193
				return e;
194
			}
195
151
196
			public IAgentController getConnection() {
152
		ac = createConnection(hostName, portNumber);
197
				return ac;
153
		if (ac == null)	{
198
			}
199
		}
200
		;
201
202
		EstablishConnection establishConnection = new EstablishConnection();
203
		int totalWait = 0;
204
		new Thread(establishConnection).start();
205
206
		/* Wait for a maximum of 10 seconds before bailing out */
207
		while (establishConnection.getConnection() == null
208
				&& totalWait < TOTAL_WAIT
209
				&& establishConnection.getException() == null) {
210
			totalWait++;
211
			synchronized (this) {
212
				try {
213
					wait(INCREMENTAL_WAIT);
214
				} catch (InterruptedException e) {
215
					/* Bail out */
216
					break;
217
				}
218
			}
219
		}
220
221
		/* If any errors occurred, then return it */
222
		Exception error = establishConnection.getException();
223
		if (error != null)
224
			throw error;
225
		ac = establishConnection.getConnection();
226
		if (ac == null)
227
			throw new AgentControllerUnavailableException();
154
			throw new AgentControllerUnavailableException();
228
155
		}
156
		
229
		/* Store and return the connection */
157
		/* Store and return the connection */
230
		connectionPool.put(hostKeyName, ac);
158
		connectionPool.put(hostKeyName, ac);
231
		setPortMapping(hostKeyName, portNumber, ac.getConnectionInfo().getPort());
159
		setPortMapping(hostKeyName, portNumber, ac.getConnectionInfo().getPort());
160
232
		return ac;
161
		return ac;
233
	}
162
	}
234
163
	
235
	private int getPortMapping(String host, int port) {
164
	private int getPortMapping(String host, int port) {
236
		String key = host + ":" + port;
165
		String key = host + ":" + port;
237
		if (portMappings.containsKey(key)) {
166
		if (portMappings.containsKey(key)) {
Lines 245-248 Link Here
245
		String key = host + ":" + port;
174
		String key = host + ":" + port;
246
		portMappings.put(key, new Integer(newPort));
175
		portMappings.put(key, new Integer(newPort));
247
	}
176
	}
177
	
178
	public void setACFactory(IAgentControllerFactory acFactory) {
179
		this.acFactory = acFactory;
180
	}
181
182
	public static void setAgentControllerFactory(IAgentControllerFactory acFactory) {
183
		getInstance().setACFactory(acFactory);
184
	}
185
	
186
	private IAgentController createConnection (String hostName, int portNumber) 
187
		throws Exception {
188
		
189
		if (acFactory == null) acFactory = new AgentControllerFactory();
190
		return acFactory.createConnection(hostName, portNumber);
191
	}
248
}
192
}
(-)src/org/eclipse/tptp/platform/execution/client/core/internal/SecureConnectionImpl.java (-132 / +81 lines)
Lines 1-145 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2006 IBM Corporation, Intel Corporation.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - Initial API and implementation
10
 *    Vishnu K Naikawadi, Intel - Initial API and implementation
11
 *
12
 * $Id$ 
13
 *******************************************************************************/
14
15
package org.eclipse.tptp.platform.execution.client.core.internal;
1
package org.eclipse.tptp.platform.execution.client.core.internal;
16
2
17
18
import java.io.IOException;
3
import java.io.IOException;
19
import java.net.ConnectException;
4
import java.net.Socket;
20
import java.net.InetAddress;
21
import java.security.KeyManagementException;
22
import java.security.NoSuchAlgorithmException;
23
import java.security.Security;
24
25
import javax.net.ssl.HandshakeCompletedEvent;
26
import javax.net.ssl.HandshakeCompletedListener;
27
import javax.net.ssl.SSLSession;
28
import javax.net.ssl.SSLSocket;
29
import javax.net.ssl.SSLSocketFactory;
30
31
import org.eclipse.tptp.platform.execution.client.core.*;
32
import org.eclipse.tptp.platform.execution.security.*;
33
import org.eclipse.tptp.platform.execution.exceptions.*;
34
import org.eclipse.tptp.platform.execution.util.internal.*;
35
36
5
37
import javax.net.ssl.SSLContext;
6
import javax.net.ssl.SSLContext;
7
import javax.net.ssl.SSLSocket;
8
import javax.net.ssl.TrustManager;
9
10
import org.eclipse.tptp.platform.execution.client.core.INode;
11
import org.eclipse.tptp.platform.execution.exceptions.LoginFailedException;
12
import org.eclipse.tptp.platform.execution.exceptions.ReconnectRequestedException;
13
import org.eclipse.tptp.platform.execution.exceptions.SecureConnectionRequiredException;
14
import org.eclipse.tptp.platform.execution.exceptions.UntrustedAgentControllerException;
38
15
39
public class SecureConnectionImpl extends ConnectionImpl {
16
public class SecureConnectionImpl extends ConnectionImpl {
40
	
17
    private SSLSocket initSSL (Socket socket) throws IOException {
41
	private boolean handshakeSuccess;
18
    	if (socket == null || !socket.isConnected()) return null;
19
    	
20
		TrustManager tms[] = null;
21
		try {
22
			X509TrustManagerImpl tm = new X509TrustManagerImpl();
23
			tms = new TrustManager[1];
24
			tms[0] = tm;
25
		} catch (Exception e) {}
26
		
27
		SSLContext sslCtx;
28
		try {
29
			sslCtx = SSLContext.getInstance("SSL");
30
			sslCtx.init(null, tms, null);
31
		}
32
		catch(Exception e) {
33
			sslCtx = null;
34
		}
35
		
36
		if (sslCtx == null) return null;
37
		
38
		String host = socket.getInetAddress().getHostAddress();
39
		int port = socket.getPort();
40
		
41
		SSLSocket sslSocket = (SSLSocket) sslCtx.getSocketFactory().createSocket(socket, host, port, true);
42
		sslSocket.setUseClientMode(true);
42
43
43
    public SecureConnectionImpl() {
44
		sslSocket.startHandshake();
44
        super();
45
    }
46
45
47
    public void connect(INode node, SecureConnectionInfo connInfo) throws IOException, SecureConnectionRequiredException, LoginFailedException, UntrustedAgentControllerException, ReconnectRequestedException {
46
		if (sslSocket.getSession() == null) return null;
48
        _port = connInfo.getPort();
49
        int offset = 0;
50
        InetAddress[] addrs = node.getAllInetAddresses();
51
        int protocolOffset = 0;
52
        ISecureClientParameters ClientSecureParams = connInfo.getSecureClientParameters();
53
        
54
        /* Determine our acceptable protocols */
55
		String[] sslProtocols = ClientSecureParams.getEnabledProtocols();
56
		if(sslProtocols==null) {
57
			sslProtocols=new String[] {"SSL"};
58
		}
59
		
47
		
60
        do {
48
		return sslSocket;
61
            /* Connect to the remote machine */
62
            try {
63
                /* Attach using SSL and initiate a handshake */
64
                SSLContext sslContext = SSLContext.getInstance(sslProtocols[protocolOffset]/*,node.getSecurityParameters().getSecurityProvider()*/);
65
                //Commented the line below to support security for the RAC since it is not part of the new API
66
                //sslContext.init(ClientSecureParams.getKeystoreManager().getKeyManagers(), node.getAgentController(_port).getSecurityParameters().getKeystoreManager().getTrustManagers(), null);
67
68
                if (sslContext == null) {
69
                    Security.addProvider(ClientSecureParams.getSecurityProvider());
70
71
                    _socket = SSLSocketFactory.getDefault().createSocket(addrs[offset], _port);
72
                    ((SSLSocket) _socket).addHandshakeCompletedListener(new HandshakeCompletedListener() {
73
                        public void handshakeCompleted(HandshakeCompletedEvent e) {	
74
                        }
75
                    });
76
77
                    ((SSLSocket) _socket).startHandshake();
78
                }
79
                else {
80
                    _socket = sslContext.getSocketFactory().createSocket(addrs[offset], _port);
81
                    ((SSLSocket) _socket).addHandshakeCompletedListener(new HandshakeCompletedListener() {
82
                        public void handshakeCompleted(HandshakeCompletedEvent e) {	
83
                        }
84
                    });
85
                }
86
                
87
				String[] cyphers=ClientSecureParams.getEnabledCipherSuites();
88
				if(cyphers!=null) {
89
					((SSLSocket) _socket).setEnabledCipherSuites(ClientSecureParams.getEnabledCipherSuites());
90
				}
91
				else {
92
					((SSLSocket) _socket).setEnabledCipherSuites(((SSLSocket)_socket).getSupportedCipherSuites());
93
				}
94
				((SSLSocket) _socket).setUseClientMode(true);
95
                
96
				//((SSLSocket) _socket).startHandshake();
97
98
                /* The underlying JSSE code returns the SSL socket before all
99
                 * the SSL handshakes, including client authentication, are
100
                 * completed.  The handshake carries on, asynchronously, in
101
                 * the background. If the handshake fails then the socket is
102
                 * not usable. We synchronize things by calling getSession()
103
                 * on the SSL socket.  The thread calling getSession() is
104
                 * forced to wait until the underlying SSL handshake is completed,
105
                 *  and if the handshake fails then getSession() returns a null.
106
                 */
107
                SSLSession session = ((SSLSocket) _socket).getSession();
108
109
                /* If we could not establish a session we should throw an exception */
110
                if (session==null) {
111
                    throw new UntrustedAgentControllerException(Constants.TPTP_PLATFORM_EXEC_MSG39);
112
                }
113
                if(session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")) {
114
					throw new UntrustedAgentControllerException(Constants.TPTP_PLATFORM_EXEC_MSG39);
115
                }
116
				break;
117
            }
118
            catch (ConnectException e) {
119
                offset++;
120
                if (offset == addrs.length) {
121
                    throw e;
122
                }
123
                /* Reset protocol offset */
124
                protocolOffset = 0;
125
            }
126
            catch (NoSuchAlgorithmException e) {
127
                /* Try another protocol if there are any left */
128
                protocolOffset++;
129
                if (protocolOffset == sslProtocols.length) {
130
                    throw new ConnectException(Constants.TPTP_PLATFORM_EXEC_MSG40);
131
                }
132
            }
133
            //Commented the exception block below to allow for security - not implemented in the AC 
134
//            catch (KeyManagementException e) {
135
//                /* We need to handle this */
136
//            }
137
        }
138
        while (offset < addrs.length);
139
140
        sendConnectCommand();
141
        _node = node;
142
        this.init();
143
    }
49
    }
50
    
51
    public boolean connect(INode node, ConnectionImpl con) throws IOException, UntrustedAgentControllerException, 
52
    	ReconnectRequestedException, SecureConnectionRequiredException, LoginFailedException {
53
54
    	if (con == null) return false;
55
    	Socket socket = con.getSocket();
56
    	if (socket == null || !socket.isConnected()) return false;
57
    	
58
    	con.setSocket(null);	// to save socket from garbage collecting
59
    	
60
		setSoTimeout(socket.getSoTimeout());
61
		_node = node;
62
		_port = socket.getPort();
63
		inetAddress = socket.getInetAddress();
64
			
65
		SSLSocket sslSocket = initSSL(socket);
66
		if (sslSocket == null) return false;
67
		
68
		setSocket (sslSocket);
144
69
70
		init();		// to complete connection establishment
71
		
72
		return true;
73
    }
74
    
75
	public int createDataConnection(int direction) throws IOException, SecureConnectionRequiredException {
76
		Socket dataSock = connectSocket();
77
		if (dataSock == null) throw new IOException();
78
79
		int dataConnectionId = -1;
80
		boolean securityRequired = false;
81
82
		try {
83
			dataConnectionId = initDataConnection(dataSock, direction);
84
		} catch (SecureConnectionRequiredException e) {
85
			securityRequired = true;
86
		}
87
		
88
		if (!securityRequired) return dataConnectionId;
89
		
90
		SSLSocket sslDataSock = initSSL(dataSock);
91
		
92
		return initDataConnection(sslDataSock, direction);
93
	}
145
}
94
}
(-)src/org/eclipse/tptp/platform/execution/client/core/internal/NodeImpl.java (-57 / +34 lines)
Lines 14-41 Link Here
14
14
15
package org.eclipse.tptp.platform.execution.client.core.internal;
15
package org.eclipse.tptp.platform.execution.client.core.internal;
16
16
17
import java.io.IOException;
18
import java.net.InetAddress;
17
import java.net.InetAddress;
19
import java.net.UnknownHostException;
18
import java.net.UnknownHostException;
20
import java.util.Enumeration;
21
import java.util.Hashtable;
19
import java.util.Hashtable;
22
import java.util.Vector;
20
import java.util.Vector;
23
21
24
import org.eclipse.core.runtime.Platform;
22
import org.eclipse.core.runtime.Platform;
25
import org.eclipse.tptp.platform.execution.client.core.*;
23
import org.eclipse.tptp.platform.execution.client.core.*;
26
import org.eclipse.tptp.platform.execution.util.*;
27
import org.eclipse.tptp.platform.execution.util.internal.*;
24
import org.eclipse.tptp.platform.execution.util.internal.*;
28
import org.eclipse.tptp.platform.execution.security.*;
25
import org.eclipse.tptp.platform.execution.security.*;
29
import org.eclipse.tptp.platform.execution.exceptions.*;
26
import org.eclipse.tptp.platform.execution.exceptions.*;
30
import org.eclipse.tptp.platform.iac.administrator.internal.startstop.AutoStartStop;
27
import org.eclipse.tptp.platform.iac.administrator.internal.startstop.AutoStartStop;
31
import org.osgi.framework.Bundle;
28
import org.osgi.framework.Bundle;
32
29
33
34
35
public class NodeImpl implements INode {
30
public class NodeImpl implements INode {
36
37
    private static final int DEFAULT_LIST_PROCESS_TIMEOUT = 7000;
38
39
	protected String _name;
31
	protected String _name;
40
	protected InetAddress[] _addr;
32
	protected InetAddress[] _addr;
41
	protected Vector _listeners=new Vector(10);
33
	protected Vector _listeners=new Vector(10);
Lines 53-62 Link Here
53
		try {
45
		try {
54
			_addr=InetAddress.getAllByName(addr.getHostName());
46
			_addr=InetAddress.getAllByName(addr.getHostName());
55
		}
47
		}
56
		catch(Exception e) {
48
		catch(Exception e) {}
57
58
		}
59
60
	}
49
	}
61
50
62
	public NodeImpl(String name, InetAddress[] addr) {
51
	public NodeImpl(String name, InetAddress[] addr) {
Lines 95-105 Link Here
95
	 * @see Node#isConnected()
84
	 * @see Node#isConnected()
96
	 */
85
	 */
97
	public boolean isConnected() {
86
	public boolean isConnected() {
98
		if(_ac!=null) {
87
		return _ac != null;
99
			//return _ac.isActive();
100
			return true;
101
		}
102
		return false;
103
	}
88
	}
104
89
105
	/**
90
	/**
Lines 120-191 Link Here
120
			
105
			
121
		IConnection _connection = null;
106
		IConnection _connection = null;
122
		int tryCount = 0;
107
		int tryCount = 0;
123
		int ret = -1;
108
		if(_ac == null) {
124
		if(_ac==null) 
109
			do {
125
		{
110
				try {
126
			do
111
					_connection = ConnectionFactory.createConnection(this, connInfo); 
127
			{
112
					if (tryCount == Constants.CONNECT_TIMEOUT_TRY_COUNT) {
128
				try 
129
				{
130
					_connection=new ConnectionImpl();
131
					_connection.connect(this, connInfo);					
132
					if (tryCount == Constants.CONNECT_TIMEOUT_TRY_COUNT)
133
					{
134
						throw new TimeoutException(Constants.TPTP_PLATFORM_EXEC_MSG21);
113
						throw new TimeoutException(Constants.TPTP_PLATFORM_EXEC_MSG21);
135
					}
114
					}
136
					tryCount++;
115
					tryCount++;
137
				}
116
				}
117
				catch (LoginFailedException e) {
118
					throw e;
119
				}
138
				catch (ReconnectRequestedException e) {
120
				catch (ReconnectRequestedException e) {
139
					connInfo.setPort(e.getReconnectPort());
121
					connInfo.setPort(e.getReconnectPort());
140
					tryCount = 0;
122
					tryCount = 0;
141
					_connection=null;
123
					_connection=null;
142
				}
124
				}
143
				catch(Exception e) {
125
				catch(Exception e) {
144
					_connection=null;
126
					_connection = null;
145
					if (Constants.TPTP_DEBUG) System.out.println("The NodeIml connect exception - " + e);
127
					if (Constants.TPTP_DEBUG) System.out.println("The NodeIml connect exception - " + e);
146
					throw new AgentControllerUnavailableException(Constants.TPTP_PLATFORM_EXEC_MSG22 + e.getMessage());
128
					throw new AgentControllerUnavailableException(Constants.TPTP_PLATFORM_EXEC_MSG22 + e.getMessage());
147
				}
129
				}
148
			}
130
			}
149
			while(_connection == null);
131
			while(_connection == null);
150
		}
132
		}
151
		if(_connection != null)
133
		
152
		{
134
		if(_connection != null) {
153
			_ac = new AgentController(this, connInfo);
135
			_ac = new AgentController(this, connInfo);
154
			((AgentController)_ac).setConnection(_connection);
136
			((AgentController)_ac).setConnection(_connection);
155
			return _ac;
137
		} 
156
		}
157
		
138
		
158
		return _ac;
139
		return _ac;
159
	}
140
	}
160
	
141
	
161
	public synchronized IAgentController connect(ConnectionInfo connInfo, User user) throws AgentControllerUnavailableException, SecureConnectionRequiredException, UntrustedAgentControllerException, LoginFailedException
142
	public synchronized IAgentController connect(ConnectionInfo connInfo, User user) throws AgentControllerUnavailableException, SecureConnectionRequiredException, UntrustedAgentControllerException, LoginFailedException	{
162
	{
143
		if (!isConnected()) {
163
		boolean userAuthenticated = false;
144
			connect(connInfo);
164
		connect(connInfo);
165
		
166
		try 
167
		{
168
			if (_ac != null)
169
			{
170
				userAuthenticated = _ac.authenticateUser(user);
171
			}
172
			
173
			if (userAuthenticated)
174
			{
175
				return _ac;
176
			}
177
		}
145
		}
178
		catch(Exception e) 
179
		{
180
			
146
			
181
			throw new AgentControllerUnavailableException(Constants.TPTP_PLATFORM_EXEC_MSG22);
147
		if (_ac == null) return null;
182
		}
183
		
148
		
184
		return null;
149
		try {
150
			_ac.authenticateUser(user);
151
		} catch (Exception e) {
152
			e.printStackTrace();
153
			throw new AgentControllerUnavailableException();
154
		}
155
156
		return _ac;
185
	}
157
	}
186
	
158
	
187
	public IAgentController getAgentController(int port)
159
	public IAgentController getAgentController(int port) {
188
	{
189
		return _ac;
160
		return _ac;
190
	}
161
	}
191
	
162
	
Lines 204-208 Link Here
204
175
205
		return isLocal;
176
		return isLocal;
206
	}
177
	}
178
	
179
	public void disconnect() {
180
		if (_ac != null) { 
181
			_ac.disconnect();  
182
			_ac = null; 
183
		}
184
	}
207
}
185
}
208
(-)src/org/eclipse/tptp/platform/execution/client/core/internal/AgentController.java (-192 / +106 lines)
Lines 57-87 Link Here
57
	private INode 		   _node 			= null;
57
	private INode 		   _node 			= null;
58
	private ISecureClientParameters _secureClientParameters = null;
58
	private ISecureClientParameters _secureClientParameters = null;
59
	private User		   _user 			= null;
59
	private User		   _user 			= null;
60
	private String		   Version			= null;
61
	
60
	
62
	public Hashtable		_processList 	= new Hashtable();
61
	public Hashtable		_processList 	= new Hashtable();
63
	public Hashtable		_agentList 		= new Hashtable();
62
	public Hashtable		_agentList 		= new Hashtable();
64
	
63
	
65
	private boolean			TPTP_AC 		= true;
64
	private boolean			TPTP_AC 		= true;
66
	private int				_destID 		= Constants.AC_DEST_ID;
67
	private IConnection		_connection 	= null;
65
	private IConnection		_connection 	= null;
68
	private int 			_sourceID 		= 0;
66
	private int 			_sourceID 		= 0;
69
	private IProcess		_process		= null;
70
	private IAgent			_agent			= null;
71
	//The recvd variable names used for the workaround for the innerclasses - Has to be replaced
72
	private String 			receivedAgentName 	= null;
73
	private String 			receivedAgentMetaData = null;
74
	private int				_procCntlr_DestId 	= -1;
75
	private int				_consoleDataConnID 	= -1;
67
	private int				_consoleDataConnID 	= -1;
76
	private ConsoleDataProcessor	_consoleMapper = null;
68
	private ConsoleDataProcessor	_consoleMapper = null;
77
	//listprocessWaitingCommandCount is for RAC
78
	//Do we need it for AC/
79
	private long 			_listProcessesWaitingCommandCount	= 0;
80
	private String 			DELIMIT_TOKEN = " ";
69
	private String 			DELIMIT_TOKEN = " ";
81
	private FileTransferManagerImpl _fileTransferManager = null;
70
	private FileTransferManagerImpl _fileTransferManager = null;
82
	final private static String FILE_TRANSFER_AGENT = "org.eclipse.tptp.FileTransferAgent";
71
	final private static String FILE_TRANSFER_AGENT = "org.eclipse.tptp.FileTransferAgent";
83
	//generic context used for ac events that do not have a ctxt to respond to 
72
	//generic context used for ac events that do not have a ctxt to respond to 
84
	private int				_genericcontext = -1;
85
	
73
	
86
	public AgentController(INode node,ConnectionInfo conninfo)
74
	public AgentController(INode node,ConnectionInfo conninfo)
87
	{
75
	{
Lines 121-215 Link Here
121
		return _connection.getNextContextId();
109
		return _connection.getNextContextId();
122
	}
110
	}
123
	
111
	
124
	public void disconnect()
112
	public void disconnect() {
125
	{
113
		if (_connection != null) {
126
		_connection.disconnect();
114
			_connection.disconnect();
115
			_connection = null;
116
		}
127
	}
117
	}
128
118
129
	/*
119
	/*
130
	 * Authenticate the User Credentials with AC
120
	 * Authenticate the User Credentials with AC
131
	 *
121
	 *
132
	 */
122
	 */
133
	public boolean authenticateUser(User user) throws NotConnectedException
123
	public boolean authenticateUser(User user) throws NotConnectedException {
134
	{
124
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG6);
135
		boolean userAuthenticated = false;
136
		final Object _launcherLock 	= new Object();
137
		final Object _eclipseLock 	= new Object();
138
		boolean _requireEclipseLock = false;
139
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG6);
140
		IAgent[] retagent = null;
141
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
142
125
143
		synchronized(_launcherLock) 
126
		return ((ConnectionImpl)_connection).authenticateUser(user);
144
		{
145
 		   	_requireEclipseLock=false;
146
			StringBuffer AuthenticateUserCommand = new StringBuffer("");
147
			try
148
			{					
149
				AuthenticateUserCommand.append("<authenticateUser iid=\"org.eclipse.tptp.agentManager\"><userName>");
150
				AuthenticateUserCommand.append(user.getName());
151
				AuthenticateUserCommand.append("</userName><password>");
152
				AuthenticateUserCommand.append(user.getPassword());
153
				AuthenticateUserCommand.append("</password></authenticateUser>");
154
			   	this.sendCommand(AuthenticateUserCommand.toString(), Constants.AC_DEST_ID, new ICommandHandler()
155
			   	{
156
			   		public void incomingCommand(INode node, ICommandElement command)
157
			   		{
158
			   			genCmdHandler.setCommandElement(command);
159
			   		}
160
			   	});
161
				_requireEclipseLock=true;
162
				_launcherLock.wait(Constants.TIMEOUT_PERIOD);
163
			}
164
			catch(InterruptedException e) 
165
			{
166
				e.printStackTrace();
167
			}
168
			catch(Exception e)
169
			{
170
				e.printStackTrace();
171
			}
172
		}
173
	 	if (genCmdHandler.getCommandElement() != null) 
174
		{
175
		 	String commandStr = ((CommandFragment)genCmdHandler.getCommandElement()).getCommandData();
176
			TPTPXMLParse ParseObj = new TPTPXMLParse();
177
			ParseObj.setParser(commandStr);
178
			Hashtable CommandHash = ParseObj.getHashTable();
179
			if (CommandHash.containsKey("userAuthenticated"))
180
			{
181
				userAuthenticated = true;
182
			}
183
			else if (CommandHash.containsKey("authenticationFailed"))
184
			{
185
				userAuthenticated = false;
186
			}
187
		}
188
		return userAuthenticated;
189
	}
127
	}
190
	
128
	
191
	/* (non-Javadoc)
129
	/* (non-Javadoc)
192
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#getAgent(java.lang.String, java.lang.String)
130
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#getAgent(java.lang.String, java.lang.String)
193
	 */
131
	 */
194
	public IAgent getAgent(String agentName, String agentClassName)
132
	public IAgent getAgent(String agentName, String agentClassName)
195
			throws NotConnectedException 
133
			throws NotConnectedException {
196
	{
197
		//if the agent is not created by the AC then the default is to create one
198
		boolean createNew = false;
199
		return getAgent(agentName, agentClassName, TPTPAgentAccess.TPTP_CONTROLLER_ACCESS);
134
		return getAgent(agentName, agentClassName, TPTPAgentAccess.TPTP_CONTROLLER_ACCESS);
200
	}
135
	}
136
	
201
	/* (non-Javadoc)
137
	/* (non-Javadoc)
202
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#getAgent(java.lang.String, java.lang.String, boolean)
138
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#getAgent(java.lang.String, java.lang.String, boolean)
203
	 */
139
	 */
204
	public IAgent getAgent(String agentName, String agentClassName,	TPTPAgentAccess accessMode) throws NotConnectedException 
140
	public IAgent getAgent(String agentName, String agentClassName,	TPTPAgentAccess accessMode) throws NotConnectedException {
205
	{
141
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG7);
206
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG7);
207
		final Object _launcherLock 	= new Object();
208
		final Object _eclipseLock 	= new Object();
209
		boolean _requireEclipseLock = false;
210
		
142
		
211
		int receivedAgentID = -1;
143
		final Object _launcherLock 	= new Object();
212
		final InnerUtil innerutil = new InnerUtil();
213
		
144
		
214
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
145
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
215
		IAgent agent = null;
146
		IAgent agent = null;
Lines 358-369 Link Here
358
	 * Clients should call this method to get the list of deployed agents
289
	 * Clients should call this method to get the list of deployed agents
359
	 * returns the array of agent names
290
	 * returns the array of agent names
360
	 */
291
	 */
361
	public IAgent[] queryDeployedAgents(String interfaceID) throws NotConnectedException
292
	public IAgent[] queryDeployedAgents(String interfaceID) throws NotConnectedException {
362
	{
293
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG8);
363
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG8);
294
364
		final Object _launcherLock 	= new Object();
295
		final Object _launcherLock 	= new Object();
365
		final Object _eclipseLock 	= new Object();
366
		boolean _requireEclipseLock = false;	
367
		
296
		
368
		IAgent[] retagent = null;
297
		IAgent[] retagent = null;
369
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
298
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
Lines 466-477 Link Here
466
	 * TPTP_OBSERVER_ACCESS - Request Observer Access on the Agent
395
	 * TPTP_OBSERVER_ACCESS - Request Observer Access on the Agent
467
	 * TPTP_LOCK_AGENT - Request exclusive usage and others can't share this agent
396
	 * TPTP_LOCK_AGENT - Request exclusive usage and others can't share this agent
468
	 */
397
	 */
469
	private int queryAgentByProcessID(String agentName, long pid) throws NotConnectedException 
398
	private int queryAgentByProcessID(String agentName, long pid) throws NotConnectedException {
470
	{
399
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG9);
471
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG9);
400
472
		final Object _launcherLock 	= new Object();
401
		final Object _launcherLock 	= new Object();
473
		final Object _eclipseLock 	= new Object();
474
		boolean _requireEclipseLock = false;	
475
		
402
		
476
		int token =-1;
403
		int token =-1;
477
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
404
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
Lines 484-493 Link Here
484
		 		   try 
411
		 		   try 
485
				   { 	
412
				   { 	
486
		 		   	org.eclipse.tptp.platform.execution.client.core.internal.commands.QueryRunningAgentsCommand command= new org.eclipse.tptp.platform.execution.client.core.internal.commands.QueryRunningAgentsCommand();
413
		 		   	org.eclipse.tptp.platform.execution.client.core.internal.commands.QueryRunningAgentsCommand command= new org.eclipse.tptp.platform.execution.client.core.internal.commands.QueryRunningAgentsCommand();
487
		 		   	this.sendCommand(command.buildCommand(), Constants.AC_DEST_ID, new ICommandHandler()
414
		 		   	sendCommand(command.buildCommand(), Constants.AC_DEST_ID, new ICommandHandler() {
488
		 		   	{
415
		 		   		public void incomingCommand(INode node, ICommandElement command) {	
489
		 		   		public void incomingCommand(INode node, ICommandElement command)
490
		 		   		{
491
		 		   			genCmdHandler.setCommandElement(command);
416
		 		   			genCmdHandler.setCommandElement(command);
492
		 		   		}
417
		 		   		}
493
		 		   	});
418
		 		   	});
Lines 545-553 Link Here
545
		}
470
		}
546
		return token;
471
		return token;
547
	}
472
	}
548
	public void releaseAgent(int agentID)throws NotConnectedException
473
	public void releaseAgent(int agentID)throws NotConnectedException {
549
	{
474
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG10);
550
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG10);
475
		
551
		if(TPTP_AC)
476
		if(TPTP_AC)
552
		{
477
		{
553
			try
478
			try
Lines 570-581 Link Here
570
		return;
495
		return;
571
	}
496
	}
572
	
497
	
573
	public boolean requestAgentControl(int agentID, int accessMode)throws NotConnectedException
498
	public boolean requestAgentControl(int agentID, int accessMode)throws NotConnectedException	{
574
	{
499
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG11);
500
		
575
		final Object _launcherLock 	= new Object();
501
		final Object _launcherLock 	= new Object();
576
		final Object _eclipseLock 	= new Object();
502
		
577
		boolean _requireEclipseLock = false;
578
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG11);
579
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
503
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
580
		boolean controlgranted = false;
504
		boolean controlgranted = false;
581
		if(TPTP_AC)
505
		if(TPTP_AC)
Lines 647-659 Link Here
647
		}
571
		}
648
	}
572
	}
649
	
573
	
650
	public void releaseAgentControl(int agentID)throws NotConnectedException
574
	public void releaseAgentControl(int agentID)throws NotConnectedException {
651
	{
575
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG12);
652
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG12);
576
653
		if(TPTP_AC)
577
		if(TPTP_AC)	{
654
		{
578
			try	{
655
			try
656
			{
657
	 		   	org.eclipse.tptp.platform.execution.client.core.internal.commands.DetachFromAgentCommand command= new org.eclipse.tptp.platform.execution.client.core.internal.commands.DetachFromAgentCommand(Constants.releaseAgentControl_Cmd, agentID);
579
	 		   	org.eclipse.tptp.platform.execution.client.core.internal.commands.DetachFromAgentCommand command= new org.eclipse.tptp.platform.execution.client.core.internal.commands.DetachFromAgentCommand(Constants.releaseAgentControl_Cmd, agentID);
658
	 		   	this.sendCommand(command.buildCommand(), Constants.AC_DEST_ID, new ICommandHandler()
580
	 		   	this.sendCommand(command.buildCommand(), Constants.AC_DEST_ID, new ICommandHandler()
659
	 		   	{
581
	 		   	{
Lines 843-860 Link Here
843
	{
765
	{
844
		return getAgent(agentName, null, processId);
766
		return getAgent(agentName, null, processId);
845
	}
767
	}
846
	public IAgent getAgent(String agentName, String agentClassName, long processId) throws NotConnectedException
768
	
847
	{
769
	private IAgent cachedAgent=null; 
848
		if(!isConnected()){throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG7);}
770
	
771
	public IAgent getAgent(String agentName, String agentClassName, long processId) throws NotConnectedException {
772
		if(!this.isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG7);
773
849
		IAgent agent = null;
774
		IAgent agent = null;
850
		if (agentClassName != null && agentClassName.equals("org.eclipse.tptp.platform.execution.client.agent.ICollector"))
775
851
		{
776
		if (cachedAgent != null) {
777
			try { 
778
				if (cachedAgent.getProcess().getProcessId() == processId && cachedAgent.getName().equals(agentName)) {
779
					agent = cachedAgent;
780
				}
781
			} catch (Exception e) {}
782
			
783
			if (agent != null) {
784
				return agent;
785
			}
786
		}
787
788
		if (agentClassName != null && agentClassName.equals("org.eclipse.tptp.platform.execution.client.agent.ICollector"))	{
852
			agent = new CollectorImpl(agentName);
789
			agent = new CollectorImpl(agentName);
853
		}
790
		}
854
		else
791
		else {
855
		{
856
			agent = new AgentImpl(agentName);
792
			agent = new AgentImpl(agentName);
857
		}
793
		}
794
858
		IProcess process = this.createProcess();
795
		IProcess process = this.createProcess();
859
		process.setProcessId(processId);
796
		process.setProcessId(processId);
860
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
797
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
Lines 901-906 Link Here
901
	        }
838
	        }
902
			((AgentImpl)agent).setProcess(process);
839
			((AgentImpl)agent).setProcess(process);
903
			process.setAgent(agent);
840
			process.setAgent(agent);
841
			
842
			cachedAgent = agent;
843
			
904
			return agent;
844
			return agent;
905
		 }
845
		 }
906
		catch(Exception e){e.printStackTrace();	return null;}
846
		catch(Exception e){e.printStackTrace();	return null;}
Lines 911-928 Link Here
911
	/* (non-Javadoc)
851
	/* (non-Javadoc)
912
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#listProcesses()
852
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#listProcesses()
913
	 */
853
	 */
914
	public Enumeration listAgents() throws NotConnectedException 
854
	public Enumeration listAgents() throws NotConnectedException {
915
	{
855
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG13);
916
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG13);
917
		return _agentList.elements();
856
		return _agentList.elements();
918
	}
857
	}
919
	
858
	
920
	/* (non-Javadoc)
859
	/* (non-Javadoc)
921
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#listProcesses()
860
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#listProcesses()
922
	 */
861
	 */
923
	public Enumeration listProcesses() throws NotConnectedException 
862
	public Enumeration listProcesses() throws NotConnectedException	{
924
	{
863
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG14);
925
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG14);
926
		return _processList.elements();
864
		return _processList.elements();
927
	}
865
	}
928
866
Lines 930-937 Link Here
930
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#getProcess(java.lang.String)
868
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#getProcess(java.lang.String)
931
	 */
869
	 */
932
	public IProcess getProcess(long processId) throws NotConnectedException {
870
	public IProcess getProcess(long processId) throws NotConnectedException {
933
		if (!isConnected())
871
		if (!isConnected())	throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG15);
934
			throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG15);
935
872
936
		String pkey = String.valueOf(processId);
873
		String pkey = String.valueOf(processId);
937
874
Lines 953-961 Link Here
953
	 */
890
	 */
954
	public String[] queryAvailableAgents(String[] interfaceID) throws NotConnectedException {
891
	public String[] queryAvailableAgents(String[] interfaceID) throws NotConnectedException {
955
		if(!TPTP_AC) return null;
892
		if(!TPTP_AC) return null;
956
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG16); 
893
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG16);
957
894
958
		final Object responceLock = new Object();
895
		final Object responseLock = new Object();
959
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
896
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
960
		
897
		
961
		QueryAvailableAgntCommand command= new QueryAvailableAgntCommand();
898
		QueryAvailableAgntCommand command= new QueryAvailableAgntCommand();
Lines 966-972 Link Here
966
		 	sendCommand(command.buildCommand(),Constants.AC_DEST_ID,new ICommandHandler() {
903
		 	sendCommand(command.buildCommand(),Constants.AC_DEST_ID,new ICommandHandler() {
967
		 		public void incomingCommand(INode node, ICommandElement command) {
904
		 		public void incomingCommand(INode node, ICommandElement command) {
968
		 			genCmdHandler.setCommandElement(command);
905
		 			genCmdHandler.setCommandElement(command);
969
		 			synchronized(responceLock) { responceLock.notifyAll(); }
906
		 			synchronized(responseLock) { responseLock.notifyAll(); }
970
				}
907
				}
971
			});
908
			});
972
		} catch(Exception e) {
909
		} catch(Exception e) {
Lines 975-984 Link Here
975
	 			   		
912
	 			   		
976
		if (sendMsgEx != null) throw new NotConnectedException(sendMsgEx.getMessage()); 
913
		if (sendMsgEx != null) throw new NotConnectedException(sendMsgEx.getMessage()); 
977
914
978
		synchronized(responceLock) {
915
		synchronized(responseLock) {
979
	 	    if (genCmdHandler.getCommandElement() == null) {
916
	 	    if (genCmdHandler.getCommandElement() == null) {
980
	 	    	try {
917
	 	    	try {
981
	 	    		responceLock.wait(Constants.PROCESS_LAUNCH_TIMEOUT_TRY_COUNT*Constants.TIMEOUT_PERIOD);
918
	 	    		responseLock.wait(Constants.PROCESS_LAUNCH_TIMEOUT_TRY_COUNT*Constants.TIMEOUT_PERIOD);
982
	 	    	} catch (Exception e) {}
919
	 	    	} catch (Exception e) {}
983
	 	    }
920
	 	    }
984
		}
921
		}
Lines 990-1026 Link Here
990
	 	String commandStr = ((CommandFragment)genCmdHandler.getCommandElement()).getCommandData();
927
	 	String commandStr = ((CommandFragment)genCmdHandler.getCommandElement()).getCommandData();
991
		TPTPXMLParse ParseObj = new TPTPXMLParse();
928
		TPTPXMLParse ParseObj = new TPTPXMLParse();
992
		ParseObj.setParser(commandStr);
929
		ParseObj.setParser(commandStr);
993
		Vector	PVector = ParseObj.getVector(); 
930
		Vector	pVector = ParseObj.getVector();
994
		Vector  tempvector = new Vector();
931
		if (pVector == null) return null;
995
			
932
		
996
		for(int i=0; i < PVector.size(); i++) {
933
		String response = null;
997
			if((((Variable)(PVector.elementAt(i))).getName()).equals("agentNames")) {
934
		Iterator it = pVector.iterator();
998
			  	tempvector.add((String)((Variable)(PVector.elementAt(i))).getValue());
935
		while (it.hasNext()) {
999
			 }		
936
			Variable var = (Variable) it.next();
1000
		}
937
			if ("agentNames".equals(var.getName())) {
1001
938
				response = (String) var.getValue();
1002
		String[] retStr = null;
939
				break;
1003
		if (tempvector.size() == 1) {
1004
			String temp = (String)tempvector.elementAt(0);
1005
			if(temp != null) {
1006
				retStr = new String[tempvector.size()];
1007
				retStr = TPTPString.tokenizeString(DELIMIT_TOKEN, temp);
1008
			}
940
			}
1009
		}
941
		}
1010
		 	
942
		
1011
		return retStr;
943
		return (response == null) ? null : TPTPString.tokenizeString(DELIMIT_TOKEN, response);
1012
	}
944
	}
1013
	
945
1014
	public String[] queryAvailableAgents() throws NotConnectedException 
946
	public String[] queryAvailableAgents() throws NotConnectedException	{
1015
	{
1016
		return queryAvailableAgents(null);
947
		return queryAvailableAgents(null);
1017
	}
948
	}
1018
	public IAgent[] queryRunningAgents(String agentName, String[] interfaceID, long pid) throws NotConnectedException
949
	
1019
	{
950
	public IAgent[] queryRunningAgents(String agentName, String[] interfaceID, long pid) throws NotConnectedException {
1020
	    final Object _launcherLock 	= new Object();
951
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG17);
1021
		final Object _eclipseLock 	= new Object();
952
1022
		boolean _requireEclipseLock = false;
953
		final Object _launcherLock 	= new Object();
1023
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG17);
1024
		IAgent[] retagent = null;
954
		IAgent[] retagent = null;
1025
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
955
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
1026
		if(TPTP_AC)
956
		if(TPTP_AC)
Lines 1035-1041 Link Here
1035
		 		   	if(interfaceID != null )command.setAgentInterfaceID(interfaceID.length, interfaceID);
965
		 		   	if(interfaceID != null )command.setAgentInterfaceID(interfaceID.length, interfaceID);
1036
		 		    if(agentName != null )command.setAgentName(agentName);
966
		 		    if(agentName != null )command.setAgentName(agentName);
1037
		 		    if(pid != 0 )command.setProcessId(pid);
967
		 		    if(pid != 0 )command.setProcessId(pid);
1038
		 		    				
968
1039
		 		   	this.sendCommand(command.buildCommand(), Constants.AC_DEST_ID, new ICommandHandler()
969
		 		   	this.sendCommand(command.buildCommand(), Constants.AC_DEST_ID, new ICommandHandler()
1040
		 		   	{
970
		 		   	{
1041
		 		   		public void incomingCommand(INode node, ICommandElement command)
971
		 		   		public void incomingCommand(INode node, ICommandElement command)
Lines 1185-1205 Link Here
1185
	/* (non-Javadoc)
1115
	/* (non-Javadoc)
1186
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#queryRunningAgents()
1116
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#queryRunningAgents()
1187
	 */
1117
	 */
1188
	public IAgent[] queryRunningAgents() throws NotConnectedException 
1118
	public IAgent[] queryRunningAgents() throws NotConnectedException {
1189
	{
1190
	   return queryRunningAgents(null);
1119
	   return queryRunningAgents(null);
1191
	}
1120
	}
1121
	
1192
	/* (non-Javadoc)
1122
	/* (non-Javadoc)
1193
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#getAgentMetadata(java.lang.String)
1123
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#getAgentMetadata(java.lang.String)
1194
	 */
1124
	 */
1195
	public String getAgentMetadata(String agentName)
1125
	public String getAgentMetadata(String agentName) throws NotConnectedException {
1196
			throws NotConnectedException 
1126
		if(!isConnected()) throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG18);
1197
	{
1127
		
1198
		if(!isConnected())throw new NotConnectedException(Constants.TPTP_PLATFORM_EXEC_MSG18);
1199
		final Object _launcherLock 	= new Object();
1128
		final Object _launcherLock 	= new Object();
1200
		final Object _eclipseLock 	= new Object();
1201
		final InnerUtil datarecvd 	= new InnerUtil();
1202
		boolean _requireEclipseLock = false;
1203
		String retagentMetadata = "";
1129
		String retagentMetadata = "";
1204
		
1130
		
1205
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
1131
		final GenericCommandHandler genCmdHandler = new GenericCommandHandler();
Lines 1306-1326 Link Here
1306
	/* (non-Javadoc)
1232
	/* (non-Javadoc)
1307
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#removeEventListener(java.lang.String, org.eclipse.tptp.platform.execution.core.ICommandHandler)
1233
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#removeEventListener(java.lang.String, org.eclipse.tptp.platform.execution.core.ICommandHandler)
1308
	 */
1234
	 */
1309
	public void removeEventListener(String interfaceID,
1235
	public void removeEventListener(String interfaceID,	ICommandHandler eventHandler) {
1310
			ICommandHandler eventHandler) 
1311
	{
1312
		// TODO Auto-generated method stub
1236
		// TODO Auto-generated method stub
1313
	}
1237
	}
1314
1238
1315
	/* (non-Javadoc)
1239
	/* (non-Javadoc)
1316
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#sendCommand(java.lang.String, int, org.eclipse.tptp.platform.execution.core.ICommandHandler)
1240
	 * @see org.eclipse.tptp.platform.execution.core.IAgentController#sendCommand(java.lang.String, int, org.eclipse.tptp.platform.execution.core.ICommandHandler)
1317
	 */
1241
	 */
1318
	public void sendCommand(String cmd, int destID, ICommandHandler handler) throws IOException
1242
	public void sendCommand(String cmd, int destID, ICommandHandler handler) throws IOException {
1319
	{
1320
		ControlMessage message = new ControlMessage();
1243
		ControlMessage message = new ControlMessage();
1321
		message.setMessageType(Constants.TPTP_AC_MESSAGE);
1244
		message.setMessageType(Constants.TPTP_AC_MESSAGE);
1322
		message.setMagicNumber(Constants.AC_MAGIC_NUMBER);
1245
		message.setMagicNumber(Constants.AC_MAGIC_NUMBER);
1323
		message.setFlags(0);
1246
		message.setFlags(0);
1247
			
1324
		CommandFragment cmdFrag = new CommandFragment();
1248
		CommandFragment cmdFrag = new CommandFragment();
1325
		cmdFrag.setDestination(destID);
1249
		cmdFrag.setDestination(destID);
1326
		cmdFrag.setSource(this._sourceID);
1250
		cmdFrag.setSource(this._sourceID);
Lines 1328-1343 Link Here
1328
		cmdFrag.setCommand(cmd);
1252
		cmdFrag.setCommand(cmd);
1329
		cmdFrag.buildCommand();//Build the command in ConnectionImpl::sendMessage as we don't know the context at this place
1253
		cmdFrag.buildCommand();//Build the command in ConnectionImpl::sendMessage as we don't know the context at this place
1330
		message.appendCommand(cmdFrag);
1254
		message.appendCommand(cmdFrag);
1331
1255
			
1332
		if (handler == null)
1256
		if (handler == null) {
1333
		{
1334
			//this.getConnection().sendMessage(message, this.acCommandHandler);
1257
			//this.getConnection().sendMessage(message, this.acCommandHandler);
1335
		}
1258
		}
1336
		else
1259
		else {
1337
		{
1260
			getConnection().sendMessage(message, handler);
1338
			this.getConnection().sendMessage(message, handler);
1339
		}
1261
		}
1340
	}
1262
	}
1263
	
1341
	/** 
1264
	/** 
1342
	 * Sends a command to the specified destination, the command requires a control message object
1265
	 * Sends a command to the specified destination, the command requires a control message object
1343
	 * and a commandhandler 
1266
	 * and a commandhandler 
Lines 1480-1487 Link Here
1480
		
1403
		
1481
	}
1404
	}
1482
	
1405
	
1483
	public void incomingCommand(INode node, ICommandElement command)
1406
	public void incomingCommand(INode node, ICommandElement command) {
1484
	{
1485
	}
1407
	}
1486
	
1408
	
1487
	/*
1409
	/*
Lines 1559-1576 Link Here
1559
		//return _consoleMapper;
1481
		//return _consoleMapper;
1560
		return (new ConsoleDataProcessor());
1482
		return (new ConsoleDataProcessor());
1561
	}
1483
	}
1562
	class InnerUtil
1563
	{
1564
		private Object value;
1565
		public Object getValue()
1566
		{
1567
			return this.value;
1568
		}
1569
		public void setValue(Object value)
1570
		{
1571
			this.value = value;
1572
		}
1573
	}
1574
	
1484
	
1575
	public boolean isConnected() {
1485
	public boolean isConnected() {
1576
		return _connection != null && _connection.isActive();
1486
		return _connection != null && _connection.isActive();
Lines 1583-1586 Link Here
1583
		
1493
		
1584
		return -1;
1494
		return -1;
1585
	}
1495
	}
1496
	
1497
	public boolean isAuthenticated() {
1498
		return _connection != null && ((ConnectionImpl)_connection).isAuthenticated(); 
1499
	}
1586
}
1500
}
(-)src/org/eclipse/tptp/platform/execution/client/core/internal/ConnectionImpl.java (-438 / +437 lines)
Lines 28-33 Link Here
28
import java.util.Hashtable;
28
import java.util.Hashtable;
29
29
30
import org.eclipse.tptp.platform.execution.client.core.*;
30
import org.eclipse.tptp.platform.execution.client.core.*;
31
import org.eclipse.tptp.platform.execution.client.core.internal.commands.AuthenticateCommand;
32
import org.eclipse.tptp.platform.execution.security.User;
31
import org.eclipse.tptp.platform.execution.util.*;
33
import org.eclipse.tptp.platform.execution.util.*;
32
import org.eclipse.tptp.platform.execution.util.internal.CommandFragment;
34
import org.eclipse.tptp.platform.execution.util.internal.CommandFragment;
33
import org.eclipse.tptp.platform.execution.util.internal.Constants;
35
import org.eclipse.tptp.platform.execution.util.internal.Constants;
Lines 37-46 Link Here
37
import org.eclipse.tptp.platform.execution.exceptions.*;
39
import org.eclipse.tptp.platform.execution.exceptions.*;
38
40
39
public class ConnectionImpl implements IConnection {
41
public class ConnectionImpl implements IConnection {
40
41
	protected Socket _socket;
42
	protected Socket _socket;
42
	protected INode _node;
43
	protected INode _node;
43
	protected int _port;
44
	protected int _port;
45
	protected InetAddress inetAddress = null;
44
	
46
	
45
	private int _connectionId = 0;
47
	private int _connectionId = 0;
46
	private int protoVersion = 0;
48
	private int protoVersion = 0;
Lines 52-254 Link Here
52
	private boolean _isComplete = false;
54
	private boolean _isComplete = false;
53
55
54
	private final Vector _listeners = new Vector();
56
	private final Vector _listeners = new Vector();
55
	private final Object _connectionLock = new Object();
56
	private final Object _loginLock = new Object();
57
57
58
	private static final Object writeLock = new Object();
59
	private static final Object writeDataLock = new Object();
58
	private static final Object contextLock = new Object();
60
	private static final Object contextLock = new Object();
59
	private boolean _isInitialized		= false;
61
	private static final Object authLock = new Object();
60
	private boolean _loginPending 		= false;
62
	private boolean _isInitialized = false;
61
	private ReconnectRequestedException _reconnectRequestedException=null;
63
	private boolean isAuthenticated = false;
62
	private SecureConnectionRequiredException _secureConnectionRequiredException=null;
63
	private LoginFailedException _loginFailed=null;
64
64
65
	private int _soTimeout = Constants.TIMEOUT_PERIOD;
65
	private int _soTimeout = Constants.TIMEOUT_PERIOD;
66
66
67
	class DataConnection
67
	class DataConnection {				// it is better to move all processing of data connections to AC or Node
68
	{
69
		private Socket _dataSocket;
68
		private Socket _dataSocket;
70
		private ACTCPDataServer _dataServer;
69
		private ACTCPDataServer _dataServer;
70
		private int dataConnectionId;
71
		
71
		
72
		public void setDataSocket(Socket dataSocket){_dataSocket = dataSocket;}
72
		public void setDataSocket(Socket dataSocket) { _dataSocket = dataSocket; }
73
		public void setDataServer(ACTCPDataServer dataServer){_dataServer = dataServer;}
73
		public void setDataServer(ACTCPDataServer dataServer) { _dataServer = dataServer; }
74
		public Socket getDataSocket(){return _dataSocket;}
74
		public Socket getDataSocket() { return _dataSocket; }
75
		public ACTCPDataServer getDataServer(){return _dataServer;}
75
		public ACTCPDataServer getDataServer() { return _dataServer; }
76
		public int getDataConnectionId() { return dataConnectionId; }
77
		public void setDataconnectionId(int dataConnectionId) { this.dataConnectionId = dataConnectionId; }
76
	}
78
	}
77
	
79
	
78
	public ConnectionImpl() {
80
	public ConnectionImpl() {
79
		super();
80
	}
81
	}
81
	
82
82
	public int getConnectionId()
83
	public int getConnectionId() {
83
	{
84
		return _connectionId;
84
		return this._connectionId;
85
	}
85
	}
86
	
86
	
87
	public boolean isNewAC()
87
	public boolean isNewAC() {
88
	{
89
		return true;
88
		return true;
90
	}
89
	}
91
	
90
	
92
	public long getNextContextId()
91
	public long getNextContextId() {
93
	{
94
		synchronized(contextLock){
92
		synchronized(contextLock){
95
			return _context++;
93
			return _context++;
96
		}
94
		}
97
	
98
	}
95
	}
99
	
96
	
100
	public void addContext(long contextID, ICommandHandler handler)
97
	public void addContext(long contextID, ICommandHandler handler)	{
101
	{
102
		synchronized(contextLock){
98
		synchronized(contextLock){
103
			this._contextMapper.addContext(contextID, handler);
99
			this._contextMapper.addContext(contextID, handler);
104
		}
100
		}
105
	}
101
	}
106
102
107
	public void connect(INode node, ConnectionInfo connInfo) throws IOException, SecureConnectionRequiredException, LoginFailedException, UntrustedAgentControllerException, ReconnectRequestedException
103
	protected Socket connectSocket () throws IOException {
108
	{
104
		if (_node == null) return null;
109
		_port=connInfo.getPort();
105
		return connectSocket(_node.getAllInetAddresses(), _port);
110
		_soTimeout = connInfo.getSoTimeout();
106
	}
111
		int offset=0;
107
	
112
		InetAddress[] addrs=node.getAllInetAddresses();
108
	protected Socket connectSocket (InetAddress addrs[], int port) throws IOException {
109
		if (addrs == null || addrs.length <= 0) return null;
113
110
114
		do {
111
		Socket socket = null;
115
			/* Connect to the remote machine */
116
			try {
117
				if(Constants.TPTP_DEBUG)System.out.println("Connecting to " + addrs[offset] + " at port " + _port);
118
				_socket=new Socket(addrs[offset], _port);
119
				
120
				sendConnectCommand();
121
				break;
122
			}
123
			catch(IOException e) {
124
				offset++;
125
				if (Constants.TPTP_DEBUG)System.out.println(e.getMessage());
126
				if(offset==addrs.length) {
127
					if (Constants.TPTP_DEBUG)System.out.println("Error while connecting to the Agent Controller on " + addrs[offset] + " running at port " + _port);
128
					throw e;
129
				}
130
			}
131
		}while(offset<addrs.length);
132
		_node=node;
133
		
112
		
134
		this.init();
113
		for (int i=0; i<addrs.length; i++) {
114
			if(Constants.TPTP_DEBUG) System.out.println("Connecting to " + addrs[i] + " at port " + _port);
115
			socket = new Socket(addrs[i], port);
116
			socket.setSoTimeout(_soTimeout);
117
			socket.setTcpNoDelay(true);
118
			inetAddress = addrs[i];
119
			break;
120
		}
121
122
		return socket;
123
	}
124
	
125
	public void connect(INode node, ConnectionInfo connInfo) throws IOException, SecureConnectionRequiredException, 
126
		LoginFailedException, UntrustedAgentControllerException, ReconnectRequestedException {
127
		
128
		_soTimeout = connInfo.getSoTimeout();
129
		if (_soTimeout > 0) _soTimeout *= Constants.CONNECT_TIMEOUT_TRY_COUNT;
130
		
131
		_node = node;
132
		_port = connInfo.getPort();
133
		
134
		_socket = connectSocket(node.getAllInetAddresses(), _port); 
135
		if (_socket == null) throw new IOException();
136
137
		init();
135
		
138
		
136
		// We expected to have a connectionID by now.  If we don't, it's because the wait above timed out
139
		// We expected to have a connectionID by now.  If we don't, it's because the wait above timed out
137
		if ( _connectionId == 0 ) {
140
		if (_connectionId == 0) {
138
       		throw new LoginFailedException("Timeout while waiting for connection to complete");
141
       		throw new LoginFailedException("Timeout while waiting for connection to complete");
139
		}
142
		}
140
	}
143
	}
141
	public void connect(INode node, int port) throws IOException, SecureConnectionRequiredException, LoginFailedException, UntrustedAgentControllerException, ReconnectRequestedException
144
	
142
	{
145
	public void connect(INode node, int port) throws IOException, SecureConnectionRequiredException, LoginFailedException, UntrustedAgentControllerException, ReconnectRequestedException {
143
		ConnectionInfo connInfo = new ConnectionInfo();
146
		ConnectionInfo connInfo = new ConnectionInfo();
144
		connInfo.setPort(port);
147
		connInfo.setPort(port);
145
		connect( node, connInfo );
148
		connect(node, connInfo);
146
	}
147
	
148
	protected void sendConnectCommand() throws IOException
149
	{
150
		if(Constants.TPTP_DEBUG)System.out.println("The AC is New");					
151
		sendControlCommand(Constants.CONNECT);
152
	}
149
	}
153
150
154
151
	protected void init() throws SecureConnectionRequiredException, LoginFailedException, IOException, ReconnectRequestedException {
155
	/* Init */
152
		_contextMapper = new ContextMapper();
156
	protected void init() throws SecureConnectionRequiredException, LoginFailedException, IOException, ReconnectRequestedException
157
	{
158
		try 
159
		{
160
			_socket.setSoTimeout(_soTimeout);
161
			_socket.setTcpNoDelay(true);
162
		}
163
		catch(SocketException e) {
164
			/* We can ignore this */
165
		}
166
167
		_contextMapper=new ContextMapper();
168
		_dataConnectionMap = new Hashtable();
153
		_dataConnectionMap = new Hashtable();
169
		_cmdHandler=new ICommandHandler() 
154
		
170
		{
155
		_cmdHandler = new ICommandHandler() {
171
			public void incomingCommand(INode node, ICommandElement command) 
156
			public void incomingCommand(INode node, ICommandElement command) {
172
			{
173
				handleACCommands(command);
157
				handleACCommands(command);
174
			}
158
			}
175
		};
159
		};
176
160
177
		/* RKD:  With the V5 RAC it first accepts the socket connection and then determines is the connection
161
		sendControlCommand(Constants.CONNECT);
178
		 * is allowed.  If the connection is not allowed the the connection is cut.  We need to first connect
162
179
		 * and then determine if we have been cut off.  The connection has already occurred above us in the
163
		byte rbuf[] = new byte[512];
180
		 * stack.  We then will wait until either a read timeout has occured on the reader thread or the
164
		BufferedInputStream inStream = new BufferedInputStream(_socket.getInputStream());
181
		 * connection gets cut by the other side.
165
		int offset = 0;
182
		 */
166
183
167
		while (true) {
184
		synchronized(_connectionLock) {
168
			int bytesRead = inStream.read(rbuf, offset, rbuf.length-offset);
185
			SocketReaderThread reader=new SocketReaderThread();
169
186
			reader.setName(_node.getName()+"_connection");
170
			if(bytesRead < 0) break;
187
			reader.setDaemon(true);
171
188
			reader.start();
172
	        if (offset > 0) {
189
			try 
173
	        	bytesRead += offset;
190
			{
174
				offset = 0;
191
				_connectionLock.wait();
175
	        }
192
			}
176
			
193
			catch(InterruptedException e){e.printStackTrace();}
177
			 // If we've tried to connect to a backward compatibility
194
178
			 // layer of the AC, we'll immediately get a response in 
195
			_isInitialized=true;
179
			 // RAC format.  If we ignore this, the BC layer will
196
180
			 // respond to our first message by giving us the port
197
			if (_reconnectRequestedException!=null) {
181
			 // to connect to the regular socket TL.
198
				ReconnectRequestedException temp=_reconnectRequestedException;
182
			 //
199
				_reconnectRequestedException = null;
183
	        
200
				throw temp;
184
			int v = checkForRACMessage(rbuf, offset);
185
			if(v >= 0) {
186
				// We read the header, the next four bytes will be the length 
187
				// (including the header) of the RAC message
188
				int len = (int) TPTPMessageUtil.readTPTPLongFromBuffer(rbuf, v);
189
				if (len == bytesRead) {
190
					offset = 0;
191
					continue;
192
				}
193
				
194
				if (len > bytesRead) {
195
					inStream.skip(len - bytesRead);
196
					offset = 0;
197
					continue;
198
				}
199
200
				offset = len;
201
			}
202
203
				// First we make sure we have at least enough read for the message header.
204
				  // If not, compress and re-read.
205
			//
206
			if (bytesRead-offset < Constants.AC_MESSAGE_HEADER_SIZE) {
207
				System.arraycopy(rbuf, offset, rbuf, 0, bytesRead-offset);
208
				offset = bytesRead - offset;
209
				continue;
201
			}
210
			}
202
			
211
			
203
			/* If this connection has a pending exception because the server is secure we need to throw the
212
				// We have the header information, now lets try and get the entire message.  Once
204
			 * exception so that the caller can create a new connection with the proper security settings.
213
				 //  again the same error conditions can occur.
205
			 */
214
				//
206
			if(_secureConnectionRequiredException!=null) {
215
				//System.out.println("Offset xx::"+new String(buffer));
207
				SecureConnectionRequiredException temp=_secureConnectionRequiredException;
216
208
				_secureConnectionRequiredException=null;
217
			ControlMessage msg=new ControlMessage();
209
				_loginPending=false;
218
			msg.setMessageType(Constants.TPTP_AC_MESSAGE);
210
				throw temp;
219
			int current;
220
				
221
			try {
222
				if (rbuf.length == bytesRead + offset) {
223
					current = msg.readFromBuffer(rbuf, offset);
224
				}
225
				else {
226
					// length is not passed to readFromBuffer so we should ensure 
227
					// that readFromBuffer will not read trash from the end of the buffer
228
					// and no exception will be thrown.
229
					// ControlMessage.readFromBuffer(buffer, offset, length) method
230
					// is needed in order to prevent extra memory allocations in this case.
231
					byte[] buffer2 = new byte[bytesRead];
232
					System.arraycopy(rbuf, offset, buffer2, 0, bytesRead);
233
					current = msg.readFromBuffer(buffer2, 0);
234
				}
235
			} catch (Exception e) {
236
				throw new IOException();
211
			}
237
			}
238
			
239
			long flags = msg.getFlags();
240
			if ((flags & Constants.CONNECTION_COMPLETE) != 0) {
241
				isAuthenticated = (flags & Constants.AUTHENTICATION_FAILED) == 0;
242
				
243
	    		int cmdOffset = 0;
244
	    		_connectionId = extractConnectionId(rbuf, current+cmdOffset);
245
	    		cmdOffset += 4;
212
246
213
			synchronized(_loginLock) {
247
		    	int uuidLen = (int) TPTPMessageUtil.readTPTPLongFromBuffer(rbuf, current+cmdOffset);
214
				if(_loginPending) {
248
	    		cmdOffset += 4 + uuidLen + 1;	// including trailing null
215
					try {
249
		    		
216
						_loginLock.wait();
250
	    		if ((cmdOffset + 4) <= msg.getLength()) { 	// check if protoVersion is available
251
	    			protoVersion = (int) TPTPMessageUtil.readTPTPLongFromBuffer(rbuf, current+cmdOffset);
252
	    		}
253
				
254
	    		if (Constants.TPTP_DEBUG) System.out.println("Connection complete response - " + _connectionId + ", protoVer=" + protoVersion);
255
	    		
256
				break;
257
			}								// equals - since CONNECTION_RECONNECT_REQUEST has two bits set
258
			else if ((flags & Constants.CONNECTION_REFUSED) != 0) {
259
				if ((flags & Constants.SECURITY_REQUIRED) != 0) {
260
					throw new SecureConnectionRequiredException();
261
				}
262
				else if((flags & Constants.CONNECTION_RECONNECT_REQUEST) == Constants.CONNECTION_RECONNECT_REQUEST) {
263
					int portreq = -1;
264
	    		
265
					try	{
266
						close();
267
						CommandFragment cmd = (CommandFragment)msg.getCommand(0);
268
						String strToParse = cmd.getCommandData();
269
						TPTPXMLParse ParseObj = new TPTPXMLParse();
270
						ParseObj.setParser(strToParse.trim());
271
						Hashtable CommandHash = ParseObj.getHashTable();
272
						if(CommandHash.containsKey("port")) {
273
							portreq = Integer.parseInt((String)ParseObj.getHashTable().get("port"));
274
						}
217
					}
275
					}
218
					catch(InterruptedException e) {
276
					catch(Exception e){}
219
						/* We should ignore this */
277
    	    	 			
278
					if(portreq == -1) {
279
						// This is a bad situation.  The AC should have given us a port
280
						// Since it didn't (unexpectedly), let's try a default
281
						portreq = 10006;
220
					}
282
					}
283
					
284
					// Tell the caller how to reconnect
285
					throw new ReconnectRequestedException(portreq);
221
				}
286
				}
287
				
288
				throw new IOException("Connection Refused");
222
			}
289
			}
223
290
			
224
			if(_loginFailed!=null) {
291
			throw new IOException("Unknown command");
225
				LoginFailedException temp=_loginFailed;
226
				_loginFailed=null;
227
				_loginPending=false;
228
				throw temp;
229
			}
230
			if(_isComplete) {
231
				throw new IOException();
232
			}
233
		}
292
		}
293
		
294
    	(new SocketReaderThread()).start();
295
    	_isInitialized = true;
234
	}
296
	}
235
297
	
236
	private void handleACCommands(ICommandElement command)
298
	private void handleACCommands(ICommandElement command) {
237
	{
238
		long contextId=command.getContext();
299
		long contextId=command.getContext();
239
		if(Constants.TPTP_DEBUG)System.out.println("The context of the returned command:" + contextId);
300
		if(Constants.TPTP_DEBUG)System.out.println("The context of the returned command:" + contextId);
240
		
301
		
241
		//Find the command handler associated with this contextId and
302
		//Find the command handler associated with this contextId and
242
		// forward the message appropriately.
303
		// forward the message appropriately.
243
		ICommandHandler ch=_contextMapper.getHandler(contextId);
304
		ICommandHandler ch=_contextMapper.getHandler(contextId);
244
		if(ch != null) 
305
		if(ch != null) {
245
		{
246
			if(Constants.TPTP_DEBUG)System.out.println("Forwarding to command handler");
306
			if(Constants.TPTP_DEBUG)System.out.println("Forwarding to command handler");
247
			ch.incomingCommand(_node, command);
307
			ch.incomingCommand(_node, command);
248
		}	
308
		}	
249
		else {
250
			if(Constants.TPTP_DEBUG)System.out.println("Could not find command handler");
251
		}
252
	}
309
	}
253
	
310
	
254
	private int extractConnectionId(byte[] buffer, int offset) {
311
	private int extractConnectionId(byte[] buffer, int offset) {
Lines 266-273 Link Here
266
	 *    nonzero if error
323
	 *    nonzero if error
267
	 *
324
	 *
268
	 *********************************************************/
325
	 *********************************************************/
269
	private void sendCONNECT_DATACommand(Socket datasock, int direction) throws IOException 
326
	private void sendCONNECT_DATACommand(Socket datasock, int direction) throws IOException	{
270
	{
271
		long flags = 0 ;
327
		long flags = 0 ;
272
328
273
		/* build the CONNECT command string */
329
		/* build the CONNECT command string */
Lines 284-290 Link Here
284
		long dataPathType = direction;
340
		long dataPathType = direction;
285
		offset = TPTPMessageUtil.writeTPTPLongToBuffer(buffer, offset, dataPathType);		
341
		offset = TPTPMessageUtil.writeTPTPLongToBuffer(buffer, offset, dataPathType);		
286
		
342
		
287
		OutputStream stream=datasock.getOutputStream();
343
		OutputStream stream = datasock.getOutputStream();
288
		stream.write(buffer);		
344
		stream.write(buffer);		
289
		stream.flush();
345
		stream.flush();
290
	}
346
	}
Lines 301-308 Link Here
301
	 *    nonzero if error
357
	 *    nonzero if error
302
	 *
358
	 *
303
	 *********************************************************/
359
	 *********************************************************/
304
	private void sendControlCommand(long commandFlags) throws IOException 
360
	private void sendControlCommand(long commandFlags) throws IOException  {
305
	{
306
		long flags = 0 ;
361
		long flags = 0 ;
307
362
308
		/* build the CONNECT command string */
363
		/* build the CONNECT command string */
Lines 317-420 Link Here
317
		sendMessage(connectMessage, _cmdHandler);
372
		sendMessage(connectMessage, _cmdHandler);
318
	}	
373
	}	
319
374
375
	int createDataConnection(int direction) throws IOException, SecureConnectionRequiredException {
376
		Socket datasock = connectSocket();
377
		if (datasock == null) throw new IOException();
320
378
321
	int createDataConnection(int direction) throws IOException
379
		return initDataConnection(datasock, direction);
322
	{
380
	}
323
		Socket datasock = null;
381
	
324
		int dataConnectionId = -1;
382
	protected int initDataConnection(Socket datasock, int direction) throws IOException, SecureConnectionRequiredException {
325
		byte[] buffer=new byte[Constants.MAX_MESSAGE_LENGTH];
383
		if (datasock == null || !datasock.isConnected()) return -1;
326
		int masterOffset=0;
327
		
384
		
328
		int offset=0;
385
		// CONNECT_DATA command 
329
		InetAddress[] addrs=_node.getAllInetAddresses();
330
331
		do {
332
			/* Connect to the remote machine */
333
			try {
334
					datasock=new Socket(addrs[offset], _port);
335
					datasock.setTcpNoDelay(true);
336
					datasock.setSoTimeout(_soTimeout);
337
					break;
338
			}
339
			catch(IOException exp)
340
			{
341
				offset++;
342
				//System.out.println(e.getMessage());
343
				if(offset==addrs.length) {
344
					throw exp;
345
				}
346
			}
347
		}while(offset<addrs.length);
348
349
		/* CONNECT_DATA command */
350
		sendCONNECT_DATACommand(datasock, direction);
386
		sendCONNECT_DATACommand(datasock, direction);
351
		
387
352
		/* Get the InputStream for this socket so we can read some data */
388
		// Get the InputStream for this socket so we can read some data 
353
		InputStream inStream=datasock.getInputStream();
389
		byte[] buffer = new byte[256];
354
		int bytesRead=inStream.read(buffer, masterOffset, buffer.length-masterOffset);
390
		InputStream inStream = datasock.getInputStream();
391
		int d = inStream.read(buffer, 0, buffer.length);
355
		
392
		
356
		ControlMessage DataConnectionResponseMessage = new ControlMessage();
393
		ControlMessage DataConnectionResponseMessage = new ControlMessage();
357
		DataConnectionResponseMessage.setMessageType(Constants.TPTP_AC_MESSAGE);
394
		DataConnectionResponseMessage.setMessageType(Constants.TPTP_AC_MESSAGE);
358
		masterOffset = DataConnectionResponseMessage.readFromBuffer(buffer, masterOffset);
395
		int masterOffset = DataConnectionResponseMessage.readFromBuffer(buffer, 0);
359
		long flags = DataConnectionResponseMessage.getFlags();
396
		long flags = DataConnectionResponseMessage.getFlags();
360
		if ((flags & Constants.DATA_CONNECTION_COMPLETE) != 0)
397
		if ((flags & Constants.CONNECTION_REFUSED) != 0) {
361
    	{
398
			if ((flags & Constants.SECURITY_REQUIRED) != 0) {
362
			dataConnectionId = extractConnectionId(buffer, masterOffset);
399
				throw new SecureConnectionRequiredException();
363
    	}
400
			}
401
			
402
			throw new IOException("Connection Refused");
403
		}
404
		
405
		if ((flags & Constants.DATA_CONNECTION_COMPLETE) <= 0) return -1;
406
		
407
		int dataConnectionId = extractConnectionId(buffer, masterOffset);
408
		if (dataConnectionId <= 0) return -1;
364
		
409
		
365
		DataConnection dataConnectionInfo = new DataConnection();
410
		DataConnection dataConnectionInfo = new DataConnection();
366
		ACTCPDataServer dataServer = new ACTCPDataServer();
411
		ACTCPDataServer dataServer = new ACTCPDataServer();
367
		if (dataConnectionId > 0)
368
		{
369
			//dataConnectionId = ::getConnectionId(pMsg) ;
412
			//dataConnectionId = ::getConnectionId(pMsg) ;
370
			if(Constants.TPTP_DEBUG)System.out.println("The Data Channel ConnectionID: " + dataConnectionId);
413
		if(Constants.TPTP_DEBUG)System.out.println("The Data Channel ConnectionID: " + dataConnectionId);
371
			dataConnectionInfo.setDataSocket(datasock);
414
		dataConnectionInfo.setDataSocket(datasock);
372
			dataConnectionInfo.setDataServer(dataServer);
415
		dataConnectionInfo.setDataServer(dataServer);
373
			_dataConnectionMap.put(new Integer(dataConnectionId), dataConnectionInfo);				
416
		dataConnectionInfo.setDataconnectionId(dataConnectionId);
374
		
417
		_dataConnectionMap.put(new Integer(dataConnectionId), dataConnectionInfo);				
375
			try
418
		
376
			{
419
		try {
377
				dataServer.startServer(null, datasock);
420
			dataServer.startServer(null, datasock);
378
			}
421
		}
379
			catch(SocketException sockExp)
422
		catch(SocketException sockExp) {			
380
			{			
423
		}
381
				System.out.println("Error starting the TCPDataServer");
424
		catch(IOException Exp) {			
382
			}
383
			catch(IOException Exp)
384
			{			
385
				System.out.println("Error starting the TCPDataServer");
386
			}
387
		}
425
		}
388
		
426
		
389
		return dataConnectionId;
427
		return dataConnectionId;
390
	}
428
	}
391
429
392
	
430
	public int addDataListener(int dataConnectionId, IDataProcessor dataProcessor) {
393
	public int addDataListener(int dataConnectionId, IDataProcessor dataProcessor)
431
		if(dataConnectionId == -1) return -1;
394
	{
432
		
395
		if(dataConnectionId == -1){ return -1;}
396
		DataConnection dataConnectionInfo = (DataConnection)_dataConnectionMap.get(new Integer(dataConnectionId));
433
		DataConnection dataConnectionInfo = (DataConnection)_dataConnectionMap.get(new Integer(dataConnectionId));
397
		ACTCPDataServer dataServer = dataConnectionInfo.getDataServer();
434
		ACTCPDataServer dataServer = dataConnectionInfo.getDataServer();
398
		if(dataServer != null)
435
		if(dataServer != null) { 
399
		{ 
400
			dataServer.addDataprocessor(dataProcessor);
436
			dataServer.addDataprocessor(dataProcessor);
401
			return 0;
437
			return 0;
402
		}
438
		}
439
		
403
		return -1;
440
		return -1;
404
	}
441
	}
405
	
442
	
406
	public int removeDataListener(int dataConnectionId, IDataProcessor dataProcessor)
443
	public int removeDataListener(int dataConnectionId, IDataProcessor dataProcessor) {
407
	{
444
		try	{
408
		try
409
		{
410
			DataConnection dataConnectionInfo = (DataConnection)_dataConnectionMap.get(new Integer(dataConnectionId));
445
			DataConnection dataConnectionInfo = (DataConnection)_dataConnectionMap.get(new Integer(dataConnectionId));
411
			ACTCPDataServer dataServer = dataConnectionInfo.getDataServer();
446
			ACTCPDataServer dataServer = dataConnectionInfo.getDataServer();
412
			dataServer.removeDataprocessor(dataProcessor);
447
			dataServer.removeDataprocessor(dataProcessor);
413
			dataServer.shutdownServer();
448
			dataServer.shutdownServer();
414
		}catch(Exception e)
449
		} catch(Exception e) {}
415
		{
450
		
416
			///e.printStackTrace();
417
		}
418
		return 0;
451
		return 0;
419
	}	
452
	}	
420
	
453
	
Lines 428-441 Link Here
428
		_dataConnectionMap.remove(new Integer(dataConnID));
461
		_dataConnectionMap.remove(new Integer(dataConnID));
429
	}
462
	}
430
	
463
	
431
	private void closeDataConnection(int dataConnID)
464
	private void closeDataConnection(int dataConnID) {
432
	{
433
		DataConnection dataConnectionInfo = (DataConnection)_dataConnectionMap.get(new Integer(dataConnID));
465
		DataConnection dataConnectionInfo = (DataConnection)_dataConnectionMap.get(new Integer(dataConnID));
434
		
466
		
435
		try
467
		try {
436
		{
468
			if (dataConnectionInfo != null) {
437
			if (dataConnectionInfo != null)
438
			{
439
				// Send DISCONNECT command for data channel
469
				// Send DISCONNECT command for data channel
440
				sendControlCommand(Constants.DISCONNECT); 
470
				sendControlCommand(Constants.DISCONNECT); 
441
	
471
	
Lines 445-515 Link Here
445
				dataConnectionInfo.getDataSocket().close();
475
				dataConnectionInfo.getDataSocket().close();
446
			}
476
			}
447
		}
477
		}
448
		catch(Exception exp)
478
		catch(Exception exp) {
449
		{
450
			if (Constants.TPTP_DEBUG) System.out.println("Error destroying the data channel - " + exp.getMessage());
479
			if (Constants.TPTP_DEBUG) System.out.println("Error destroying the data channel - " + exp.getMessage());
451
		}	
480
		}	
452
	}
481
	}
453
	
482
	
454
	public void sendData(int dataConnectionId, byte[] buffer, int bufferLength)
483
	public void sendData(int dataConnectionId, byte[] buffer, int bufferLength) {
455
	{
484
		try {
456
		try
457
		{
458
			DataConnection dataConnectionInfo = (DataConnection)_dataConnectionMap.get(new Integer(dataConnectionId));
485
			DataConnection dataConnectionInfo = (DataConnection)_dataConnectionMap.get(new Integer(dataConnectionId));
459
			OutputStream stream=dataConnectionInfo._dataSocket.getOutputStream();
486
460
			stream.write(buffer);
487
			synchronized (writeDataLock) {
461
			stream.flush();
488
				OutputStream stream=dataConnectionInfo._dataSocket.getOutputStream();
462
		}
489
				stream.write(buffer);
463
		catch(IOException exp)
490
				stream.flush();
464
		{
491
			}
465
			System.out.println("Error writing the data to the Socket - " + exp);
492
		}
466
		}
493
		catch(IOException exp) {
467
		catch(Exception e)
494
		}
468
		{
495
		catch(Exception e) {
469
			System.out.println("Error sending the data - " + e);
470
		}			
496
		}			
471
	}
497
	}
472
498
473
	public void sendMessage(IControlMessage msg, ICommandHandler handler) throws IOException 
499
	public void sendMessage(IControlMessage msg, ICommandHandler handler) throws IOException {
474
	{
500
		try	{
475
		int commandCount = msg.getCommandCount();
501
			if (handler != null) {
476
502
				int commandCount = msg.getCommandCount();
477
		try
503
				for (int i=0; i < commandCount; i++) {
478
		{
504
					_contextMapper.addContext(msg.getCommand(i).getContext(), handler);
479
			for (int i=0; i < commandCount; i++) {
505
				}
480
				//System.out.println("Adding the handler to the context ...");
481
				//System.out.println("Context:" + msg.getCommand(i).getContext());
482
				//System.out.println("Handler:" + handler);
483
			    this._contextMapper.addContext(msg.getCommand(i).getContext(), handler);
484
			}
506
			}
485
			
507
			
486
			int count=msg.getSize();
508
			byte[] buffer=new byte[msg.getSize()];
487
			//System.out.println("message size " + count);
488
			byte[] buffer=new byte[count];
489
			msg.writeToBuffer(buffer, 0);
509
			msg.writeToBuffer(buffer, 0);
490
	
510
	
491
			OutputStream stream=_socket.getOutputStream();
511
			synchronized (writeLock) {
492
			stream.write(buffer);
512
				OutputStream stream=_socket.getOutputStream();
493
			stream.flush();
513
				stream.write(buffer);
514
				stream.flush();
515
			}
494
		}
516
		}
495
		catch(IOException exp)
517
		catch(IOException exp) {
496
		{
497
			if (Constants.TPTP_DEBUG)System.out.println("SendMessage error - " + exp);
518
			if (Constants.TPTP_DEBUG)System.out.println("SendMessage error - " + exp);
498
			throw exp;
519
			throw exp;
499
		}
520
		}
500
		catch(Exception exp)
521
		catch(Exception exp) {
501
		{
502
			if (Constants.TPTP_DEBUG)System.out.println("SendMessage error - " + exp);
522
			if (Constants.TPTP_DEBUG)System.out.println("SendMessage error - " + exp);
503
			//throw exp;
504
		}
523
		}
505
506
	}
524
	}
507
525
508
	public void disconnect() {
526
	public void disconnect() {
509
		synchronized(_connectionLock) {
510
			if(!_isComplete) {
527
			if(!_isComplete) {
511
				_isComplete=true;
528
				_isComplete=true;
512
				_connectionLock.notifyAll();
529
513
				try 
530
				try 
514
				{
531
				{
515
					// Destroy Data Connections
532
					// Destroy Data Connections
Lines 526-536 Link Here
526
					// Send DISCONNECT command
543
					// Send DISCONNECT command
527
					sendControlCommand(Constants.DISCONNECT);
544
					sendControlCommand(Constants.DISCONNECT);
528
					
545
					
529
					// Close the SocketReaderThread
530
					_isComplete = true;
531
					
532
					// Close the Socket
533
					_socket.close();
534
					if (Constants.TPTP_DEBUG) System.out.println("Successfully disconnected.");
546
					if (Constants.TPTP_DEBUG) System.out.println("Successfully disconnected.");
535
				}
547
				}
536
				catch(IOException e) {
548
				catch(IOException e) {
Lines 538-543 Link Here
538
					if (Constants.TPTP_DEBUG) System.out.println("Exception while disconnecting ... " + e);
550
					if (Constants.TPTP_DEBUG) System.out.println("Exception while disconnecting ... " + e);
539
				}
551
				}
540
				
552
				
553
				close();
554
541
				/* If this is a nodeimpl clear the keystore spec so it tries an insecure connect next time */
555
				/* If this is a nodeimpl clear the keystore spec so it tries an insecure connect next time */
542
				//Commented by GN since security not supported yet in the new 
556
				//Commented by GN since security not supported yet in the new 
543
				//	if(_node instanceof INode) {
557
				//	if(_node instanceof INode) {
Lines 555-579 Link Here
555
				}
569
				}
556
				*/			
570
				*/			
557
			}
571
			}
558
		}
559
	}
572
	}
560
573
574
	public void close () {
575
		if (_socket != null) {
576
			try { 
577
				_socket.close(); 
578
			} catch (Exception e) {}
579
		}
580
		
581
		_isComplete = true;
582
	}
583
	
561
	public INode getNode() {
584
	public INode getNode() {
562
		return _node;
585
		return _node;
563
	}
586
	}
564
587
565
	public boolean isActive() {
588
	public boolean isActive() {
566
		if(_isInitialized) {
589
		return _isInitialized && !_isComplete;
567
			return !_isComplete;
568
		}
569
		return false;
570
	}
590
	}
571
	public static int checkForRACMessage(byte[] buffer, int offset)
591
	
572
	{
592
	public static int checkForRACMessage(byte[] buffer, int offset) {
573
		Message tempMessage=new Message();
593
		Message tempMessage=new Message();
574
		tempMessage.readFromBuffer(buffer, offset);
594
		tempMessage.readFromBuffer(buffer, offset);
575
		if(tempMessage.getMagicNumber() == Constants.RA_MAGIC)
595
		if(tempMessage.getMagicNumber() == Constants.RA_MAGIC) {
576
		{
577
			return Constants.RAC_MESSAGE_HEADER_SIZE;
596
			return Constants.RAC_MESSAGE_HEADER_SIZE;
578
		} 
597
		} 
579
		return -1;
598
		return -1;
Lines 582-708 Link Here
582
	public int getPort() {
601
	public int getPort() {
583
		return _port;
602
		return _port;
584
	}
603
	}
604
	
605
	public InetAddress getInetAddress() {
606
		return inetAddress;
607
	}
608
	
585
	protected ContextMapper getContextMapper()
609
	protected ContextMapper getContextMapper()
586
	{
610
	{
587
	    return this._contextMapper;
611
	    return this._contextMapper;
588
	}
612
	}
589
613
590
	protected int processControlMessage(byte[] buffer, int offset, int length) {
614
	protected int processControlMessage(byte[] buffer, int offset, int length) {
591
		if(_cmdHandler != null) {
615
		if(_cmdHandler == null) return -1;
592
			ControlMessage msg=new ControlMessage();
616
		
593
			msg.setMessageType(Constants.TPTP_AC_MESSAGE);
617
		ControlMessage msg=new ControlMessage();
618
		msg.setMessageType(Constants.TPTP_AC_MESSAGE);
594
619
595
			int current=-1;
620
		int current=-1;
596
			try {
621
		try {
597
				if(Constants.TPTP_DEBUG)System.out.println("Processing the Message.");
622
			if(Constants.TPTP_DEBUG)System.out.println("Processing the Message.");
598
				if (buffer.length == length + offset) {
623
			if (buffer.length == length + offset) {
599
					current = msg.readFromBuffer(buffer, offset);
624
				current = msg.readFromBuffer(buffer, offset);
600
				}
625
			}
601
				else {
626
			else {
602
					// length is not passed to readFromBuffer so we should ensure 
627
				// length is not passed to readFromBuffer so we should ensure 
603
					// that readFromBuffer will not read trash from the end of the buffer
628
				// that readFromBuffer will not read trash from the end of the buffer
604
					// and no exception will be thrown.
629
				// and no exception will be thrown.
605
					// ControlMessage.readFromBuffer(buffer, offset, length) method
630
				// ControlMessage.readFromBuffer(buffer, offset, length) method
606
					// is needed in order to prevent extra memory allocations in this case.
631
				// is needed in order to prevent extra memory allocations in this case.
607
					byte[] buffer2 = new byte[length];
632
				byte[] buffer2 = new byte[length];
608
					System.arraycopy(buffer, offset, buffer2, 0, length);
633
				System.arraycopy(buffer, offset, buffer2, 0, length);
609
					current = msg.readFromBuffer(buffer2, 0);
634
				current = msg.readFromBuffer(buffer2, 0);
610
					if (current >= 0)
635
				if (current >= 0)
611
						current += offset;
636
					current += offset;
612
				}
613
				/* If we read more bytes then were valid, return -1 */
614
				if(current>offset+length) 
615
				{
616
					return -1;
617
				}
618
			}
637
			}
619
			catch(IndexOutOfBoundsException e) 
638
			/* If we read more bytes then were valid, return -1 */
620
			{  
639
			if(current>offset+length) {
621
				return -1;
640
				return -1;
622
			}
641
			}
623
			catch(Exception e) 
642
		}
624
			{
643
		catch(IndexOutOfBoundsException e) {  
625
		    	System.out.println("Exception while processing the message" + e);
644
			return -1;
626
		            return -1;
645
		}
627
			}
646
		catch(Exception e) {
647
			System.out.println("Exception while processing the message" + e);
648
	        return -1;
649
		}
628
650
629
	         /* If we have parsed the message successfully  Then process it */
651
	        /* If we have parsed the message successfully  Then process it */
630
			int len = msg.getSize();
652
		int len = msg.getSize();
631
			
653
			
632
		    if (current == len+offset) {
654
	    if (current == len+offset) {
633
				/* Valid pass on each command */
655
			/* Valid pass on each command */
634
	    		if(Constants.TPTP_DEBUG)System.out.println("Checking for CONNECTION_COMPLETE response");
656
//	    		if(Constants.TPTP_DEBUG)System.out.println("Checking for CONNECTION_COMPLETE response");
635
	    		long flags = msg.getFlags();
657
	   		long flags = msg.getFlags();
636
	    		
658
   			
637
		    	if ((flags & Constants.CONNECTION_COMPLETE) != 0) {			    		
659
	   		if ((flags & Constants.AUTHENTICATION_FAILED) != 0) {
638
		    		int cmdOffset = 0;
660
	   			isAuthenticated = false;
639
		    		_connectionId = extractConnectionId(buffer, current+cmdOffset);
661
	   			current += msg.getLength();
640
		    		cmdOffset += 4;
662
	   			synchronized (authLock) {
641
663
	   				authLock.notifyAll();
642
		    		int uuidLen = (int) TPTPMessageUtil.readTPTPLongFromBuffer(buffer, current+cmdOffset);
664
	   			}
643
		    		cmdOffset += 4 + uuidLen + 1;	// including trailing null
665
	   		}
644
		    		
666
    		else if ((flags & Constants.AUTHENTICATION_SUCCESSFUL) != 0) {
645
		    		if ((cmdOffset + 4) <= msg.getLength()) { 	// check if protoVersion is available
667
    			isAuthenticated = true;
646
		    			protoVersion = (int) TPTPMessageUtil.readTPTPLongFromBuffer(buffer, current+cmdOffset);
668
	   			current += msg.getLength();
647
		    		}
669
	   			synchronized (authLock) {
648
670
	   				authLock.notifyAll();
649
		    		current += msg.getLength();
671
	   			}
650
		    		if(Constants.TPTP_DEBUG)System.out.println("Connection complete response - " + _connectionId + ", protoVer=" + protoVersion);
672
    		}
651
		    		synchronized (_connectionLock) {
673
	    	else {
652
		    			_connectionLock.notifyAll();
674
	    		int count=msg.getCommandCount();
653
		    		}
675
	    		for(int i=0; i<count; i++) {
654
		    	}
676
	    			_cmdHandler.incomingCommand(_node, msg.getCommand(i));
655
		    	if((flags & Constants.CONNECTION_RECONNECT_REQUEST) !=  0)
677
	    		}
656
				{ 
678
	    	}
657
    	 			int portreq = -1;
679
	   	}
658
	    			synchronized(_socket)
659
	    			{	
660
			    		try
661
			    		{
662
				    		_isComplete=true;
663
				    		_dataConnectionMap.clear();
664
		    				_socket.close();
665
		    				CommandFragment cmd=(CommandFragment)msg.getCommand(0);
666
		    				String strToParse = cmd.getCommandData();//new String(buffer,Constants.ACK_HDR_LEN,buffer.length-12);
667
		    				TPTPXMLParse ParseObj = new TPTPXMLParse();
668
		    	 			ParseObj.setParser(strToParse.trim());
669
		    	 			Hashtable CommandHash = ParseObj.getHashTable();
670
		    	 			if(CommandHash.containsKey("port"))
671
		    	 			{
672
		    	 				portreq = Integer.parseInt((String)ParseObj.getHashTable().get("port"));
673
		    	 			}
674
			    		}
675
				    	catch(Exception e){}
676
		    		}
677
		    	 			
678
    				if(portreq == -1) {
679
    					// This is a bad situation.  The AC should have given us a port
680
    					// Since it didn't (unexpectedly), let's try a default
681
    					portreq = 10006;
682
    				}
683
    				
684
    				// Tell the caller how to reconnect
685
					_reconnectRequestedException = new ReconnectRequestedException( portreq );
686
					synchronized (_connectionLock) {
687
						// This notify will cause init to throw the above request
688
						// and cause the read thread to bail
689
						_connectionLock.notifyAll();
690
					}
691
		    	}
692
				int count=msg.getCommandCount();
693
680
694
				for(int i=0; i<count; i++) 
681
	    return current; 
695
				{
696
					_cmdHandler.incomingCommand(_node, msg.getCommand(i));
697
				}
698
			}
699
			return current;
700
		}
701
		return -1;
702
	}
682
	}
703
	
683
	
704
	
705
	
706
	/**
684
	/**
707
	 * @see Connection#addConnectionListener(ConnectionListener)
685
	 * @see Connection#addConnectionListener(ConnectionListener)
708
	 */
686
	 */
Lines 713-719 Link Here
713
			}
691
			}
714
		}
692
		}
715
	}
693
	}
716
717
	
694
	
718
	/**
695
	/**
719
	 * @see Connection#removeConnectionListener(ConnectionListener)
696
	 * @see Connection#removeConnectionListener(ConnectionListener)
Lines 729-751 Link Here
729
	public void setSoTimeout(int timeout) {
706
	public void setSoTimeout(int timeout) {
730
		_soTimeout = timeout;
707
		_soTimeout = timeout;
731
	}
708
	}
732
709
	
733
	public int getProtocolVersion() {
710
	public int getProtocolVersion() {
734
		return protoVersion;
711
		return protoVersion;
735
	}
712
	}
736
	
713
	
737
	class SocketReaderThread extends Thread implements Constants 
714
	public Socket getSocket() {
738
	{
715
		return _socket;
739
		public void run() 
716
	}
740
		{
717
	
741
			/* Run forever */
718
	public void setSocket(Socket socket) {
742
			byte[] buffer=new byte[MAX_MESSAGE_LENGTH];
719
		_socket = socket;
720
		_isComplete = true; 
721
	}
722
723
	class SocketReaderThread extends Thread implements Constants {
724
		public void run() {
725
			byte[] buffer = new byte[MAX_MESSAGE_LENGTH];
743
			int masterOffset=0;
726
			int masterOffset=0;
744
			boolean incompleteMsg;
727
			boolean incompleteMsg;
745
			int timeoutCount=0;
728
746
			_isComplete = false;
729
			_isComplete = false;
747
			
730
			
748
			/* Get the InputStream for this socket so we can read some data */
731
			// Get the InputStream for this socket so we can read some data 
749
			BufferedInputStream inStream;
732
			BufferedInputStream inStream;
750
			try {
733
			try {
751
				inStream = new BufferedInputStream(_socket.getInputStream());
734
				inStream = new BufferedInputStream(_socket.getInputStream());
Lines 756-826 Link Here
756
				return;
739
				return;
757
			}
740
			}
758
741
759
			while(!_isComplete) 
742
			while(!_isComplete) {
760
			{
743
				incompleteMsg = false;  // 185463 
761
				incompleteMsg = false;  /* 185463 */
744
				try	{
762
				try 
745
					int bytesRead = inStream.read(buffer, masterOffset, buffer.length-masterOffset);
763
				{
746
					if(bytesRead == -1) break;
764
					int bytesRead=inStream.read(buffer, masterOffset, buffer.length-masterOffset);
765
					
766
					if(bytesRead==-1) {break;}
767
					
747
					
768
			        if (masterOffset > 0) 
748
			        if (masterOffset > 0) {
769
			        {
770
			        	bytesRead += masterOffset;
749
			        	bytesRead += masterOffset;
771
						masterOffset = 0;
750
						masterOffset = 0;
772
			        }
751
			        }
773
			      
752
			      
774
					/*
753
					//
775
					 * If we've tried to connect to a backward compatibility
754
					// If we've tried to connect to a backward compatibility
776
					 * layer of the AC, we'll immediately get a response in 
755
					// layer of the AC, we'll immediately get a response in 
777
					 * RAC format.  If we ignore this, the BC layer will
756
					// RAC format.  If we ignore this, the BC layer will
778
					 * respond to our first message by giving us the port
757
					// respond to our first message by giving us the port
779
					 * to connect to the regular socket TL.
758
					// to connect to the regular socket TL.
780
					 */
759
					//
781
					int vret = checkForRACMessage(buffer, masterOffset);
760
					int vret = checkForRACMessage(buffer, masterOffset);
782
					if(vret != -1)
761
					if (vret != -1) {
783
					{
784
						// We read the header, the next four bytes will be the length 
762
						// We read the header, the next four bytes will be the length 
785
						// (including the header) of the RAC message
763
						// (including the header) of the RAC message
786
						long length=TPTPMessageUtil.readTPTPLongFromBuffer(buffer, vret);
764
						long length = TPTPMessageUtil.readTPTPLongFromBuffer(buffer, vret);
787
						masterOffset = (int)length;
765
						masterOffset = (int)length;
788
					}
766
					}
789
	
767
	
790
					while(masterOffset<bytesRead) 
768
					while(masterOffset<bytesRead) {
791
					{
792
						int newOffset=0;
769
						int newOffset=0;
793
						/* First we make sure we have at least enough read for the message header.
770
						// First we make sure we have at least enough read for the message header.
794
						   If not, compress and re-read.
771
						 //  If not, compress and re-read.
795
						*/
772
						//
796
						if ( bytesRead-masterOffset < AC_MESSAGE_HEADER_SIZE ) {
773
						if ( bytesRead-masterOffset < AC_MESSAGE_HEADER_SIZE ) {
797
							System.arraycopy( buffer, masterOffset, buffer, 0, bytesRead-masterOffset );
774
							System.arraycopy( buffer, masterOffset, buffer, 0, bytesRead-masterOffset );
798
							masterOffset=bytesRead-masterOffset;
775
							masterOffset=bytesRead-masterOffset;
799
							incompleteMsg = true;
776
							incompleteMsg = true;
800
							break;
777
							break;
801
						}
778
						}
802
						/* We have the header information, now lets try and get the entire message.  Once
779
						
803
						   again the same error conditions can occur.
780
						// We have the header information, now lets try and get the entire message.  Once
804
						*/
781
						 //  again the same error conditions can occur.
805
						if(Constants.TPTP_DEBUG)System.out.println("Received a non-acknowledgement message");
782
						//
806
						//System.out.println("Offset xx::"+new String(buffer));
783
						newOffset = processControlMessage(buffer, masterOffset, bytesRead);
807
						newOffset=processControlMessage(buffer, masterOffset, bytesRead);
784
						
808
						if(Constants.TPTP_DEBUG)System.out.println("Recvd Message : " + buffer.toString());
785
						if(Constants.TPTP_DEBUG)System.out.println("Recvd Message: " + buffer.toString());
809
						if ( newOffset == -1 ) 
786
						
810
						{
787
						if (newOffset == -1) {
811
							// newOffset of -1 indicates the message is bigger than what's left in the buffer
788
							// newOffset of -1 indicates the message is bigger than what's left in the buffer
812
							// If the masterOffset is zero, this means the message is bigger than the buffer 
789
							// If the masterOffset is zero, this means the message is bigger than the buffer 
813
							//   itself, so we need to grow the buffer.  Otherwise, we'll slide the message
790
							//   itself, so we need to grow the buffer.  Otherwise, we'll slide the message
814
							//   to the beginning of the buffer and try to read some more
791
							//   to the beginning of the buffer and try to read some more
815
							if(masterOffset>0) 
792
							if(masterOffset>0) {
816
							{
817
								System.arraycopy( buffer, masterOffset, buffer, 0, bytesRead-masterOffset );
793
								System.arraycopy( buffer, masterOffset, buffer, 0, bytesRead-masterOffset );
818
							}
794
							}
819
		 					else if (bytesRead == buffer.length) 
795
		 					else if (bytesRead == buffer.length) 
820
         					{
796
         					{
821
		                        int len = buffer.length * 2;
797
		                        int len = buffer.length * 2;
822
		                        byte[] tmpbuffer=new byte[len];
798
		                        byte[] tmpbuffer=new byte[len];
823
		                        /* Copy necessary data over to new buffer */
799
		                        // Copy necessary data over to new buffer 
824
		                        System.arraycopy(buffer, masterOffset, tmpbuffer, 0, bytesRead-masterOffset);
800
		                        System.arraycopy(buffer, masterOffset, tmpbuffer, 0, bytesRead-masterOffset);
825
		                        buffer = tmpbuffer;
801
		                        buffer = tmpbuffer;
826
                 			}
802
                 			}
Lines 829-850 Link Here
829
							break;
805
							break;
830
						}
806
						}
831
						masterOffset=newOffset;
807
						masterOffset=newOffset;
832
					} /* end of inner while */
808
					} // end of inner while 
833
	
809
	
834
					if (!incompleteMsg) 
810
					if (!incompleteMsg) 
835
					{
811
					{
836
						masterOffset=0;
812
						masterOffset=0;
837
				    }
813
				    }
838
				}
814
				}
839
				catch(InterruptedIOException e) 
815
				catch(InterruptedIOException e) {
840
				{
841
					 if(timeoutCount > Constants.CONNECT_TIMEOUT_TRY_COUNT && !_isInitialized) 
842
					 {
843
						 synchronized(_connectionLock) {
844
					 		_connectionLock.notifyAll();
845
					 	}
846
					 }
847
					 timeoutCount++;
848
				}
816
				}
849
				catch(SocketException e) 
817
				catch(SocketException e) 
850
				{
818
				{
Lines 856-864 Link Here
856
					//e.printStackTrace();
824
					//e.printStackTrace();
857
					break;
825
					break;
858
				}
826
				}
859
			} /* end of outer while */
827
			} // end of outer while 
860
			/* The server is now stopping */
828
			// The server is now stopping 
829
			
861
			disconnect();
830
			disconnect();
862
		}
831
		}
863
	}
832
	}
833
	
834
	public boolean isAuthenticated() {
835
		return isAuthenticated;
836
	}
837
	
838
	protected boolean authenticateUser(User user) {
839
		if (user == null || user.getName() == null || user.getPassword() == null) return false;
840
		
841
		ControlMessage authMsg = new ControlMessage();
842
		authMsg.setMessageType(Constants.TPTP_AC_MESSAGE);
843
		authMsg.setMagicNumber(Constants.AC_MAGIC_NUMBER);
844
		authMsg.setFlags(Constants.AUTHENTICATE);
845
		
846
		AuthenticateCommand authCmd = new AuthenticateCommand(user.getName(), user.getPassword());
847
		authMsg.appendCommand(authCmd);
848
		
849
		try { 
850
			sendMessage(authMsg, new ICommandHandler() {
851
				public void incomingCommand(INode node, ICommandElement command) {}
852
			});
853
		} catch (Exception e) {
854
			return false;
855
		}
856
857
		synchronized (authLock) {
858
			try { authLock.wait(Constants.WAIT_RESPONCE_TIMEOUT); } catch (Exception e) {}
859
		}
860
		
861
		return isAuthenticated;
862
	}
864
}
863
}
(-)src/org/eclipse/tptp/platform/execution/exceptions/LoginFailedException.java (+4 lines)
Lines 28-33 Link Here
28
	private long _port;
28
	private long _port;
29
29
30
30
31
	public LoginFailedException() {
32
		_port = 0;
33
	}
34
31
	public LoginFailedException(long port) {
35
	public LoginFailedException(long port) {
32
		_port=port;
36
		_port=port;
33
	}
37
	}
(-)src/org/eclipse/tptp/platform/execution/client/core/IAgentController.java (+2 lines)
Lines 283-288 Link Here
283
	 */
283
	 */
284
	boolean authenticateUser(User user) throws NotConnectedException;
284
	boolean authenticateUser(User user) throws NotConnectedException;
285
     
285
     
286
	boolean isAuthenticated();
287
	
286
	/**
288
	/**
287
	 * Get a Agent Reference to communicate with the agent
289
	 * Get a Agent Reference to communicate with the agent
288
	 * @param agentName
290
	 * @param agentName
(-)src/org/eclipse/tptp/platform/execution/client/core/NodeFactory.java (-10 / +5 lines)
Lines 87-94 Link Here
87
	 * if the Node exists it will be returned.
87
	 * if the Node exists it will be returned.
88
	 */
88
	 */
89
	public static INode createNode(InetAddress address) throws UnknownHostException {
89
	public static INode createNode(InetAddress address) throws UnknownHostException {
90
		//return createNode(address, null);
90
		String hostname = address.getHostName();
91
		return createNode(address);
91
		INode node = containsNode(hostname);
92
		if (node != null) return node;
93
		
94
		return addNode(hostname, address, null);
92
	}
95
	}
93
96
94
97
Lines 148-157 Link Here
148
		}
151
		}
149
	}
152
	}
150
	
153
	
151
152
153
154
	
155
	private static INode containsNode(String name) {
154
	private static INode containsNode(String name) {
156
		synchronized(_servers) {
155
		synchronized(_servers) {
157
			// If this is "localhost" try and resolve its real name first
156
			// If this is "localhost" try and resolve its real name first
Lines 199-205 Link Here
199
		return null;
198
		return null;
200
	}
199
	}
201
200
202
	
203
	/**
201
	/**
204
	 * Searches the Node list based upon the InetAddress.
202
	 * Searches the Node list based upon the InetAddress.
205
	 * @return the Node if it exists, null otherwise.
203
	 * @return the Node if it exists, null otherwise.
Lines 208-214 Link Here
208
		//return getNode(addr, null);
206
		//return getNode(addr, null);
209
		return containsNode(addr.getHostName());
207
		return containsNode(addr.getHostName());
210
	}
208
	}
211
212
213
}
209
}
214
(-)src/org/eclipse/tptp/platform/execution/client/core/internal/X509TrustManagerImpl.java (+47 lines)
Added Link Here
1
package org.eclipse.tptp.platform.execution.client.core.internal;
2
3
import java.security.KeyStore;
4
import java.security.cert.CertificateException;
5
import java.security.cert.X509Certificate;
6
7
import javax.net.ssl.TrustManager;
8
import javax.net.ssl.TrustManagerFactory;
9
import javax.net.ssl.X509TrustManager;
10
11
public class X509TrustManagerImpl implements X509TrustManager {
12
	private X509TrustManager defaultX509tm; 
13
	
14
	X509TrustManagerImpl () throws Exception {
15
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
16
		tmf.init((KeyStore) null);
17
		
18
		TrustManager tms[] = tmf.getTrustManagers();
19
		for (int i=0; i<tms.length; i++) {
20
			if (tms[i] instanceof X509TrustManager) {
21
				defaultX509tm = (X509TrustManager) tms[i];
22
				break;
23
			}
24
		}
25
	}
26
	
27
	public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
28
		if (defaultX509tm == null) throw new CertificateException ("Trust manager not found");
29
		
30
		defaultX509tm.checkClientTrusted(certs, authType);
31
	}
32
33
	public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
34
		if (defaultX509tm != null)
35
			try {
36
				defaultX509tm.checkServerTrusted(certs, authType);
37
				return;
38
			} catch (Exception e) {}
39
			
40
// TODO: ask user if certificate is trusted, save it
41
	}
42
43
	public X509Certificate[] getAcceptedIssuers() {
44
		if (defaultX509tm != null) return defaultX509tm.getAcceptedIssuers();
45
		return null;
46
	}
47
}
(-)src/org/eclipse/tptp/platform/execution/client/core/internal/commands/AuthenticateCommand.java (+28 lines)
Added Link Here
1
package org.eclipse.tptp.platform.execution.client.core.internal.commands;
2
3
import org.eclipse.tptp.platform.execution.util.internal.CommandElement;
4
import org.eclipse.tptp.platform.execution.util.internal.TPTPMessageUtil;
5
import org.eclipse.tptp.platform.execution.util.internal.TPTPString;
6
7
public class AuthenticateCommand extends CommandElement {
8
	private TPTPString name;
9
	private TPTPString password;
10
	
11
	public AuthenticateCommand(String name, String password) {
12
		this.name = new TPTPString(name);
13
		this.password = new TPTPString(password);
14
	}
15
	
16
	public int getSize() {
17
		return name.getSize() + password.getSize();
18
	}
19
20
	public int readFromBuffer(byte[] buffer, int offset) {
21
		return 0;
22
	}
23
24
	public int writeToBuffer(byte[] buffer, int offset) {
25
		int current = TPTPMessageUtil.writeTPTPStringToBuffer(buffer, offset, name);
26
		return TPTPMessageUtil.writeTPTPStringToBuffer(buffer, current, password);
27
	}
28
}
(-)src/org/eclipse/tptp/platform/execution/util/internal/IAgentControllerFactory.java (+7 lines)
Added Link Here
1
package org.eclipse.tptp.platform.execution.util.internal;
2
3
import org.eclipse.tptp.platform.execution.client.core.IAgentController;
4
5
public interface IAgentControllerFactory {
6
	public IAgentController createConnection(String hostName, int portNumber) throws Exception;
7
}
(-)src/org/eclipse/tptp/platform/execution/client/core/internal/ConnectionFactory.java (+39 lines)
Added Link Here
1
package org.eclipse.tptp.platform.execution.client.core.internal;
2
3
import java.io.IOException;
4
5
import org.eclipse.tptp.platform.execution.client.core.ConnectionInfo;
6
import org.eclipse.tptp.platform.execution.client.core.INode;
7
import org.eclipse.tptp.platform.execution.exceptions.LoginFailedException;
8
import org.eclipse.tptp.platform.execution.exceptions.NotConnectedException;
9
import org.eclipse.tptp.platform.execution.exceptions.ReconnectRequestedException;
10
import org.eclipse.tptp.platform.execution.exceptions.SecureConnectionRequiredException;
11
import org.eclipse.tptp.platform.execution.exceptions.UntrustedAgentControllerException;
12
13
public class ConnectionFactory {
14
	public static IConnection createConnection (INode node, ConnectionInfo conInfo) throws LoginFailedException, 
15
		UntrustedAgentControllerException, IOException, ReconnectRequestedException, SecureConnectionRequiredException,
16
		NotConnectedException {
17
		
18
		ConnectionImpl con = null;
19
		boolean securityRequired = false;
20
21
		try {
22
			con = new ConnectionImpl();
23
			con.connect(node, conInfo);
24
		} catch (SecureConnectionRequiredException e) {
25
			securityRequired = true;
26
		}
27
	
28
		if (!securityRequired) return con;	// insecure connection
29
		
30
		SecureConnectionImpl secCon = new SecureConnectionImpl ();
31
			
32
		if (!secCon.connect(node, con)) {
33
			secCon.close();
34
			secCon = null;
35
		}		
36
			
37
		return secCon;
38
	}
39
}
(-)src/org/eclipse/tptp/platform/execution/util/internal/AgentControllerFactory.java (+161 lines)
Added Link Here
1
package org.eclipse.tptp.platform.execution.util.internal;
2
3
import org.eclipse.tptp.platform.execution.client.core.ConnectionInfo;
4
import org.eclipse.tptp.platform.execution.client.core.IAgentController;
5
import org.eclipse.tptp.platform.execution.client.core.INode;
6
import org.eclipse.tptp.platform.execution.client.core.NodeFactory;
7
import org.eclipse.tptp.platform.execution.exceptions.AgentControllerUnavailableException;
8
import org.eclipse.tptp.platform.execution.exceptions.LoginFailedException;
9
import org.eclipse.tptp.platform.execution.exceptions.SecureConnectionRequiredException;
10
import org.eclipse.tptp.platform.execution.security.User;
11
12
public class AgentControllerFactory implements IAgentControllerFactory {
13
	/**
14
	 * The incremental wait times
15
	 */
16
	public static final int INCREMENTAL_WAIT = 100;
17
18
	/**
19
	 * The total incremental wait
20
	 */
21
	public static final int TOTAL_WAIT = 100;
22
23
	public IAgentController createConnection(String hostName, int portNumber) throws Exception {
24
		IAgentController ac = null;
25
		EstablishConnection establishConnection = new EstablishConnection(hostName, portNumber);
26
		String userName = null;
27
		boolean lookingForUser = true;
28
		int retry = 0;
29
		
30
		do {
31
			Thread ect = new Thread(establishConnection);
32
			ect.start();
33
			/* Wait for a maximum of 10 seconds before bailing out */
34
			ect.join(TOTAL_WAIT*INCREMENTAL_WAIT);
35
			if (ect.isAlive()) ect.interrupt();
36
			
37
			Exception error = establishConnection.getException();
38
			if (error != null) throw error;
39
			
40
			ac = establishConnection.getConnection();
41
			if (ac == null) {
42
				throw new AgentControllerUnavailableException("");
43
			}
44
			
45
			if (ac.isAuthenticated()) break;
46
			
47
			User user = null;
48
			if (lookingForUser) {
49
				user = findUser(hostName);
50
				lookingForUser = false;
51
				if (user != null) {
52
					userName = user.getName();
53
					establishConnection.setUser(user);
54
					continue;		// try it
55
				}
56
			}
57
			
58
			user = promptAuthentication(hostName, userName);
59
			if(user == null) break;
60
61
			userName = user.getName();
62
			establishConnection.setUser(user);
63
		} while (retry++ < 3);
64
65
		if (!ac.isAuthenticated()) {
66
			try { ac.disconnect(); } catch (Exception e) {}
67
			throw new LoginFailedException("Authentication failed");
68
		}
69
		
70
		return ac;
71
	}
72
73
	/*
74
	 * The establishment of the connection should be done in a separate
75
	 * thread.
76
	 */
77
	class EstablishConnection implements Runnable {
78
		private String host;
79
		private int port;
80
		private Exception e;
81
		private IAgentController ac;
82
		private User user;
83
		private INode node;
84
85
		public EstablishConnection (String host, int port) {
86
			this.host = host;
87
			this.port = port;
88
			
89
			node = null;
90
		}
91
		
92
		public void run() {
93
			ac = null;
94
			e = null;
95
96
			if (node == null) {
97
				try {
98
					node = NodeFactory.createNode(host);
99
				} catch (Exception ex) {
100
					node = null;
101
				}
102
			
103
				if (node == null) return;
104
			}
105
			
106
			ConnectionInfo connInfo = new ConnectionInfo();
107
108
			connInfo.setHostName(host);
109
			connInfo.setPort(port);
110
			
111
			try {
112
				if (user == null)
113
					ac = node.connect(connInfo);
114
				else
115
					ac = node.connect(connInfo, user);
116
117
				/* Notify that the connection is done */
118
			} catch (LoginFailedException e) {
119
			} catch (SecureConnectionRequiredException e) {
120
			} catch (Exception e) {
121
				/*
122
				 * For some reason Sun JDK 1.5_06 has problems resolving the
123
				 * hostname "localhost". As a workaround change it to
124
				 * 127.0.0.1
125
				 */
126
127
				this.e = e;
128
				
129
				if ("localhost".equals(connInfo.getHostName())) {
130
					connInfo.setHostName("127.0.0.1");
131
				
132
					try {
133
						ac = node.connect(connInfo);
134
						this.e = null;
135
					} catch (Exception ex) {}
136
				}
137
			}
138
		}
139
140
		public Exception getException() {
141
			return e;
142
		}
143
144
		public IAgentController getConnection() {
145
			return ac;
146
		}
147
		
148
		public void setUser(User user) {
149
			this.user = user;
150
		}
151
	}
152
153
	// 	to prevent multiple User registration, to be substituted by descendants
154
	public User findUser(String hostName) {
155
		return null;
156
	}
157
					
158
	public User promptAuthentication(String hostName, String userName) {
159
		return null;
160
	}
161
}
(-)src/org/eclipse/tptp/platform/execution/samples/SecureClientAC.java (+118 lines)
Added Link Here
1
package org.eclipse.tptp.platform.execution.samples;
2
3
import org.eclipse.tptp.platform.execution.client.agent.*;
4
import org.eclipse.tptp.platform.execution.client.core.*;
5
import org.eclipse.tptp.platform.execution.security.User;
6
import org.eclipse.tptp.platform.execution.util.*;
7
8
public class SecureClientAC {
9
	public final static String HOST = "localhost";
10
	public final static int PORT = 10006;
11
	
12
	public static void main(String[] args) {
13
		ConnectionInfo connInfo = null;
14
		IAgentController ac = null;
15
		INode node = null;
16
17
		System.out.println("Connecting to Agent Controller\n");
18
19
		try {
20
			node = NodeFactory.createNode(HOST);
21
			//Set the connection parameters required 
22
			connInfo = new ConnectionInfo();
23
			connInfo.setHostName(HOST);
24
			connInfo.setPort(PORT);
25
26
			ac = node.connect(connInfo);
27
		} catch (Exception e) {
28
			System.out.println("Error occurred while connecting to " + HOST + ":" + e);
29
		}
30
31
		if (ac == null) return;
32
33
		System.out.println("Connected to " + HOST + ":" + PORT);
34
		
35
		while (!ac.isAuthenticated()) {
36
			User user = getUser();
37
			if (user == null) {
38
				System.out.println("\nAuthentication failed");
39
				break;
40
			}
41
			
42
			try {
43
				ac = node.connect(connInfo, user);
44
			} catch (Exception e) {
45
				System.out.println("ex " + e);
46
			}
47
		}
48
49
		if (!ac.isAuthenticated()) {
50
			ac.disconnect();
51
			return;
52
		}
53
		
54
		try {
55
			ICollector timeCollector = (ICollector) ac.getAgent("org.eclipse.tptp.TimeCollector", "org.eclipse.tptp.platform.execution.client.agent.ICollector");
56
			if(timeCollector == null) {
57
				System.out.println("Agent not available, configure the agent and retry");
58
				ac.disconnect();
59
				return;
60
			}
61
				
62
			//Create the Data Connection required to recieve response from the collector;
63
			//The input to startMonitoring is the to establish the data connection between the client and 
64
			//the agent controller for the direction of data flow.
65
			//See constants for additional values.
66
			timeCollector.startMonitoring(TPTPDataPath.DATA_PATH_TWO_WAY);
67
			timeCollector.addDataListener(new IDataProcessor() {
68
				public void incomingData(byte[] buffer, int length, java.net.InetAddress peer) {
69
					String data = new String(buffer, 0, length);
70
					System.out.println("The Data received from TimeCollector - " + data.trim());
71
				}
72
							
73
				public void incomingData(char[] buffer, int length, java.net.InetAddress peer) {}
74
				public void invalidDataType(byte[] data, int length, java.net.InetAddress peer) {}
75
				public void waitingForData() {}
76
			});				
77
				
78
			//Send a message to Agent
79
				
80
			timeCollector.run();
81
			timeCollector.sendData("HELLO from org.eclipse.tptp.platform.execution plugin".getBytes());
82
				//Wait for the response to arrive
83
				Thread.sleep(2000);
84
				
85
			timeCollector.stop();
86
			
87
			Thread.sleep(1000); 
88
				// Disconnect from AC				
89
			ac.disconnect();
90
			System.out.println("disconnected");				
91
		}
92
		catch(Exception exp) {
93
			System.out.println("Error occurred while connecting to " + HOST + ":" + exp);
94
		}		
95
	}
96
	
97
	private static User getUser() {
98
		byte buf[] = new byte[256];
99
		int n;
100
		
101
		System.out.println("\nUser authentication.");
102
		System.out.print("Login: ");
103
		try { n = System.in.read(buf); } catch (Exception e) { n = 0; }
104
		if (n <= 0) return null;
105
106
		String login = new String(buf, 0, n).trim();
107
		if (login.length() == 0) return null;
108
		
109
		System.out.print("Password: ");
110
		try { n = System.in.read(buf); } catch (Exception e) { n = 0; }
111
		if (n <= 0) return null;
112
		
113
		String psw = new String(buf, 0, n).trim();
114
		if (psw.length() == 0) return null;
115
116
		return new User(null, login, psw);
117
	}
118
}

Return to bug 195644