ShellStreamTest_ReadExpect.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. [TestMethod]
  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. [TestMethod]
  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 async Task ReadAsyncDoesNotBlockWriteAsync()
  181. {
  182. byte[] buffer = new byte[16];
  183. Task<int> readTask = _shellStream.ReadAsync(buffer, 0, buffer.Length);
  184. await _shellStream.WriteAsync("ls\n"u8.ToArray(), 0, 3);
  185. Assert.IsFalse(readTask.IsCompleted);
  186. _channelSessionStub.Receive("Directory.Build.props"u8.ToArray());
  187. await readTask;
  188. }
  189. [TestMethod]
  190. public void Read_MultiByte()
  191. {
  192. _channelSessionStub.Receive(new byte[] { 0xF0 });
  193. _channelSessionStub.Receive(new byte[] { 0x9F });
  194. _channelSessionStub.Receive(new byte[] { 0x91 });
  195. _channelSessionStub.Receive(new byte[] { 0x8D });
  196. Assert.AreEqual("👍", _shellStream.Read());
  197. }
  198. [TestMethod]
  199. public void ReadLine_MultiByte()
  200. {
  201. _channelSessionStub.Receive(new byte[] { 0xF0 });
  202. _channelSessionStub.Receive(new byte[] { 0x9F });
  203. _channelSessionStub.Receive(new byte[] { 0x91 });
  204. _channelSessionStub.Receive(new byte[] { 0x8D });
  205. _channelSessionStub.Receive(new byte[] { 0x0D });
  206. _channelSessionStub.Receive(new byte[] { 0x0A });
  207. Assert.AreEqual("👍", _shellStream.ReadLine());
  208. Assert.AreEqual("", _shellStream.Read());
  209. }
  210. [TestMethod]
  211. public void Expect_Regex_MultiByte()
  212. {
  213. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("𐓏𐓘𐓻𐓘𐓻𐓟 𐒻𐓟"));
  214. Assert.AreEqual("𐓏𐓘𐓻𐓘𐓻𐓟 ", _shellStream.Expect(new Regex(@"\s")));
  215. Assert.AreEqual("𐒻𐓟", _shellStream.Read());
  216. }
  217. [TestMethod]
  218. public void Expect_String_MultiByte()
  219. {
  220. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("hello 你好"));
  221. Assert.AreEqual("hello 你好", _shellStream.Expect("你好"));
  222. Assert.AreEqual("", _shellStream.Read());
  223. }
  224. [TestMethod]
  225. public void Expect_Regex_non_ASCII_characters()
  226. {
  227. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  228. Assert.AreEqual("Hello, こ", _shellStream.Expect(new Regex(@"[^\u0000-\u007F]")));
  229. Assert.AreEqual("んにちは, Bonjour", _shellStream.Read());
  230. }
  231. [TestMethod]
  232. public void Expect_String_LargeExpect()
  233. {
  234. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('a', 100)));
  235. for (var i = 0; i < 10; i++)
  236. {
  237. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('b', 100)));
  238. }
  239. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  240. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('c', 100)));
  241. Assert.AreEqual($"{new string('a', 100)}{new string('b', 1000)}Hello, こんにちは, Bonjour", _shellStream.Expect($"{new string('b', 1000)}Hello, こんにちは, Bonjour"));
  242. Assert.AreEqual($"{new string('c', 100)}", _shellStream.Read());
  243. }
  244. [TestMethod]
  245. public void Expect_String_WithLookback()
  246. {
  247. const string expected = "ccccc";
  248. // Prime buffer
  249. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string(' ', BufferSize)));
  250. // Test data
  251. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('a', 100)));
  252. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('b', 100)));
  253. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(expected));
  254. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('d', 100)));
  255. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('e', 100)));
  256. // Expected result
  257. var expectedResult = $"{new string(' ', BufferSize)}{new string('a', 100)}{new string('b', 100)}{expected}";
  258. var expectedRead = $"{new string('d', 100)}{new string('e', 100)}";
  259. Assert.AreEqual(expectedResult, _shellStream.Expect(expected, TimeSpan.Zero, lookback: 250));
  260. Assert.AreEqual(expectedRead, _shellStream.Read());
  261. }
  262. [TestMethod]
  263. public void Expect_Regex_WithLookback()
  264. {
  265. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("0123456789"));
  266. Assert.AreEqual("01234567", _shellStream.Expect(new Regex(@"\d"), TimeSpan.Zero, lookback: 3));
  267. Assert.AreEqual("89", _shellStream.Read());
  268. }
  269. [TestMethod]
  270. public void Expect_Regex_WithLookback_non_ASCII_characters()
  271. {
  272. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  273. Assert.AreEqual("Hello, こんにち", _shellStream.Expect(new Regex(@"[^\u0000-\u007F]"), TimeSpan.Zero, lookback: 11));
  274. Assert.AreEqual("は, Bonjour", _shellStream.Read());
  275. }
  276. [TestMethod]
  277. public void Expect_Timeout()
  278. {
  279. Stopwatch stopwatch = Stopwatch.StartNew();
  280. Assert.IsNull(_shellStream.Expect("Hello World!", TimeSpan.FromMilliseconds(200)));
  281. TimeSpan elapsed = stopwatch.Elapsed;
  282. // Account for variance in system timer resolution.
  283. Assert.IsTrue(elapsed > TimeSpan.FromMilliseconds(180), elapsed.ToString());
  284. }
  285. private class ChannelSessionStub : IChannelSession
  286. {
  287. public void Receive(byte[] data)
  288. {
  289. DataReceived.Invoke(this, new ChannelDataEventArgs(channelNumber: 0, data));
  290. }
  291. public void Close()
  292. {
  293. Closed.Invoke(this, new ChannelEventArgs(channelNumber: 0));
  294. }
  295. public bool SendShellRequest()
  296. {
  297. return true;
  298. }
  299. public bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModeValues)
  300. {
  301. return true;
  302. }
  303. public void Dispose()
  304. {
  305. }
  306. public void Open()
  307. {
  308. }
  309. public event EventHandler<ChannelDataEventArgs> DataReceived;
  310. public event EventHandler<ChannelEventArgs> Closed;
  311. #pragma warning disable 0067
  312. public event EventHandler<ExceptionEventArgs> Exception;
  313. public event EventHandler<ChannelExtendedDataEventArgs> ExtendedDataReceived;
  314. public event EventHandler<ChannelRequestEventArgs> RequestReceived;
  315. #pragma warning restore 0067
  316. #pragma warning disable IDE0025 // Use block body for property
  317. #pragma warning disable IDE0022 // Use block body for method
  318. public uint LocalChannelNumber => throw new NotImplementedException();
  319. public uint LocalPacketSize => throw new NotImplementedException();
  320. public uint RemoteChannelNumber => throw new NotImplementedException();
  321. public uint RemotePacketSize => throw new NotImplementedException();
  322. public bool IsOpen => throw new NotImplementedException();
  323. public bool SendBreakRequest(uint breakLength) => throw new NotImplementedException();
  324. public void SendData(byte[] data) => throw new NotImplementedException();
  325. public void SendData(byte[] data, int offset, int size) => throw new NotImplementedException();
  326. public bool SendEndOfWriteRequest() => throw new NotImplementedException();
  327. public bool SendEnvironmentVariableRequest(string variableName, string variableValue) => throw new NotImplementedException();
  328. public void SendEof() => throw new NotImplementedException();
  329. public bool SendExecRequest(string command) => throw new NotImplementedException();
  330. public bool SendKeepAliveRequest() => throw new NotImplementedException();
  331. public void SendLocalFlowRequest(bool clientCanDo) => throw new NotImplementedException();
  332. public bool SendSignalRequest(string signalName) => throw new NotImplementedException();
  333. public bool SendSubsystemRequest(string subsystem) => throw new NotImplementedException();
  334. public void SendWindowChangeRequest(uint columns, uint rows, uint width, uint height) => throw new NotImplementedException();
  335. public bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber) => throw new NotImplementedException();
  336. #pragma warning restore IDE0022 // Use block body for method
  337. #pragma warning restore IDE0025 // Use block body for property
  338. }
  339. }
  340. }