comparison src/com/trilead/ssh2/channel/LocalAcceptThread.java @ 0:0ce5cc452d02

initial version
author Carl Byington <carl@five-ten-sg.com>
date Thu, 22 May 2014 10:41:19 -0700
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:0ce5cc452d02
1
2 package com.trilead.ssh2.channel;
3
4 import java.io.IOException;
5 import java.net.InetSocketAddress;
6 import java.net.ServerSocket;
7 import java.net.Socket;
8
9 /**
10 * LocalAcceptThread.
11 *
12 * @author Christian Plattner, plattner@trilead.com
13 * @version $Id: LocalAcceptThread.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
14 */
15 public class LocalAcceptThread extends Thread implements IChannelWorkerThread {
16 ChannelManager cm;
17 String host_to_connect;
18 int port_to_connect;
19
20 final ServerSocket ss;
21
22 public LocalAcceptThread(ChannelManager cm, int local_port, String host_to_connect, int port_to_connect)
23 throws IOException {
24 this.cm = cm;
25 this.host_to_connect = host_to_connect;
26 this.port_to_connect = port_to_connect;
27 ss = new ServerSocket(local_port);
28 }
29
30 public LocalAcceptThread(ChannelManager cm, InetSocketAddress localAddress, String host_to_connect,
31 int port_to_connect) throws IOException {
32 this.cm = cm;
33 this.host_to_connect = host_to_connect;
34 this.port_to_connect = port_to_connect;
35 ss = new ServerSocket();
36 ss.bind(localAddress);
37 }
38
39 public void run() {
40 try {
41 cm.registerThread(this);
42 }
43 catch (IOException e) {
44 stopWorking();
45 return;
46 }
47
48 while (true) {
49 Socket s = null;
50
51 try {
52 s = ss.accept();
53 }
54 catch (IOException e) {
55 stopWorking();
56 return;
57 }
58
59 Channel cn = null;
60 StreamForwarder r2l = null;
61 StreamForwarder l2r = null;
62
63 try {
64 /* This may fail, e.g., if the remote port is closed (in optimistic terms: not open yet) */
65 cn = cm.openDirectTCPIPChannel(host_to_connect, port_to_connect, s.getInetAddress().getHostAddress(), s
66 .getPort());
67 }
68 catch (IOException e) {
69 /* Simply close the local socket and wait for the next incoming connection */
70 try {
71 s.close();
72 }
73 catch (IOException ignore) {
74 }
75
76 continue;
77 }
78
79 try {
80 r2l = new StreamForwarder(cn, null, s, cn.stdoutStream, s.getOutputStream(), "RemoteToLocal");
81 l2r = new StreamForwarder(cn, r2l, s, s.getInputStream(), cn.stdinStream, "LocalToRemote");
82 }
83 catch (IOException e) {
84 try {
85 /* This message is only visible during debugging, since we discard the channel immediatelly */
86 cn.cm.closeChannel(cn, "Weird error during creation of StreamForwarder (" + e.getMessage() + ")",
87 true);
88 }
89 catch (IOException ignore) {
90 }
91
92 continue;
93 }
94
95 r2l.setDaemon(true);
96 l2r.setDaemon(true);
97 r2l.start();
98 l2r.start();
99 }
100 }
101
102 public void stopWorking() {
103 try {
104 /* This will lead to an IOException in the ss.accept() call */
105 ss.close();
106 }
107 catch (IOException e) {
108 }
109 }
110 }