ForwardedPortLocalTest_Stop_PortStarted_ChannelBound.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. using Microsoft.Extensions.Logging.Abstractions;
  7. using Microsoft.VisualStudio.TestTools.UnitTesting;
  8. using Moq;
  9. using Renci.SshNet.Channels;
  10. using Renci.SshNet.Common;
  11. namespace Renci.SshNet.Tests.Classes
  12. {
  13. [TestClass]
  14. public class ForwardedPortLocalTest_Stop_PortStarted_ChannelBound
  15. {
  16. private Mock<ISession> _sessionMock;
  17. private Mock<IConnectionInfo> _connectionInfoMock;
  18. private Mock<IChannelDirectTcpip> _channelMock;
  19. private ForwardedPortLocal _forwardedPort;
  20. private IList<EventArgs> _closingRegister;
  21. private IList<ExceptionEventArgs> _exceptionRegister;
  22. private IPEndPoint _localEndpoint;
  23. private IPEndPoint _remoteEndpoint;
  24. private Socket _client;
  25. private TimeSpan _bindSleepTime;
  26. private ManualResetEvent _channelBound;
  27. private ManualResetEvent _channelBindCompleted;
  28. [TestInitialize]
  29. public void Setup()
  30. {
  31. Arrange();
  32. Act();
  33. }
  34. [TestCleanup]
  35. public void Cleanup()
  36. {
  37. if (_client != null)
  38. {
  39. _client.Dispose();
  40. _client = null;
  41. }
  42. if (_forwardedPort != null)
  43. {
  44. _forwardedPort.Dispose();
  45. _forwardedPort = null;
  46. }
  47. if (_channelBound != null)
  48. {
  49. _channelBound.Dispose();
  50. _channelBound = null;
  51. }
  52. if (_channelBindCompleted != null)
  53. {
  54. _channelBindCompleted.Dispose();
  55. _channelBindCompleted = null;
  56. }
  57. }
  58. private void CreateMocks()
  59. {
  60. _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict);
  61. _sessionMock = new Mock<ISession>(MockBehavior.Strict);
  62. _sessionMock.Setup(p => p.SessionLoggerFactory).Returns(NullLoggerFactory.Instance);
  63. _channelMock = new Mock<IChannelDirectTcpip>(MockBehavior.Strict);
  64. }
  65. private void SetupData()
  66. {
  67. var random = new Random();
  68. _closingRegister = new List<EventArgs>();
  69. _exceptionRegister = new List<ExceptionEventArgs>();
  70. _localEndpoint = new IPEndPoint(IPAddress.Loopback, 8122);
  71. _remoteEndpoint = new IPEndPoint(IPAddress.Parse("193.168.1.5"), random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort));
  72. _bindSleepTime = TimeSpan.FromMilliseconds(random.Next(100, 500));
  73. _channelBound = new ManualResetEvent(false);
  74. _channelBindCompleted = new ManualResetEvent(false);
  75. _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), (uint)_localEndpoint.Port, _remoteEndpoint.Address.ToString(), (uint)_remoteEndpoint.Port);
  76. _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args);
  77. _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
  78. _forwardedPort.Session = _sessionMock.Object;
  79. _client = new Socket(_localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
  80. {
  81. ReceiveTimeout = 100,
  82. SendTimeout = 100,
  83. SendBufferSize = 0
  84. };
  85. }
  86. private void SetupMocks()
  87. {
  88. _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15));
  89. _sessionMock.Setup(p => p.IsConnected).Returns(true);
  90. _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
  91. _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object);
  92. _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny<Socket>()));
  93. _channelMock.Setup(p => p.Bind()).Callback(() =>
  94. {
  95. _channelBound.Set();
  96. Thread.Sleep(_bindSleepTime);
  97. _channelBindCompleted.Set();
  98. });
  99. _channelMock.Setup(p => p.Dispose());
  100. }
  101. protected void Arrange()
  102. {
  103. CreateMocks();
  104. SetupData();
  105. SetupMocks();
  106. // start port
  107. _forwardedPort.Start();
  108. // connect to port
  109. _client.Connect(_localEndpoint);
  110. // wait for SOCKS client to bind to channel
  111. Assert.IsTrue(_channelBound.WaitOne(TimeSpan.FromMilliseconds(200)));
  112. }
  113. protected void Act()
  114. {
  115. _forwardedPort.Stop();
  116. }
  117. [TestMethod]
  118. public void ShouldBlockUntilBindHasCompleted()
  119. {
  120. Assert.IsTrue(_channelBindCompleted.WaitOne(0));
  121. }
  122. [TestMethod]
  123. public void IsStartedShouldReturnFalse()
  124. {
  125. Assert.IsFalse(_forwardedPort.IsStarted);
  126. }
  127. [TestMethod]
  128. public void ForwardedPortShouldRefuseNewConnections()
  129. {
  130. using (var client = new Socket(_localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
  131. {
  132. try
  133. {
  134. client.Connect(_localEndpoint);
  135. Assert.Fail();
  136. }
  137. catch (SocketException ex)
  138. {
  139. Assert.AreEqual(SocketError.ConnectionRefused, ex.SocketErrorCode);
  140. }
  141. }
  142. }
  143. [TestMethod]
  144. public void BoundClientShouldNotBeClosed()
  145. {
  146. // the forwarded port itself does not close the client connection; when the channel is closed properly
  147. // it's the channel that will take care of closing the client connection
  148. //
  149. // we'll check if the client connection is still alive by attempting to receive, which should time out
  150. // as the forwarded port (or its channel) are not sending anything
  151. var buffer = new byte[1];
  152. try
  153. {
  154. _client.Receive(buffer);
  155. Assert.Fail();
  156. }
  157. catch (SocketException ex)
  158. {
  159. Assert.AreEqual(SocketError.TimedOut, ex.SocketErrorCode);
  160. }
  161. }
  162. [TestMethod]
  163. public void ClosingShouldHaveFiredOnce()
  164. {
  165. Assert.AreEqual(1, _closingRegister.Count);
  166. }
  167. [TestMethod]
  168. public void ExceptionShouldNotHaveFired()
  169. {
  170. Assert.AreEqual(0, _exceptionRegister.Count);
  171. }
  172. [TestMethod]
  173. public void OpenOnChannelShouldBeInvokedOnce()
  174. {
  175. _channelMock.Verify(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny<Socket>()), Times.Once);
  176. }
  177. [TestMethod]
  178. public void BindOnChannelShouldBeInvokedOnce()
  179. {
  180. _channelMock.Verify(p => p.Bind(), Times.Once);
  181. }
  182. [TestMethod]
  183. public void DisposeOnChannelShouldBeInvokedOnce()
  184. {
  185. _channelMock.Verify(p => p.Dispose(), Times.Once);
  186. }
  187. }
  188. }