ShellStreamTest_ReadExpect.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. using Microsoft.Extensions.Logging.Abstractions;
  8. using Microsoft.VisualStudio.TestTools.UnitTesting;
  9. using Moq;
  10. using Renci.SshNet.Abstractions;
  11. using Renci.SshNet.Channels;
  12. using Renci.SshNet.Common;
  13. namespace Renci.SshNet.Tests.Classes
  14. {
  15. [TestClass]
  16. public class ShellStreamTest_ReadExpect
  17. {
  18. private const int BufferSize = 1024;
  19. private ShellStream _shellStream;
  20. private ChannelSessionStub _channelSessionStub;
  21. [TestInitialize]
  22. public void Initialize()
  23. {
  24. _channelSessionStub = new ChannelSessionStub();
  25. var connectionInfoMock = new Mock<IConnectionInfo>();
  26. connectionInfoMock.Setup(p => p.Encoding).Returns(Encoding.UTF8);
  27. var sessionMock = new Mock<ISession>();
  28. sessionMock.Setup(p => p.SessionLoggerFactory).Returns(NullLoggerFactory.Instance);
  29. sessionMock.Setup(p => p.ConnectionInfo).Returns(connectionInfoMock.Object);
  30. sessionMock.Setup(p => p.CreateChannelSession()).Returns(_channelSessionStub);
  31. _shellStream = new ShellStream(
  32. sessionMock.Object,
  33. "terminalName",
  34. columns: 80,
  35. rows: 24,
  36. width: 800,
  37. height: 600,
  38. terminalModeValues: null,
  39. bufferSize: BufferSize);
  40. }
  41. [TestMethod]
  42. public void Read_String()
  43. {
  44. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  45. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  46. Assert.AreEqual("Hello World!", _shellStream.Read());
  47. }
  48. [TestMethod]
  49. public void Read_Bytes()
  50. {
  51. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  52. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  53. byte[] buffer = new byte[12];
  54. Assert.AreEqual(7, _shellStream.Read(buffer, 3, 7));
  55. CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("\0\0\0Hello W\0\0"), buffer);
  56. Assert.AreEqual(5, _shellStream.Read(buffer, 0, 12));
  57. CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("orld!llo W\0\0"), buffer);
  58. }
  59. #if NET
  60. [TestMethod]
  61. public void Read_Bytes_Span()
  62. {
  63. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  64. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  65. byte[] buffer = new byte[12];
  66. Assert.AreEqual(7, _shellStream.Read(buffer.AsSpan(3, 7)));
  67. CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("\0\0\0Hello W\0\0"), buffer);
  68. Assert.AreEqual(5, _shellStream.Read(buffer));
  69. CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("orld!llo W\0\0"), buffer);
  70. }
  71. #endif
  72. [TestMethod]
  73. public void Channel_DataReceived_MoreThanBufferSize()
  74. {
  75. // Test buffer resizing
  76. byte[] expectedData = CryptoAbstraction.GenerateRandom(BufferSize * 3);
  77. _channelSessionStub.Receive(expectedData);
  78. byte[] actualData = new byte[expectedData.Length + 1];
  79. Assert.AreEqual(expectedData.Length, _shellStream.Read(actualData, 0, actualData.Length));
  80. CollectionAssert.AreEqual(expectedData, actualData.Take(expectedData.Length));
  81. }
  82. [DataTestMethod]
  83. [DataRow("\r\n")]
  84. [DataRow("\r")]
  85. [DataRow("\n")]
  86. public void ReadLine(string newLine)
  87. {
  88. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  89. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  90. // We specify a timeout to avoid waiting infinitely.
  91. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  92. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(newLine));
  93. Assert.AreEqual("Hello World!", _shellStream.ReadLine(TimeSpan.Zero));
  94. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  95. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Second line!" + newLine + "Third line!" + newLine));
  96. Assert.AreEqual("Second line!", _shellStream.ReadLine(TimeSpan.Zero));
  97. Assert.AreEqual("Third line!", _shellStream.ReadLine(TimeSpan.Zero));
  98. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  99. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Last line!")); // no newLine at the end
  100. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  101. _channelSessionStub.Close();
  102. Assert.AreEqual("Last line!", _shellStream.ReadLine(TimeSpan.Zero));
  103. }
  104. [TestMethod]
  105. public void ReadLine_DifferentTerminators()
  106. {
  107. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello\rWorld!\nWhat's\r\ngoing\n\ron?\n"));
  108. Assert.AreEqual("Hello", _shellStream.ReadLine());
  109. Assert.AreEqual("World!", _shellStream.ReadLine());
  110. Assert.AreEqual("What's", _shellStream.ReadLine());
  111. Assert.AreEqual("going", _shellStream.ReadLine());
  112. Assert.AreEqual("", _shellStream.ReadLine());
  113. Assert.AreEqual("on?", _shellStream.ReadLine());
  114. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  115. }
  116. [DataTestMethod]
  117. [DataRow("\r\n")]
  118. [DataRow("\r")]
  119. [DataRow("\n")]
  120. public void Read_MultipleLines(string newLine)
  121. {
  122. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  123. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  124. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(newLine));
  125. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Second line!" + newLine + "Third line!" + newLine));
  126. Assert.AreEqual("Hello World!" + newLine + "Second line!" + newLine + "Third line!" + newLine, _shellStream.Read());
  127. }
  128. [TestMethod]
  129. public async Task Read_NonEmptyArray_OnlyReturnsZeroAfterClose()
  130. {
  131. Task<int> readTask = _shellStream.ReadAsync(new byte[16], 0, 16);
  132. await Task.Delay(50);
  133. Assert.IsFalse(readTask.IsCompleted);
  134. _channelSessionStub.Close();
  135. Assert.AreEqual(0, await readTask);
  136. }
  137. [TestMethod]
  138. public async Task Read_EmptyArray_OnlyReturnsZeroWhenDataAvailable()
  139. {
  140. Task<int> readTask = _shellStream.ReadAsync(Array.Empty<byte>(), 0, 0);
  141. await Task.Delay(50);
  142. Assert.IsFalse(readTask.IsCompleted);
  143. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello World!"));
  144. Assert.AreEqual(0, await readTask);
  145. }
  146. #if NET
  147. [TestMethod]
  148. public async Task Read_EmptySpan_OnlyReturnsZeroWhenDataAvailable()
  149. {
  150. ValueTask<int> readTask = _shellStream.ReadAsync(Memory<byte>.Empty);
  151. await Task.Delay(50);
  152. Assert.IsFalse(readTask.IsCompleted);
  153. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello World!"));
  154. Assert.AreEqual(0, await readTask);
  155. }
  156. #endif
  157. [TestMethod]
  158. public void Expect()
  159. {
  160. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  161. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  162. Assert.IsNull(_shellStream.Expect("123", TimeSpan.Zero));
  163. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("\r\n12345"));
  164. Assert.AreEqual("Hello World!\r\n123", _shellStream.Expect("123"));
  165. Assert.AreEqual("45", _shellStream.Read());
  166. }
  167. [TestMethod]
  168. public void Read_AfterDispose_StillWorks()
  169. {
  170. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello World!"));
  171. _shellStream.Dispose();
  172. #pragma warning disable S3966 // Objects should not be disposed more than once
  173. _shellStream.Dispose(); // Check that multiple Dispose is OK.
  174. #pragma warning restore S3966 // Objects should not be disposed more than once
  175. Assert.IsTrue(_shellStream.CanRead);
  176. Assert.AreEqual("Hello World!", _shellStream.ReadLine());
  177. Assert.IsNull(_shellStream.ReadLine());
  178. }
  179. [TestMethod]
  180. public void Read_MultiByte()
  181. {
  182. _channelSessionStub.Receive(new byte[] { 0xF0 });
  183. _channelSessionStub.Receive(new byte[] { 0x9F });
  184. _channelSessionStub.Receive(new byte[] { 0x91 });
  185. _channelSessionStub.Receive(new byte[] { 0x8D });
  186. Assert.AreEqual("👍", _shellStream.Read());
  187. }
  188. [TestMethod]
  189. public void ReadLine_MultiByte()
  190. {
  191. _channelSessionStub.Receive(new byte[] { 0xF0 });
  192. _channelSessionStub.Receive(new byte[] { 0x9F });
  193. _channelSessionStub.Receive(new byte[] { 0x91 });
  194. _channelSessionStub.Receive(new byte[] { 0x8D });
  195. _channelSessionStub.Receive(new byte[] { 0x0D });
  196. _channelSessionStub.Receive(new byte[] { 0x0A });
  197. Assert.AreEqual("👍", _shellStream.ReadLine());
  198. Assert.AreEqual("", _shellStream.Read());
  199. }
  200. [TestMethod]
  201. public void Expect_Regex_MultiByte()
  202. {
  203. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("𐓏𐓘𐓻𐓘𐓻𐓟 𐒻𐓟"));
  204. Assert.AreEqual("𐓏𐓘𐓻𐓘𐓻𐓟 ", _shellStream.Expect(new Regex(@"\s")));
  205. Assert.AreEqual("𐒻𐓟", _shellStream.Read());
  206. }
  207. [TestMethod]
  208. public void Expect_String_MultiByte()
  209. {
  210. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("hello 你好"));
  211. Assert.AreEqual("hello 你好", _shellStream.Expect("你好"));
  212. Assert.AreEqual("", _shellStream.Read());
  213. }
  214. [TestMethod]
  215. public void Expect_Regex_non_ASCII_characters()
  216. {
  217. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  218. Assert.AreEqual("Hello, こ", _shellStream.Expect(new Regex(@"[^\u0000-\u007F]")));
  219. Assert.AreEqual("んにちは, Bonjour", _shellStream.Read());
  220. }
  221. [TestMethod]
  222. public void Expect_String_LargeExpect()
  223. {
  224. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('a', 100)));
  225. for (var i = 0; i < 10; i++)
  226. {
  227. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('b', 100)));
  228. }
  229. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  230. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('c', 100)));
  231. Assert.AreEqual($"{new string('a', 100)}{new string('b', 1000)}Hello, こんにちは, Bonjour", _shellStream.Expect($"{new string('b', 1000)}Hello, こんにちは, Bonjour"));
  232. Assert.AreEqual($"{new string('c', 100)}", _shellStream.Read());
  233. }
  234. [TestMethod]
  235. public void Expect_String_WithLookback()
  236. {
  237. const string expected = "ccccc";
  238. // Prime buffer
  239. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string(' ', BufferSize)));
  240. // Test data
  241. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('a', 100)));
  242. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('b', 100)));
  243. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(expected));
  244. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('d', 100)));
  245. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('e', 100)));
  246. // Expected result
  247. var expectedResult = $"{new string(' ', BufferSize)}{new string('a', 100)}{new string('b', 100)}{expected}";
  248. var expectedRead = $"{new string('d', 100)}{new string('e', 100)}";
  249. Assert.AreEqual(expectedResult, _shellStream.Expect(expected, TimeSpan.Zero, lookback: 250));
  250. Assert.AreEqual(expectedRead, _shellStream.Read());
  251. }
  252. [TestMethod]
  253. public void Expect_Regex_WithLookback()
  254. {
  255. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("0123456789"));
  256. Assert.AreEqual("01234567", _shellStream.Expect(new Regex(@"\d"), TimeSpan.Zero, lookback: 3));
  257. Assert.AreEqual("89", _shellStream.Read());
  258. }
  259. [TestMethod]
  260. public void Expect_Regex_WithLookback_non_ASCII_characters()
  261. {
  262. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  263. Assert.AreEqual("Hello, こんにち", _shellStream.Expect(new Regex(@"[^\u0000-\u007F]"), TimeSpan.Zero, lookback: 11));
  264. Assert.AreEqual("は, Bonjour", _shellStream.Read());
  265. }
  266. [TestMethod]
  267. public void Expect_Timeout()
  268. {
  269. Stopwatch stopwatch = Stopwatch.StartNew();
  270. Assert.IsNull(_shellStream.Expect("Hello World!", TimeSpan.FromMilliseconds(200)));
  271. TimeSpan elapsed = stopwatch.Elapsed;
  272. // Account for variance in system timer resolution.
  273. Assert.IsTrue(elapsed > TimeSpan.FromMilliseconds(180), elapsed.ToString());
  274. }
  275. private class ChannelSessionStub : IChannelSession
  276. {
  277. public void Receive(byte[] data)
  278. {
  279. DataReceived.Invoke(this, new ChannelDataEventArgs(channelNumber: 0, data));
  280. }
  281. public void Close()
  282. {
  283. Closed.Invoke(this, new ChannelEventArgs(channelNumber: 0));
  284. }
  285. public bool SendShellRequest()
  286. {
  287. return true;
  288. }
  289. public bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModeValues)
  290. {
  291. return true;
  292. }
  293. public void Dispose()
  294. {
  295. }
  296. public void Open()
  297. {
  298. }
  299. public event EventHandler<ChannelDataEventArgs> DataReceived;
  300. public event EventHandler<ChannelEventArgs> Closed;
  301. #pragma warning disable 0067
  302. public event EventHandler<ExceptionEventArgs> Exception;
  303. public event EventHandler<ChannelExtendedDataEventArgs> ExtendedDataReceived;
  304. public event EventHandler<ChannelRequestEventArgs> RequestReceived;
  305. #pragma warning restore 0067
  306. #pragma warning disable IDE0025 // Use block body for property
  307. #pragma warning disable IDE0022 // Use block body for method
  308. public uint LocalChannelNumber => throw new NotImplementedException();
  309. public uint LocalPacketSize => throw new NotImplementedException();
  310. public uint RemoteChannelNumber => throw new NotImplementedException();
  311. public uint RemotePacketSize => throw new NotImplementedException();
  312. public bool IsOpen => throw new NotImplementedException();
  313. public bool SendBreakRequest(uint breakLength) => throw new NotImplementedException();
  314. public void SendData(byte[] data) => throw new NotImplementedException();
  315. public void SendData(byte[] data, int offset, int size) => throw new NotImplementedException();
  316. public bool SendEndOfWriteRequest() => throw new NotImplementedException();
  317. public bool SendEnvironmentVariableRequest(string variableName, string variableValue) => throw new NotImplementedException();
  318. public void SendEof() => throw new NotImplementedException();
  319. public bool SendExecRequest(string command) => throw new NotImplementedException();
  320. public bool SendKeepAliveRequest() => throw new NotImplementedException();
  321. public void SendLocalFlowRequest(bool clientCanDo) => throw new NotImplementedException();
  322. public bool SendSignalRequest(string signalName) => throw new NotImplementedException();
  323. public bool SendSubsystemRequest(string subsystem) => throw new NotImplementedException();
  324. public void SendWindowChangeRequest(uint columns, uint rows, uint width, uint height) => throw new NotImplementedException();
  325. public bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber) => throw new NotImplementedException();
  326. #pragma warning restore IDE0022 // Use block body for method
  327. #pragma warning restore IDE0025 // Use block body for property
  328. }
  329. }
  330. }