| | | 1 | | using System; |
| | | 2 | | using System.Globalization; |
| | | 3 | | using System.Net; |
| | | 4 | | using System.Threading; |
| | | 5 | | |
| | | 6 | | using Renci.SshNet.Abstractions; |
| | | 7 | | using Renci.SshNet.Common; |
| | | 8 | | using Renci.SshNet.Messages.Connection; |
| | | 9 | | |
| | | 10 | | namespace Renci.SshNet |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Provides functionality for remote port forwarding. |
| | | 14 | | /// </summary> |
| | | 15 | | public class ForwardedPortRemote : ForwardedPort |
| | | 16 | | { |
| | | 17 | | private ForwardedPortStatus _status; |
| | | 18 | | private bool _requestStatus; |
| | 206 | 19 | | private EventWaitHandle _globalRequestResponse = new AutoResetEvent(initialState: false); |
| | | 20 | | private CountdownEvent _pendingChannelCountdown; |
| | | 21 | | private bool _isDisposed; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Gets a value indicating whether port forwarding is started. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <value> |
| | | 27 | | /// <see langword="true"/> if port forwarding is started; otherwise, <see langword="false"/>. |
| | | 28 | | /// </value> |
| | | 29 | | public override bool IsStarted |
| | | 30 | | { |
| | 1284 | 31 | | get { return _status == ForwardedPortStatus.Started; } |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Gets the bound host. |
| | | 36 | | /// </summary> |
| | 1004 | 37 | | public IPAddress BoundHostAddress { get; private set; } |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// Gets the bound host. |
| | | 41 | | /// </summary> |
| | | 42 | | public string BoundHost |
| | | 43 | | { |
| | | 44 | | get |
| | 798 | 45 | | { |
| | 798 | 46 | | return BoundHostAddress.ToString(); |
| | 798 | 47 | | } |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Gets the bound port. |
| | | 52 | | /// </summary> |
| | 1225 | 53 | | public uint BoundPort { get; private set; } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Gets the forwarded host. |
| | | 57 | | /// </summary> |
| | 268 | 58 | | public IPAddress HostAddress { get; private set; } |
| | | 59 | | |
| | | 60 | | /// <summary> |
| | | 61 | | /// Gets the forwarded host. |
| | | 62 | | /// </summary> |
| | | 63 | | public string Host |
| | | 64 | | { |
| | | 65 | | get |
| | 0 | 66 | | { |
| | 0 | 67 | | return HostAddress.ToString(); |
| | 0 | 68 | | } |
| | | 69 | | } |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// Gets the forwarded port. |
| | | 73 | | /// </summary> |
| | 268 | 74 | | public uint Port { get; private set; } |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// Initializes a new instance of the <see cref="ForwardedPortRemote" /> class. |
| | | 78 | | /// </summary> |
| | | 79 | | /// <param name="boundHostAddress">The bound host address.</param> |
| | | 80 | | /// <param name="boundPort">The bound port.</param> |
| | | 81 | | /// <param name="hostAddress">The host address.</param> |
| | | 82 | | /// <param name="port">The port.</param> |
| | | 83 | | /// <exception cref="ArgumentNullException"><paramref name="boundHostAddress"/> is <see langword="null"/>.</exce |
| | | 84 | | /// <exception cref="ArgumentNullException"><paramref name="hostAddress"/> is <see langword="null"/>.</exception |
| | | 85 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="boundPort" /> is greater than <see cref="IPEnd |
| | | 86 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is greater than <see cref="IPEndPoint |
| | 206 | 87 | | public ForwardedPortRemote(IPAddress boundHostAddress, uint boundPort, IPAddress hostAddress, uint port) |
| | 206 | 88 | | { |
| | 206 | 89 | | if (boundHostAddress is null) |
| | 0 | 90 | | { |
| | 0 | 91 | | throw new ArgumentNullException(nameof(boundHostAddress)); |
| | | 92 | | } |
| | | 93 | | |
| | 206 | 94 | | if (hostAddress is null) |
| | 0 | 95 | | { |
| | 0 | 96 | | throw new ArgumentNullException(nameof(hostAddress)); |
| | | 97 | | } |
| | | 98 | | |
| | 206 | 99 | | boundPort.ValidatePort("boundPort"); |
| | 206 | 100 | | port.ValidatePort("port"); |
| | | 101 | | |
| | 206 | 102 | | BoundHostAddress = boundHostAddress; |
| | 206 | 103 | | BoundPort = boundPort; |
| | 206 | 104 | | HostAddress = hostAddress; |
| | 206 | 105 | | Port = port; |
| | 206 | 106 | | _status = ForwardedPortStatus.Stopped; |
| | 206 | 107 | | } |
| | | 108 | | |
| | | 109 | | /// <summary> |
| | | 110 | | /// Initializes a new instance of the <see cref="ForwardedPortRemote"/> class. |
| | | 111 | | /// </summary> |
| | | 112 | | /// <param name="boundPort">The bound port.</param> |
| | | 113 | | /// <param name="host">The host.</param> |
| | | 114 | | /// <param name="port">The port.</param> |
| | | 115 | | /// <example> |
| | | 116 | | /// <code source="..\..\src\Renci.SshNet.Tests\Classes\ForwardedPortRemoteTest.cs" region="Example SshClient |
| | | 117 | | /// </example> |
| | | 118 | | public ForwardedPortRemote(uint boundPort, string host, uint port) |
| | 3 | 119 | | : this(string.Empty, boundPort, host, port) |
| | 3 | 120 | | { |
| | 3 | 121 | | } |
| | | 122 | | |
| | | 123 | | /// <summary> |
| | | 124 | | /// Initializes a new instance of the <see cref="ForwardedPortRemote"/> class. |
| | | 125 | | /// </summary> |
| | | 126 | | /// <param name="boundHost">The bound host.</param> |
| | | 127 | | /// <param name="boundPort">The bound port.</param> |
| | | 128 | | /// <param name="host">The host.</param> |
| | | 129 | | /// <param name="port">The port.</param> |
| | | 130 | | public ForwardedPortRemote(string boundHost, uint boundPort, string host, uint port) |
| | 3 | 131 | | : this(DnsAbstraction.GetHostAddresses(boundHost)[0], |
| | 3 | 132 | | boundPort, |
| | 3 | 133 | | DnsAbstraction.GetHostAddresses(host)[0], |
| | 3 | 134 | | port) |
| | 3 | 135 | | { |
| | 3 | 136 | | } |
| | | 137 | | |
| | | 138 | | /// <summary> |
| | | 139 | | /// Starts remote port forwarding. |
| | | 140 | | /// </summary> |
| | | 141 | | protected override void StartPort() |
| | 137 | 142 | | { |
| | 137 | 143 | | if (!ForwardedPortStatus.ToStarting(ref _status)) |
| | 0 | 144 | | { |
| | 0 | 145 | | return; |
| | | 146 | | } |
| | | 147 | | |
| | 137 | 148 | | InitializePendingChannelCountdown(); |
| | | 149 | | |
| | | 150 | | try |
| | 137 | 151 | | { |
| | 137 | 152 | | Session.RegisterMessage("SSH_MSG_REQUEST_FAILURE"); |
| | 137 | 153 | | Session.RegisterMessage("SSH_MSG_REQUEST_SUCCESS"); |
| | 137 | 154 | | Session.RegisterMessage("SSH_MSG_CHANNEL_OPEN"); |
| | | 155 | | |
| | 137 | 156 | | Session.RequestSuccessReceived += Session_RequestSuccess; |
| | 137 | 157 | | Session.RequestFailureReceived += Session_RequestFailure; |
| | 137 | 158 | | Session.ChannelOpenReceived += Session_ChannelOpening; |
| | | 159 | | |
| | | 160 | | // send global request to start forwarding |
| | 137 | 161 | | Session.SendMessage(new TcpIpForwardGlobalRequestMessage(BoundHost, BoundPort)); |
| | | 162 | | |
| | | 163 | | // wat for response on global request to start direct tcpip |
| | 137 | 164 | | Session.WaitOnHandle(_globalRequestResponse); |
| | | 165 | | |
| | 137 | 166 | | if (!_requestStatus) |
| | 0 | 167 | | { |
| | 0 | 168 | | throw new SshException(string.Format(CultureInfo.CurrentCulture, "Port forwarding for '{0}' port '{1 |
| | | 169 | | } |
| | 137 | 170 | | } |
| | 0 | 171 | | catch (Exception) |
| | 0 | 172 | | { |
| | | 173 | | // mark port stopped |
| | 0 | 174 | | _status = ForwardedPortStatus.Stopped; |
| | | 175 | | |
| | | 176 | | // when the request to start port forward was rejected or failed, then we're no longer |
| | | 177 | | // interested in these events |
| | 0 | 178 | | Session.RequestSuccessReceived -= Session_RequestSuccess; |
| | 0 | 179 | | Session.RequestFailureReceived -= Session_RequestFailure; |
| | 0 | 180 | | Session.ChannelOpenReceived -= Session_ChannelOpening; |
| | | 181 | | |
| | 0 | 182 | | throw; |
| | | 183 | | } |
| | | 184 | | |
| | 137 | 185 | | _status = ForwardedPortStatus.Started; |
| | 137 | 186 | | } |
| | | 187 | | |
| | | 188 | | /// <summary> |
| | | 189 | | /// Stops remote port forwarding. |
| | | 190 | | /// </summary> |
| | | 191 | | /// <param name="timeout">The maximum amount of time to wait for the port to stop.</param> |
| | | 192 | | protected override void StopPort(TimeSpan timeout) |
| | 224 | 193 | | { |
| | 224 | 194 | | if (!ForwardedPortStatus.ToStopping(ref _status)) |
| | 87 | 195 | | { |
| | 87 | 196 | | return; |
| | | 197 | | } |
| | | 198 | | |
| | 137 | 199 | | base.StopPort(timeout); |
| | | 200 | | |
| | | 201 | | // send global request to cancel direct tcpip |
| | 137 | 202 | | Session.SendMessage(new CancelTcpIpForwardGlobalRequestMessage(BoundHost, BoundPort)); |
| | | 203 | | |
| | | 204 | | // wait for response on global request to cancel direct tcpip or completion of message |
| | | 205 | | // listener loop (in which case response on global request can never be received) |
| | 137 | 206 | | _ = WaitHandle.WaitAny(new[] { _globalRequestResponse, Session.MessageListenerCompleted }, timeout); |
| | | 207 | | |
| | | 208 | | // unsubscribe from session events as either the tcpip forward is cancelled at the |
| | | 209 | | // server, or our session message loop has completed |
| | 137 | 210 | | Session.RequestSuccessReceived -= Session_RequestSuccess; |
| | 137 | 211 | | Session.RequestFailureReceived -= Session_RequestFailure; |
| | 137 | 212 | | Session.ChannelOpenReceived -= Session_ChannelOpening; |
| | | 213 | | |
| | | 214 | | // wait for pending channels to close |
| | 137 | 215 | | _ = _pendingChannelCountdown.Signal(); |
| | | 216 | | |
| | 137 | 217 | | if (!_pendingChannelCountdown.Wait(timeout)) |
| | 0 | 218 | | { |
| | | 219 | | // TODO: log as warning |
| | 0 | 220 | | DiagnosticAbstraction.Log("Timeout waiting for pending channels in remote forwarded port to close."); |
| | 0 | 221 | | } |
| | | 222 | | |
| | 137 | 223 | | _status = ForwardedPortStatus.Stopped; |
| | 224 | 224 | | } |
| | | 225 | | |
| | | 226 | | /// <summary> |
| | | 227 | | /// Ensures the current instance is not disposed. |
| | | 228 | | /// </summary> |
| | | 229 | | /// <exception cref="ObjectDisposedException">The current instance is disposed.</exception> |
| | | 230 | | protected override void CheckDisposed() |
| | 191 | 231 | | { |
| | | 232 | | #if NET7_0_OR_GREATER |
| | 128 | 233 | | ObjectDisposedException.ThrowIf(_isDisposed, this); |
| | | 234 | | #else |
| | 63 | 235 | | if (_isDisposed) |
| | 3 | 236 | | { |
| | 3 | 237 | | throw new ObjectDisposedException(GetType().FullName); |
| | | 238 | | } |
| | | 239 | | #endif // NET7_0_OR_GREATER |
| | 182 | 240 | | } |
| | | 241 | | |
| | | 242 | | private void Session_ChannelOpening(object sender, MessageEventArgs<ChannelOpenMessage> e) |
| | 121 | 243 | | { |
| | 121 | 244 | | var channelOpenMessage = e.Message; |
| | 121 | 245 | | if (channelOpenMessage.Info is ForwardedTcpipChannelInfo info) |
| | 118 | 246 | | { |
| | | 247 | | // Ensure this is the corresponding request |
| | 118 | 248 | | if (info.ConnectedAddress == BoundHost && info.ConnectedPort == BoundPort) |
| | 110 | 249 | | { |
| | 110 | 250 | | if (!IsStarted) |
| | 48 | 251 | | { |
| | 48 | 252 | | Session.SendMessage(new ChannelOpenFailureMessage(channelOpenMessage.LocalChannelNumber, |
| | 48 | 253 | | string.Empty, |
| | 48 | 254 | | ChannelOpenFailureMessage.AdministrativelyProh |
| | 48 | 255 | | return; |
| | | 256 | | } |
| | | 257 | | |
| | 62 | 258 | | ThreadAbstraction.ExecuteThread(() => |
| | 62 | 259 | | { |
| | 62 | 260 | | // capture the countdown event that we're adding a count to, as we need to make sure that we |
| | 62 | 261 | | // that same instance; the instance field for the countdown event is re-initialize when the |
| | 62 | 262 | | // and that time there may still be pending requests |
| | 62 | 263 | | var pendingChannelCountdown = _pendingChannelCountdown; |
| | 62 | 264 | | |
| | 62 | 265 | | pendingChannelCountdown.AddCount(); |
| | 62 | 266 | | |
| | 62 | 267 | | try |
| | 62 | 268 | | { |
| | 62 | 269 | | RaiseRequestReceived(info.OriginatorAddress, info.OriginatorPort); |
| | 62 | 270 | | |
| | 62 | 271 | | using (var channel = Session.CreateChannelForwardedTcpip(channelOpenMessage.LocalChannel |
| | 62 | 272 | | { |
| | 62 | 273 | | channel.Exception += Channel_Exception; |
| | 62 | 274 | | channel.Bind(new IPEndPoint(HostAddress, (int) Port), this); |
| | 62 | 275 | | } |
| | 62 | 276 | | } |
| | 0 | 277 | | catch (Exception exp) |
| | 0 | 278 | | { |
| | 0 | 279 | | RaiseExceptionEvent(exp); |
| | 0 | 280 | | } |
| | 62 | 281 | | finally |
| | 62 | 282 | | { |
| | 62 | 283 | | // take into account that CountdownEvent has since been disposed; when stopping the port |
| | 62 | 284 | | // wait for a given time for the channels to close, but once that timeout period has ela |
| | 62 | 285 | | // the CountdownEvent will be disposed |
| | 62 | 286 | | try |
| | 62 | 287 | | { |
| | 62 | 288 | | _ = pendingChannelCountdown.Signal(); |
| | 62 | 289 | | } |
| | 0 | 290 | | catch (ObjectDisposedException) |
| | 0 | 291 | | { |
| | 62 | 292 | | // Ignore any ObjectDisposedException |
| | 0 | 293 | | } |
| | 62 | 294 | | } |
| | 124 | 295 | | }); |
| | 62 | 296 | | } |
| | 70 | 297 | | } |
| | 121 | 298 | | } |
| | | 299 | | |
| | | 300 | | /// <summary> |
| | | 301 | | /// Initializes the <see cref="CountdownEvent"/>. |
| | | 302 | | /// </summary> |
| | | 303 | | /// <remarks> |
| | | 304 | | /// <para> |
| | | 305 | | /// When the port is started for the first time, a <see cref="CountdownEvent"/> is created with an initial count |
| | | 306 | | /// of <c>1</c>. |
| | | 307 | | /// </para> |
| | | 308 | | /// <para> |
| | | 309 | | /// On subsequent (re)starts, we'll dispose the current <see cref="CountdownEvent"/> and create a new one with |
| | | 310 | | /// initial count of <c>1</c>. |
| | | 311 | | /// </para> |
| | | 312 | | /// </remarks> |
| | | 313 | | private void InitializePendingChannelCountdown() |
| | 137 | 314 | | { |
| | 137 | 315 | | var original = Interlocked.Exchange(ref _pendingChannelCountdown, new CountdownEvent(1)); |
| | 137 | 316 | | original?.Dispose(); |
| | 137 | 317 | | } |
| | | 318 | | |
| | | 319 | | private void Channel_Exception(object sender, ExceptionEventArgs exceptionEventArgs) |
| | 0 | 320 | | { |
| | 0 | 321 | | RaiseExceptionEvent(exceptionEventArgs.Exception); |
| | 0 | 322 | | } |
| | | 323 | | |
| | | 324 | | private void Session_RequestFailure(object sender, EventArgs e) |
| | 0 | 325 | | { |
| | 0 | 326 | | _requestStatus = false; |
| | 0 | 327 | | _ = _globalRequestResponse.Set(); |
| | 0 | 328 | | } |
| | | 329 | | |
| | | 330 | | private void Session_RequestSuccess(object sender, MessageEventArgs<RequestSuccessMessage> e) |
| | 223 | 331 | | { |
| | 223 | 332 | | _requestStatus = true; |
| | | 333 | | |
| | 223 | 334 | | if (BoundPort == 0) |
| | 0 | 335 | | { |
| | 0 | 336 | | BoundPort = (e.Message.BoundPort is null) ? 0 : e.Message.BoundPort.Value; |
| | 0 | 337 | | } |
| | | 338 | | |
| | 223 | 339 | | _ = _globalRequestResponse.Set(); |
| | 223 | 340 | | } |
| | | 341 | | |
| | | 342 | | /// <summary> |
| | | 343 | | /// Releases unmanaged and - optionally - managed resources. |
| | | 344 | | /// </summary> |
| | | 345 | | /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langwor |
| | | 346 | | protected override void Dispose(bool disposing) |
| | 290 | 347 | | { |
| | 290 | 348 | | if (_isDisposed) |
| | 84 | 349 | | { |
| | 84 | 350 | | return; |
| | | 351 | | } |
| | | 352 | | |
| | 206 | 353 | | base.Dispose(disposing); |
| | | 354 | | |
| | 206 | 355 | | if (disposing) |
| | 201 | 356 | | { |
| | 201 | 357 | | var session = Session; |
| | 201 | 358 | | if (session != null) |
| | 0 | 359 | | { |
| | 0 | 360 | | Session = null; |
| | 0 | 361 | | session.RequestSuccessReceived -= Session_RequestSuccess; |
| | 0 | 362 | | session.RequestFailureReceived -= Session_RequestFailure; |
| | 0 | 363 | | session.ChannelOpenReceived -= Session_ChannelOpening; |
| | 0 | 364 | | } |
| | | 365 | | |
| | 201 | 366 | | var globalRequestResponse = _globalRequestResponse; |
| | 201 | 367 | | if (globalRequestResponse != null) |
| | 201 | 368 | | { |
| | 201 | 369 | | _globalRequestResponse = null; |
| | 201 | 370 | | globalRequestResponse.Dispose(); |
| | 201 | 371 | | } |
| | | 372 | | |
| | 201 | 373 | | var pendingRequestsCountdown = _pendingChannelCountdown; |
| | 201 | 374 | | if (pendingRequestsCountdown != null) |
| | 123 | 375 | | { |
| | 123 | 376 | | _pendingChannelCountdown = null; |
| | 123 | 377 | | pendingRequestsCountdown.Dispose(); |
| | 123 | 378 | | } |
| | 201 | 379 | | } |
| | | 380 | | |
| | 206 | 381 | | _isDisposed = true; |
| | 290 | 382 | | } |
| | | 383 | | |
| | | 384 | | /// <summary> |
| | | 385 | | /// Finalizes an instance of the <see cref="ForwardedPortRemote"/> class. |
| | | 386 | | /// </summary> |
| | | 387 | | ~ForwardedPortRemote() |
| | 10 | 388 | | { |
| | 5 | 389 | | Dispose(disposing: false); |
| | 10 | 390 | | } |
| | | 391 | | } |
| | | 392 | | } |