-
-
Notifications
You must be signed in to change notification settings - Fork 978
Expand file tree
/
Copy pathJumpChannel.cs
More file actions
215 lines (177 loc) · 6.36 KB
/
JumpChannel.cs
File metadata and controls
215 lines (177 loc) · 6.36 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Renci.SshNet.Common;
namespace Renci.SshNet.Channels
{
/// <summary>
/// Implements "direct-tcpip" SSH channel.
/// </summary>
internal sealed class JumpChannel : IDisposable
{
private readonly ISession _session;
private readonly EventWaitHandle _channelOpen = new AutoResetEvent(initialState: false);
private Socket _listener;
/// <summary>
/// Gets the bound host.
/// </summary>
public string BoundHost { get; private set; }
/// <summary>
/// Gets the bound port.
/// </summary>
public uint BoundPort { get; private set; }
/// <summary>
/// Gets the forwarded host.
/// </summary>
public string Host { get; private set; }
/// <summary>
/// Gets the forwarded port.
/// </summary>
public uint Port { get; private set; }
/// <summary>
/// Gets a value indicating whether port forwarding is started.
/// </summary>
/// <value>
/// <c>true</c> if port forwarding is started; otherwise, <c>false</c>.
/// </value>
public bool IsStarted
{ get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="JumpChannel"/> class.
/// </summary>
/// <param name="session">The session used to create the channel.</param>
/// <param name="host">The host.</param>
/// <param name="port">The port.</param>
/// <exception cref="ArgumentNullException"><paramref name="host"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is greater than <see cref="IPEndPoint.MaxPort" />.</exception>
public JumpChannel(ISession session, string host, uint port)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
port.ValidatePort("port");
Host = host;
Port = port;
_session = session;
}
public Socket Connect()
{
var ep = new IPEndPoint(IPAddress.Loopback, 0);
_listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
_listener.Bind(ep);
_listener.Listen(1);
IsStarted = true;
// update bound port (in case original was passed as zero)
ep.Port = ((IPEndPoint)_listener.LocalEndPoint).Port;
using (var e = new SocketAsyncEventArgs())
{
e.Completed += AcceptCompleted;
// only accept new connections while we are started
if (!_listener.AcceptAsync(e))
{
AcceptCompleted(sender: null, e);
}
}
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ep);
// Wait for channel to open
_session.WaitOnHandle(_channelOpen);
_listener.Dispose();
_listener = null;
return socket;
}
#region IDisposable Members
private bool _isDisposed;
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
private void Dispose(bool disposing)
{
if (_isDisposed)
{
return;
}
if (disposing)
{
// Don't dispose the _session here, as it's considered 'owned' by the object that instantiated this JumpChannel (usually SSHConnector)
}
_isDisposed = true;
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="ForwardedPortLocal"/> is reclaimed by garbage collection.
/// </summary>
~JumpChannel()
{
Dispose(disposing: false);
}
#endregion
private void AcceptCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError is SocketError.OperationAborted or SocketError.NotSocket)
{
// server was stopped
return;
}
// capture client socket
var clientSocket = e.AcceptSocket;
if (e.SocketError != SocketError.Success)
{
// dispose broken client socket
CloseClientSocket(clientSocket);
return;
}
_ = _channelOpen.Set();
// process connection
ProcessAccept(clientSocket);
}
private void ProcessAccept(Socket clientSocket)
{
// close the client socket if we're no longer accepting new connections
if (!IsStarted)
{
CloseClientSocket(clientSocket);
return;
}
try
{
var originatorEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
using (var channel = _session.CreateChannelDirectTcpip())
{
channel.Open(Host, Port, forwardedPort: null, clientSocket);
channel.Bind();
}
}
catch
{
CloseClientSocket(clientSocket);
}
}
private static void CloseClientSocket(Socket clientSocket)
{
if (clientSocket.Connected)
{
try
{
clientSocket.Shutdown(SocketShutdown.Send);
}
catch (Exception)
{
// ignore exception when client socket was already closed
}
}
clientSocket.Dispose();
}
}
}