ShellStreamTest_ReadExpect.cs 16 KB

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