001: package ch.ethz.ssh2.channel;
002:
003: import java.io.IOException;
004: import java.net.ServerSocket;
005: import java.net.Socket;
006:
007: /**
008: * LocalAcceptThread.
009: *
010: * @author Christian Plattner, plattner@inf.ethz.ch
011: * @version $Id: LocalAcceptThread.java,v 1.7 2006/07/30 21:59:29 cplattne Exp $
012: */
013: public class LocalAcceptThread extends Thread implements
014: IChannelWorkerThread {
015: ChannelManager cm;
016: int local_port;
017: String host_to_connect;
018: int port_to_connect;
019:
020: final ServerSocket ss;
021:
022: public LocalAcceptThread(ChannelManager cm, int local_port,
023: String host_to_connect, int port_to_connect)
024: throws IOException {
025: this .cm = cm;
026: this .local_port = local_port;
027: this .host_to_connect = host_to_connect;
028: this .port_to_connect = port_to_connect;
029:
030: ss = new ServerSocket(local_port);
031: }
032:
033: public void run() {
034: try {
035: cm.registerThread(this );
036: } catch (IOException e) {
037: stopWorking();
038: return;
039: }
040:
041: while (true) {
042: Socket s = null;
043:
044: try {
045: s = ss.accept();
046: } catch (IOException e) {
047: stopWorking();
048: return;
049: }
050:
051: Channel cn = null;
052: StreamForwarder r2l = null;
053: StreamForwarder l2r = null;
054:
055: try {
056: /* This may fail, e.g., if the remote port is closed (in optimistic terms: not open yet) */
057:
058: cn = cm.openDirectTCPIPChannel(host_to_connect,
059: port_to_connect, s.getInetAddress()
060: .getHostAddress(), s.getPort());
061:
062: } catch (IOException e) {
063: /* Simply close the local socket and wait for the next incoming connection */
064:
065: try {
066: s.close();
067: } catch (IOException ignore) {
068: }
069:
070: continue;
071: }
072:
073: try {
074: r2l = new StreamForwarder(cn, null, null,
075: cn.stdoutStream, s.getOutputStream(),
076: "RemoteToLocal");
077: l2r = new StreamForwarder(cn, r2l, s, s
078: .getInputStream(), cn.stdinStream,
079: "LocalToRemote");
080: } catch (IOException e) {
081: try {
082: /* This message is only visible during debugging, since we discard the channel immediatelly */
083: cn.cm.closeChannel(cn,
084: "Weird error during creation of StreamForwarder ("
085: + e.getMessage() + ")", true);
086: } catch (IOException ignore) {
087: }
088:
089: continue;
090: }
091:
092: r2l.setDaemon(true);
093: l2r.setDaemon(true);
094: r2l.start();
095: l2r.start();
096: }
097: }
098:
099: public void stopWorking() {
100: try {
101: /* This will lead to an IOException in the ss.accept() call */
102: ss.close();
103: } catch (IOException e) {
104: }
105: }
106: }
|