aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/ch/ethz/ssh2/channel/RemoteAcceptThread.java
blob: 57a7f88022b7999643fc8310394cc31ecfd04190 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved.
 * Please refer to the LICENSE.txt for licensing details.
 */
package ch.ethz.ssh2.channel;

import java.io.IOException;
import java.net.Socket;

import ch.ethz.ssh2.log.Logger;

/**
 * RemoteAcceptThread.
 *
 * @author Christian Plattner
 * @version $Id: RemoteAcceptThread.java 41 2011-06-02 10:36:41Z dkocher@sudo.ch $
 */
public class RemoteAcceptThread extends Thread
{
	private static final Logger log = Logger.getLogger(RemoteAcceptThread.class);

	Channel c;

	String remoteConnectedAddress;
	int remoteConnectedPort;
	String remoteOriginatorAddress;
	int remoteOriginatorPort;
	String targetAddress;
	int targetPort;

	Socket s;

	public RemoteAcceptThread(Channel c, String remoteConnectedAddress, int remoteConnectedPort,
							  String remoteOriginatorAddress, int remoteOriginatorPort, String targetAddress, int targetPort)
	{
		this.c = c;
		this.remoteConnectedAddress = remoteConnectedAddress;
		this.remoteConnectedPort = remoteConnectedPort;
		this.remoteOriginatorAddress = remoteOriginatorAddress;
		this.remoteOriginatorPort = remoteOriginatorPort;
		this.targetAddress = targetAddress;
		this.targetPort = targetPort;

		log.debug("RemoteAcceptThread: " + remoteConnectedAddress + "/" + remoteConnectedPort + ", R: "
				+ remoteOriginatorAddress + "/" + remoteOriginatorPort);
	}

	@Override
	public void run()
	{
		try
		{
			c.cm.sendOpenConfirmation(c);

			s = new Socket(targetAddress, targetPort);

			StreamForwarder r2l = new StreamForwarder(c, null, null, c.getStdoutStream(), s.getOutputStream(),
					"RemoteToLocal");
			StreamForwarder l2r = new StreamForwarder(c, null, null, s.getInputStream(), c.getStdinStream(),
					"LocalToRemote");

			/* No need to start two threads, one can be executed in the current thread */

			r2l.setDaemon(true);
			r2l.start();
			l2r.run();

			while (r2l.isAlive())
			{
				try
				{
					r2l.join();
				}
				catch (InterruptedException ignored)
				{
				}
			}

			/* If the channel is already closed, then this is a no-op */

			c.cm.closeChannel(c, "EOF on both streams reached.", true);
			s.close();
		}
		catch (IOException e)
		{
			log.warning("IOException in proxy code: " + e.getMessage());

			try
			{
				c.cm.closeChannel(c, "IOException in proxy code (" + e.getMessage() + ")", true);
			}
			catch (IOException ignored)
			{
			}
			try
			{
				if (s != null)
					s.close();
			}
			catch (IOException ignored)
			{
			}
		}
	}
}