| | | 1 | | using System; |
| | | 2 | | using System.Net; |
| | | 3 | | using System.Net.Sockets; |
| | | 4 | | using System.Threading; |
| | | 5 | | |
| | | 6 | | using Renci.SshNet.Abstractions; |
| | | 7 | | using Renci.SshNet.Common; |
| | | 8 | | |
| | | 9 | | namespace Renci.SshNet |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Provides functionality for local port forwarding. |
| | | 13 | | /// </summary> |
| | | 14 | | public partial class ForwardedPortLocal : ForwardedPort |
| | | 15 | | { |
| | | 16 | | private ForwardedPortStatus _status; |
| | | 17 | | private bool _isDisposed; |
| | | 18 | | private Socket _listener; |
| | | 19 | | private CountdownEvent _pendingChannelCountdown; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Gets the bound host. |
| | | 23 | | /// </summary> |
| | 420 | 24 | | public string BoundHost { get; private set; } |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// Gets the bound port. |
| | | 28 | | /// </summary> |
| | 580 | 29 | | public uint BoundPort { get; private set; } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Gets the forwarded host. |
| | | 33 | | /// </summary> |
| | 458 | 34 | | public string Host { get; private set; } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Gets the forwarded port. |
| | | 38 | | /// </summary> |
| | 452 | 39 | | public uint Port { get; private set; } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Gets a value indicating whether port forwarding is started. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <value> |
| | | 45 | | /// <see langword="true"/> if port forwarding is started; otherwise, <see langword="false"/>. |
| | | 46 | | /// </value> |
| | | 47 | | public override bool IsStarted |
| | | 48 | | { |
| | 1995 | 49 | | get { return _status == ForwardedPortStatus.Started; } |
| | | 50 | | } |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// Initializes a new instance of the <see cref="ForwardedPortLocal"/> class. |
| | | 54 | | /// </summary> |
| | | 55 | | /// <param name="boundPort">The bound port.</param> |
| | | 56 | | /// <param name="host">The host.</param> |
| | | 57 | | /// <param name="port">The port.</param> |
| | | 58 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="boundPort" /> is greater than <see cref="IPEnd |
| | | 59 | | /// <exception cref="ArgumentNullException"><paramref name="host"/> is <see langword="null"/>.</exception> |
| | | 60 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is greater than <see cref="IPEndPoint |
| | | 61 | | /// <example> |
| | | 62 | | /// <code source="..\..\src\Renci.SshNet.Tests\Classes\ForwardedPortLocalTest.cs" region="Example SshClient |
| | | 63 | | /// </example> |
| | | 64 | | public ForwardedPortLocal(uint boundPort, string host, uint port) |
| | 3 | 65 | | : this(string.Empty, boundPort, host, port) |
| | 3 | 66 | | { |
| | 3 | 67 | | } |
| | | 68 | | |
| | | 69 | | /// <summary> |
| | | 70 | | /// Initializes a new instance of the <see cref="ForwardedPortLocal"/> class. |
| | | 71 | | /// </summary> |
| | | 72 | | /// <param name="boundHost">The bound host.</param> |
| | | 73 | | /// <param name="host">The host.</param> |
| | | 74 | | /// <param name="port">The port.</param> |
| | | 75 | | /// <exception cref="ArgumentNullException"><paramref name="boundHost"/> is <see langword="null"/>.</exception> |
| | | 76 | | /// <exception cref="ArgumentNullException"><paramref name="host"/> is <see langword="null"/>.</exception> |
| | | 77 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is greater than <see cref="IPEndPoint |
| | | 78 | | public ForwardedPortLocal(string boundHost, string host, uint port) |
| | 24 | 79 | | : this(boundHost, 0, host, port) |
| | 24 | 80 | | { |
| | 24 | 81 | | } |
| | | 82 | | |
| | | 83 | | /// <summary> |
| | | 84 | | /// Initializes a new instance of the <see cref="ForwardedPortLocal"/> class. |
| | | 85 | | /// </summary> |
| | | 86 | | /// <param name="boundHost">The bound host.</param> |
| | | 87 | | /// <param name="boundPort">The bound port.</param> |
| | | 88 | | /// <param name="host">The host.</param> |
| | | 89 | | /// <param name="port">The port.</param> |
| | | 90 | | /// <exception cref="ArgumentNullException"><paramref name="boundHost"/> is <see langword="null"/>.</exception> |
| | | 91 | | /// <exception cref="ArgumentNullException"><paramref name="host"/> is <see langword="null"/>.</exception> |
| | | 92 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="boundPort" /> is greater than <see cref="IPEnd |
| | | 93 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is greater than <see cref="IPEndPoint |
| | 254 | 94 | | public ForwardedPortLocal(string boundHost, uint boundPort, string host, uint port) |
| | 254 | 95 | | { |
| | 254 | 96 | | if (boundHost is null) |
| | 3 | 97 | | { |
| | 3 | 98 | | throw new ArgumentNullException(nameof(boundHost)); |
| | | 99 | | } |
| | | 100 | | |
| | 251 | 101 | | if (host is null) |
| | 3 | 102 | | { |
| | 3 | 103 | | throw new ArgumentNullException(nameof(host)); |
| | | 104 | | } |
| | | 105 | | |
| | 248 | 106 | | boundPort.ValidatePort("boundPort"); |
| | 248 | 107 | | port.ValidatePort("port"); |
| | | 108 | | |
| | 248 | 109 | | BoundHost = boundHost; |
| | 248 | 110 | | BoundPort = boundPort; |
| | 248 | 111 | | Host = host; |
| | 248 | 112 | | Port = port; |
| | 248 | 113 | | _status = ForwardedPortStatus.Stopped; |
| | 248 | 114 | | } |
| | | 115 | | |
| | | 116 | | /// <summary> |
| | | 117 | | /// Starts local port forwarding. |
| | | 118 | | /// </summary> |
| | | 119 | | protected override void StartPort() |
| | 166 | 120 | | { |
| | 166 | 121 | | if (!ForwardedPortStatus.ToStarting(ref _status)) |
| | 0 | 122 | | { |
| | 0 | 123 | | return; |
| | | 124 | | } |
| | | 125 | | |
| | | 126 | | try |
| | 166 | 127 | | { |
| | 166 | 128 | | InternalStart(); |
| | 166 | 129 | | } |
| | 0 | 130 | | catch (Exception) |
| | 0 | 131 | | { |
| | 0 | 132 | | _status = ForwardedPortStatus.Stopped; |
| | 0 | 133 | | throw; |
| | | 134 | | } |
| | 166 | 135 | | } |
| | | 136 | | |
| | | 137 | | /// <summary> |
| | | 138 | | /// Stops local port forwarding, and waits for the specified timeout until all pending |
| | | 139 | | /// requests are processed. |
| | | 140 | | /// </summary> |
| | | 141 | | /// <param name="timeout">The maximum amount of time to wait for pending requests to finish processing.</param> |
| | | 142 | | protected override void StopPort(TimeSpan timeout) |
| | 268 | 143 | | { |
| | 268 | 144 | | if (!ForwardedPortStatus.ToStopping(ref _status)) |
| | 102 | 145 | | { |
| | 102 | 146 | | return; |
| | | 147 | | } |
| | | 148 | | |
| | | 149 | | // signal existing channels that the port is closing |
| | 166 | 150 | | base.StopPort(timeout); |
| | | 151 | | |
| | | 152 | | // prevent new requests from getting processed |
| | 166 | 153 | | StopListener(); |
| | | 154 | | |
| | | 155 | | // wait for open channels to close |
| | 166 | 156 | | InternalStop(timeout); |
| | | 157 | | |
| | | 158 | | // mark port stopped |
| | 166 | 159 | | _status = ForwardedPortStatus.Stopped; |
| | 268 | 160 | | } |
| | | 161 | | |
| | | 162 | | /// <summary> |
| | | 163 | | /// Ensures the current instance is not disposed. |
| | | 164 | | /// </summary> |
| | | 165 | | /// <exception cref="ObjectDisposedException">The current instance is disposed.</exception> |
| | | 166 | | protected override void CheckDisposed() |
| | 220 | 167 | | { |
| | | 168 | | #if NET7_0_OR_GREATER |
| | 148 | 169 | | ObjectDisposedException.ThrowIf(_isDisposed, this); |
| | | 170 | | #else |
| | 72 | 171 | | if (_isDisposed) |
| | 3 | 172 | | { |
| | 3 | 173 | | throw new ObjectDisposedException(GetType().FullName); |
| | | 174 | | } |
| | | 175 | | #endif // NET7_0_OR_GREATER |
| | 211 | 176 | | } |
| | | 177 | | |
| | | 178 | | /// <summary> |
| | | 179 | | /// Releases unmanaged and - optionally - managed resources. |
| | | 180 | | /// </summary> |
| | | 181 | | /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langwor |
| | | 182 | | protected override void Dispose(bool disposing) |
| | 365 | 183 | | { |
| | 365 | 184 | | if (_isDisposed) |
| | 111 | 185 | | { |
| | 111 | 186 | | return; |
| | | 187 | | } |
| | | 188 | | |
| | 254 | 189 | | base.Dispose(disposing); |
| | 254 | 190 | | InternalDispose(disposing); |
| | 254 | 191 | | _isDisposed = true; |
| | 365 | 192 | | } |
| | | 193 | | |
| | | 194 | | /// <summary> |
| | | 195 | | /// Finalizes an instance of the <see cref="ForwardedPortLocal"/> class. |
| | | 196 | | /// </summary> |
| | | 197 | | ~ForwardedPortLocal() |
| | 48 | 198 | | { |
| | 24 | 199 | | Dispose(disposing: false); |
| | 48 | 200 | | } |
| | | 201 | | |
| | | 202 | | private void InternalStart() |
| | 166 | 203 | | { |
| | 166 | 204 | | var addr = DnsAbstraction.GetHostAddresses(BoundHost)[0]; |
| | 166 | 205 | | var ep = new IPEndPoint(addr, (int) BoundPort); |
| | | 206 | | |
| | 166 | 207 | | _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; |
| | 166 | 208 | | _listener.Bind(ep); |
| | 166 | 209 | | _listener.Listen(5); |
| | | 210 | | |
| | | 211 | | // update bound port (in case original was passed as zero) |
| | 166 | 212 | | BoundPort = (uint) ((IPEndPoint) _listener.LocalEndPoint).Port; |
| | | 213 | | |
| | 166 | 214 | | Session.ErrorOccured += Session_ErrorOccured; |
| | 166 | 215 | | Session.Disconnected += Session_Disconnected; |
| | | 216 | | |
| | 166 | 217 | | InitializePendingChannelCountdown(); |
| | | 218 | | |
| | | 219 | | // consider port started when we're listening for inbound connections |
| | 166 | 220 | | _status = ForwardedPortStatus.Started; |
| | | 221 | | |
| | 166 | 222 | | StartAccept(e: null); |
| | 166 | 223 | | } |
| | | 224 | | |
| | | 225 | | private void StartAccept(SocketAsyncEventArgs e) |
| | 232 | 226 | | { |
| | 232 | 227 | | if (e is null) |
| | 166 | 228 | | { |
| | | 229 | | #pragma warning disable CA2000 // Dispose objects before losing scope |
| | 166 | 230 | | e = new SocketAsyncEventArgs(); |
| | | 231 | | #pragma warning restore CA2000 // Dispose objects before losing scope |
| | 166 | 232 | | e.Completed += AcceptCompleted; |
| | 166 | 233 | | } |
| | | 234 | | else |
| | 66 | 235 | | { |
| | | 236 | | // clear the socket as we're reusing the context object |
| | 66 | 237 | | e.AcceptSocket = null; |
| | 66 | 238 | | } |
| | | 239 | | |
| | | 240 | | // only accept new connections while we are started |
| | 232 | 241 | | if (IsStarted) |
| | 232 | 242 | | { |
| | | 243 | | try |
| | 232 | 244 | | { |
| | 232 | 245 | | if (!_listener.AcceptAsync(e)) |
| | 0 | 246 | | { |
| | 0 | 247 | | AcceptCompleted(sender: null, e); |
| | 0 | 248 | | } |
| | 232 | 249 | | } |
| | 0 | 250 | | catch (ObjectDisposedException) |
| | 0 | 251 | | { |
| | 0 | 252 | | if (_status == ForwardedPortStatus.Stopping || _status == ForwardedPortStatus.Stopped) |
| | 0 | 253 | | { |
| | | 254 | | // ignore ObjectDisposedException while stopping or stopped |
| | 0 | 255 | | return; |
| | | 256 | | } |
| | | 257 | | |
| | 0 | 258 | | throw; |
| | | 259 | | } |
| | 232 | 260 | | } |
| | 232 | 261 | | } |
| | | 262 | | |
| | | 263 | | private void AcceptCompleted(object sender, SocketAsyncEventArgs e) |
| | 232 | 264 | | { |
| | 232 | 265 | | if (e.SocketError is SocketError.OperationAborted or SocketError.NotSocket) |
| | 166 | 266 | | { |
| | | 267 | | // server was stopped |
| | 166 | 268 | | return; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | // capture client socket |
| | 66 | 272 | | var clientSocket = e.AcceptSocket; |
| | | 273 | | |
| | 66 | 274 | | if (e.SocketError != SocketError.Success) |
| | 0 | 275 | | { |
| | | 276 | | // accept new connection |
| | 0 | 277 | | StartAccept(e); |
| | | 278 | | |
| | | 279 | | // dispose broken client socket |
| | 0 | 280 | | CloseClientSocket(clientSocket); |
| | 0 | 281 | | return; |
| | | 282 | | } |
| | | 283 | | |
| | | 284 | | // accept new connection |
| | 66 | 285 | | StartAccept(e); |
| | | 286 | | |
| | | 287 | | // process connection |
| | 66 | 288 | | ProcessAccept(clientSocket); |
| | 232 | 289 | | } |
| | | 290 | | |
| | | 291 | | private void ProcessAccept(Socket clientSocket) |
| | 66 | 292 | | { |
| | | 293 | | // close the client socket if we're no longer accepting new connections |
| | 66 | 294 | | if (!IsStarted) |
| | 0 | 295 | | { |
| | 0 | 296 | | CloseClientSocket(clientSocket); |
| | 0 | 297 | | return; |
| | | 298 | | } |
| | | 299 | | |
| | | 300 | | // capture the countdown event that we're adding a count to, as we need to make sure that we'll be signaling |
| | | 301 | | // that same instance; the instance field for the countdown event is re-initialized when the port is restart |
| | | 302 | | // and at that time there may still be pending requests |
| | 66 | 303 | | var pendingChannelCountdown = _pendingChannelCountdown; |
| | | 304 | | |
| | 66 | 305 | | pendingChannelCountdown.AddCount(); |
| | | 306 | | |
| | | 307 | | try |
| | 66 | 308 | | { |
| | 66 | 309 | | var originatorEndPoint = (IPEndPoint) clientSocket.RemoteEndPoint; |
| | | 310 | | |
| | 66 | 311 | | RaiseRequestReceived(originatorEndPoint.Address.ToString(), |
| | 66 | 312 | | (uint) originatorEndPoint.Port); |
| | | 313 | | |
| | 66 | 314 | | using (var channel = Session.CreateChannelDirectTcpip()) |
| | 66 | 315 | | { |
| | 66 | 316 | | channel.Exception += Channel_Exception; |
| | 66 | 317 | | channel.Open(Host, Port, this, clientSocket); |
| | 66 | 318 | | channel.Bind(); |
| | 66 | 319 | | } |
| | 66 | 320 | | } |
| | 0 | 321 | | catch (Exception exp) |
| | 0 | 322 | | { |
| | 0 | 323 | | RaiseExceptionEvent(exp); |
| | 0 | 324 | | CloseClientSocket(clientSocket); |
| | 0 | 325 | | } |
| | | 326 | | finally |
| | 66 | 327 | | { |
| | | 328 | | // take into account that CountdownEvent has since been disposed; when stopping the port we |
| | | 329 | | // wait for a given time for the channels to close, but once that timeout period has elapsed |
| | | 330 | | // the CountdownEvent will be disposed |
| | | 331 | | try |
| | 66 | 332 | | { |
| | 66 | 333 | | _ = pendingChannelCountdown.Signal(); |
| | 66 | 334 | | } |
| | 0 | 335 | | catch (ObjectDisposedException) |
| | 0 | 336 | | { |
| | | 337 | | // Ignore any ObjectDisposedException |
| | 0 | 338 | | } |
| | 66 | 339 | | } |
| | 66 | 340 | | } |
| | | 341 | | |
| | | 342 | | /// <summary> |
| | | 343 | | /// Initializes the <see cref="CountdownEvent"/>. |
| | | 344 | | /// </summary> |
| | | 345 | | /// <remarks> |
| | | 346 | | /// <para> |
| | | 347 | | /// When the port is started for the first time, a <see cref="CountdownEvent"/> is created with an initial count |
| | | 348 | | /// of <c>1</c>. |
| | | 349 | | /// </para> |
| | | 350 | | /// <para> |
| | | 351 | | /// On subsequent (re)starts, we'll dispose the current <see cref="CountdownEvent"/> and create a new one with |
| | | 352 | | /// initial count of <c>1</c>. |
| | | 353 | | /// </para> |
| | | 354 | | /// </remarks> |
| | | 355 | | private void InitializePendingChannelCountdown() |
| | 166 | 356 | | { |
| | 166 | 357 | | var original = Interlocked.Exchange(ref _pendingChannelCountdown, new CountdownEvent(1)); |
| | 166 | 358 | | original?.Dispose(); |
| | 166 | 359 | | } |
| | | 360 | | |
| | | 361 | | private static void CloseClientSocket(Socket clientSocket) |
| | 0 | 362 | | { |
| | 0 | 363 | | if (clientSocket.Connected) |
| | 0 | 364 | | { |
| | | 365 | | try |
| | 0 | 366 | | { |
| | 0 | 367 | | clientSocket.Shutdown(SocketShutdown.Send); |
| | 0 | 368 | | } |
| | 0 | 369 | | catch (Exception) |
| | 0 | 370 | | { |
| | | 371 | | // ignore exception when client socket was already closed |
| | 0 | 372 | | } |
| | 0 | 373 | | } |
| | | 374 | | |
| | 0 | 375 | | clientSocket.Dispose(); |
| | 0 | 376 | | } |
| | | 377 | | |
| | | 378 | | /// <summary> |
| | | 379 | | /// Interrupts the listener, and unsubscribes from <see cref="Session"/> events. |
| | | 380 | | /// </summary> |
| | | 381 | | private void StopListener() |
| | 166 | 382 | | { |
| | | 383 | | // close listener socket |
| | 166 | 384 | | _listener?.Dispose(); |
| | | 385 | | |
| | | 386 | | // unsubscribe from session events |
| | 166 | 387 | | var session = Session; |
| | 166 | 388 | | if (session != null) |
| | 166 | 389 | | { |
| | 166 | 390 | | session.ErrorOccured -= Session_ErrorOccured; |
| | 166 | 391 | | session.Disconnected -= Session_Disconnected; |
| | 166 | 392 | | } |
| | 166 | 393 | | } |
| | | 394 | | |
| | | 395 | | /// <summary> |
| | | 396 | | /// Waits for pending channels to close. |
| | | 397 | | /// </summary> |
| | | 398 | | /// <param name="timeout">The maximum time to wait for the pending channels to close.</param> |
| | | 399 | | private void InternalStop(TimeSpan timeout) |
| | 166 | 400 | | { |
| | 166 | 401 | | _ = _pendingChannelCountdown.Signal(); |
| | | 402 | | |
| | 166 | 403 | | if (!_pendingChannelCountdown.Wait(timeout)) |
| | 0 | 404 | | { |
| | | 405 | | // TODO: log as warning |
| | 0 | 406 | | DiagnosticAbstraction.Log("Timeout waiting for pending channels in local forwarded port to close."); |
| | 0 | 407 | | } |
| | 166 | 408 | | } |
| | | 409 | | |
| | | 410 | | private void InternalDispose(bool disposing) |
| | 254 | 411 | | { |
| | 254 | 412 | | if (disposing) |
| | 230 | 413 | | { |
| | 230 | 414 | | var listener = _listener; |
| | 230 | 415 | | if (listener is not null) |
| | 151 | 416 | | { |
| | 151 | 417 | | _listener = null; |
| | 151 | 418 | | listener.Dispose(); |
| | 151 | 419 | | } |
| | | 420 | | |
| | 230 | 421 | | var pendingRequestsCountdown = _pendingChannelCountdown; |
| | 230 | 422 | | if (pendingRequestsCountdown is not null) |
| | 151 | 423 | | { |
| | 151 | 424 | | _pendingChannelCountdown = null; |
| | 151 | 425 | | pendingRequestsCountdown.Dispose(); |
| | 151 | 426 | | } |
| | 230 | 427 | | } |
| | 254 | 428 | | } |
| | | 429 | | |
| | | 430 | | private void Session_Disconnected(object sender, EventArgs e) |
| | 0 | 431 | | { |
| | 0 | 432 | | var session = Session; |
| | 0 | 433 | | if (session is not null) |
| | 0 | 434 | | { |
| | 0 | 435 | | StopPort(session.ConnectionInfo.Timeout); |
| | 0 | 436 | | } |
| | 0 | 437 | | } |
| | | 438 | | |
| | | 439 | | private void Session_ErrorOccured(object sender, ExceptionEventArgs e) |
| | 0 | 440 | | { |
| | 0 | 441 | | var session = Session; |
| | 0 | 442 | | if (session is not null) |
| | 0 | 443 | | { |
| | 0 | 444 | | StopPort(session.ConnectionInfo.Timeout); |
| | 0 | 445 | | } |
| | 0 | 446 | | } |
| | | 447 | | |
| | | 448 | | private void Channel_Exception(object sender, ExceptionEventArgs e) |
| | 0 | 449 | | { |
| | 0 | 450 | | RaiseExceptionEvent(e.Exception); |
| | 0 | 451 | | } |
| | | 452 | | } |
| | | 453 | | } |