Skip to content

Commit 69f1451

Browse files
authored
Fix ShellStream when receiving data larger than buffer length (#1337)
1 parent 5b9c669 commit 69f1451

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/Renci.SshNet/ShellStream.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ private void AssertValid()
7575
Debug.Assert(Monitor.IsEntered(_sync), $"Should be in lock on {nameof(_sync)}");
7676
Debug.Assert(_readHead >= 0, $"{nameof(_readHead)} should be non-negative but is {_readHead}");
7777
Debug.Assert(_readTail >= 0, $"{nameof(_readTail)} should be non-negative but is {_readTail}");
78-
Debug.Assert(_readHead < _readBuffer.Length || _readBuffer.Length == 0, $"{nameof(_readHead)} should be < {nameof(_readBuffer)}.Length but is {_readHead}");
78+
Debug.Assert(_readHead <= _readBuffer.Length, $"{nameof(_readHead)} should be <= {nameof(_readBuffer)}.Length but is {_readHead}");
7979
Debug.Assert(_readTail <= _readBuffer.Length, $"{nameof(_readTail)} should be <= {nameof(_readBuffer)}.Length but is {_readTail}");
8080
Debug.Assert(_readHead <= _readTail, $"Should have {nameof(_readHead)} <= {nameof(_readTail)} but have {_readHead} <= {_readTail}");
8181
}
@@ -938,7 +938,7 @@ private void Channel_DataReceived(object? sender, ChannelDataEventArgs e)
938938
else
939939
{
940940
// Otherwise, we're gonna need a bigger buffer.
941-
var newBuffer = new byte[_readBuffer.Length * 2];
941+
var newBuffer = new byte[Math.Max(newLength, _readBuffer.Length * 2)];
942942
Buffer.BlockCopy(_readBuffer, _readHead, newBuffer, 0, _readTail - _readHead);
943943
_readBuffer = newBuffer;
944944
}

test/Renci.SshNet.Tests/Classes/ShellStreamTest_ReadExpect.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
using Moq;
1111

12+
using Renci.SshNet.Abstractions;
1213
using Renci.SshNet.Channels;
1314
using Renci.SshNet.Common;
1415

@@ -70,6 +71,19 @@ public void Read_Bytes()
7071
CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("orld!llo W\0\0"), buffer);
7172
}
7273

74+
[TestMethod]
75+
public void Channel_DataReceived_MoreThanBufferSize()
76+
{
77+
// Test buffer resizing
78+
byte[] expectedData = CryptoAbstraction.GenerateRandom(BufferSize * 3);
79+
_channelSessionStub.Receive(expectedData);
80+
81+
byte[] actualData = new byte[expectedData.Length + 1];
82+
83+
Assert.AreEqual(expectedData.Length, _shellStream.Read(actualData, 0, actualData.Length));
84+
CollectionAssert.AreEqual(expectedData, actualData.Take(expectedData.Length));
85+
}
86+
7387
[DataTestMethod]
7488
[DataRow("\r\n")]
7589
[DataRow("\r")]

0 commit comments

Comments
 (0)