-
-
Notifications
You must be signed in to change notification settings - Fork 978
Expand file tree
/
Copy pathChannelDirectStreamLocal.cs
More file actions
309 lines (268 loc) · 10.8 KB
/
ChannelDirectStreamLocal.cs
File metadata and controls
309 lines (268 loc) · 10.8 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Connection;
namespace Renci.SshNet.Channels
{
/// <summary>
/// Implements "direct-streamlocal@openssh.com" SSH channel.
/// </summary>
internal class ChannelDirectStreamLocal : ClientChannel, IChannelDirectStreamLocal
{
private readonly object _socketLock = new object();
private EventWaitHandle _channelOpen = new AutoResetEvent(false);
private EventWaitHandle _channelData = new AutoResetEvent(false);
private IForwardedPort _forwardedPort;
private Socket _socket;
/// <summary>
/// Initializes a new <see cref="ChannelDirectStreamLocal"/> instance.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="localChannelNumber">The local channel number.</param>
/// <param name="localWindowSize">Size of the window.</param>
/// <param name="localPacketSize">Size of the packet.</param>
public ChannelDirectStreamLocal(ISession session, uint localChannelNumber, uint localWindowSize, uint localPacketSize)
: base(session, localChannelNumber, localWindowSize, localPacketSize)
{
}
/// <summary>
/// Gets the type of the channel.
/// </summary>
/// <value>
/// The type of the channel.
/// </value>
public override ChannelTypes ChannelType
{
get { return ChannelTypes.DirectStreamLocal; }
}
public void Open(string remoteSocket, IForwardedPort forwardedPort, Socket socket)
{
if (IsOpen)
throw new SshException("Channel is already open.");
if (!IsConnected)
throw new SshException("Session is not connected.");
lock (_socketLock)
{
_socket = socket;
}
_forwardedPort = forwardedPort;
_forwardedPort.Closing += ForwardedPort_Closing;
var originatorAddress = "";
var originatorPort = (uint)0;
if (socket.RemoteEndPoint is IPEndPoint)
{
var ep = (IPEndPoint)socket.RemoteEndPoint;
originatorAddress = ep.Address.ToString();
originatorPort = (uint) ep.Port;
}
SendMessage(new ChannelOpenMessage(LocalChannelNumber, LocalWindowSize, LocalPacketSize,
new DirectStreamLocalChannelInfo(remoteSocket, originatorAddress, originatorPort)));
// Wait for channel to open
WaitOnHandle(_channelOpen);
}
/// <summary>
/// Occurs as the forwarded port is being stopped.
/// </summary>
private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
{
// signal to the client that we will not send anything anymore; this should also interrupt the
// blocking receive in Bind if the client sends FIN/ACK in time
ShutdownSocket(SocketShutdown.Send);
// if the FIN/ACK is not sent in time by the remote client, then interrupt the blocking receive
// by closing the socket
CloseSocket();
}
/// <summary>
/// Binds channel to remote host.
/// </summary>
public void Bind()
{
// Cannot bind if channel is not open
if (!IsOpen)
return;
var buffer = new byte[RemotePacketSize];
SocketAbstraction.ReadContinuous(_socket, buffer, 0, buffer.Length, SendData);
// even though the client has disconnected, we still want to properly close the
// channel
//
// we'll do this in in Close() - invoked through Dispose(bool) - that way we have
// a single place from which we send an SSH_MSG_CHANNEL_EOF message and wait for
// the SSH_MSG_CHANNEL_CLOSE message
}
/// <summary>
/// Closes the socket, hereby interrupting the blocking receive in <see cref="Bind()"/>.
/// </summary>
private void CloseSocket()
{
if (_socket == null)
return;
lock (_socketLock)
{
if (_socket == null)
return;
// closing a socket actually disposes the socket, so we can safely dereference
// the field to avoid entering the lock again later
_socket.Dispose();
_socket = null;
}
}
/// <summary>
/// Shuts down the socket.
/// </summary>
/// <param name="how">One of the <see cref="SocketShutdown"/> values that specifies the operation that will no longer be allowed.</param>
private void ShutdownSocket(SocketShutdown how)
{
if (_socket == null)
return;
lock (_socketLock)
{
if (!_socket.IsConnected())
return;
try
{
_socket.Shutdown(how);
}
catch (SocketException ex)
{
// TODO: log as warning
DiagnosticAbstraction.Log("Failure shutting down socket: " + ex);
}
}
}
/// <summary>
/// Closes the channel, waiting for the SSH_MSG_CHANNEL_CLOSE message to be received from the server.
/// </summary>
protected override void Close()
{
var forwardedPort = _forwardedPort;
if (forwardedPort != null)
{
forwardedPort.Closing -= ForwardedPort_Closing;
_forwardedPort = null;
}
// signal to the client that we will not send anything anymore; this will also interrupt the
// blocking receive in Bind if the client sends FIN/ACK in time
//
// if the FIN/ACK is not sent in time, the socket will be closed after the channel is closed
ShutdownSocket(SocketShutdown.Send);
// close the SSH channel
base.Close();
// close the socket
CloseSocket();
}
/// <summary>
/// Called when channel data is received.
/// </summary>
/// <param name="data">The data.</param>
protected override void OnData(byte[] data)
{
base.OnData(data);
if (_socket != null)
{
lock (_socketLock)
{
if (_socket.IsConnected())
{
SocketAbstraction.Send(_socket, data, 0, data.Length);
}
}
}
}
/// <summary>
/// Called when channel is opened by the server.
/// </summary>
/// <param name="remoteChannelNumber">The remote channel number.</param>
/// <param name="initialWindowSize">Initial size of the window.</param>
/// <param name="maximumPacketSize">Maximum size of the packet.</param>
protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
{
base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
_channelOpen.Set();
}
protected override void OnOpenFailure(uint reasonCode, string description, string language)
{
base.OnOpenFailure(reasonCode, description, language);
_channelOpen.Set();
}
/// <summary>
/// Called when channel has no more data to receive.
/// </summary>
protected override void OnEof()
{
base.OnEof();
// the channel will send no more data, and hence it does not make sense to receive
// any more data from the client to send to the remote party (and we surely won't
// send anything anymore)
//
// this will also interrupt the blocking receive in Bind()
ShutdownSocket(SocketShutdown.Send);
}
/// <summary>
/// Called whenever an unhandled <see cref="Exception"/> occurs in <see cref="Session"/> causing
/// the message loop to be interrupted, or when an exception occurred processing a channel message.
/// </summary>
protected override void OnErrorOccured(Exception exp)
{
base.OnErrorOccured(exp);
// signal to the client that we will not send anything anymore; this will also interrupt the
// blocking receive in Bind if the client sends FIN/ACK in time
//
// if the FIN/ACK is not sent in time, the socket will be closed in Close(bool)
ShutdownSocket(SocketShutdown.Send);
}
/// <summary>
/// Called when the server wants to terminate the connection immmediately.
/// </summary>
/// <remarks>
/// The sender MUST NOT send or receive any data after this message, and
/// the recipient MUST NOT accept any data after receiving this message.
/// </remarks>
protected override void OnDisconnected()
{
base.OnDisconnected();
// the channel will accept or send no more data, and hence it does not make sense
// to accept any more data from the client (and we surely won't send anything
// anymore)
//
// so lets signal to the client that we will not send or receive anything anymore
// this will also interrupt the blocking receive in Bind()
ShutdownSocket(SocketShutdown.Both);
}
protected override void Dispose(bool disposing)
{
// make sure we've unsubscribed from all session events and closed the channel
// before we starting disposing
base.Dispose(disposing);
if (disposing)
{
if (_socket != null)
{
lock (_socketLock)
{
var socket = _socket;
if (socket != null)
{
_socket = null;
socket.Dispose();
}
}
}
var channelOpen = _channelOpen;
if (channelOpen != null)
{
_channelOpen = null;
channelOpen.Dispose();
}
var channelData = _channelData;
if (channelData != null)
{
_channelData = null;
channelData.Dispose();
}
}
}
}
}