Repository navigation
ShellStream.Expect(Regex, TimeSpan) can return "too much" string #454
Copy link
Copy link
Closed
Milestone
Description
ShellStream.Expect(Regex, TimeSpan) properly matches and dequeues data from the _incoming data queue. However, once a match is made, instead of returning all text up to the point of a match, it returns all data within the queue.
Current:
public string Expect(Regex regex, TimeSpan timeout)
{
var text = string.Empty;
while (true)
{
lock (_incoming)
{
if (_incoming.Count > 0)
{
text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count);
}
var match = regex.Match(text);
if (match.Success)
{
// Remove processed items from the queue
for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++)
{
_incoming.Dequeue();
}
break;
}
}
if (timeout.Ticks > 0)
{
if (!_dataReceived.WaitOne(timeout))
{
return null;
}
}
else
{
_dataReceived.WaitOne();
}
}
return text;
}Fix:
public string Expect(Regex regex, TimeSpan timeout)
{
var text = string.Empty;
while (true)
{
lock (_incoming)
{
if (_incoming.Count > 0)
{
text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count);
}
var match = regex.Match(text);
if (match.Success)
{
// Remove processed items from the queue
for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++)
{
_incoming.Dequeue();
}
text = text.Substring(0, match.Index + match.Length); // <-- This one line of code fixes it!
break;
}
}
if (timeout.Ticks > 0)
{
if (!_dataReceived.WaitOne(timeout))
{
return null;
}
}
else
{
_dataReceived.WaitOne();
}
}
return text;
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels
Activity
Added test for ShellStream.Expect(Regex, TimeSpan) that reproduces is…
Fixed issue sshnet#454, ShellStream.Expect(Regex, TimeSpan) returning…
IgorMilavec commentedon Feb 24, 2022
I have created a discussion #926 for all ShellStream related issues.
IgorMilavec commentedon Mar 21, 2022
@keithallenjackson I'm trying to better understand usage patterns related to Expect API. Can you please explain how you use it and if possible provide a proto code for it?
jscarle commentedon Feb 13, 2024
@IgorMilavec @WojciechNagorski This was fixed by #1207 and #1319.
WojciechNagorski commentedon Feb 22, 2024
This issue has been fixed in the 2024.0.0 version.