ba0f3 / ssh2.nim

Async SSH, SCP and SFTP client for Nim, using libssh2 wrapper [WIP]

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`execCommand` returns invalid content

m0t1x opened this issue · comments

If the transmitted data are in size > 10 KB it can occur error in transmission. Problem is in procedure channel.read and error is caused because the cstring always includes extra \0 terminator which goes beyond the size of the buffer. Error happens sporadically in situations when consecutive data buffers are completely full.

proc read*(channel: SSHChannel): string =
var
buffer: array[0..1024, char]
rc: cint
while true:
zeroMem(addr buffer, buffer.len)
rc = channel.impl.channel_read(addr buffer, buffer.len)
if rc > 0:
result.add($cast[cstring](addr buffer))
elif rc == LIBSSH2_ERROR_EAGAIN:
discard waitsocket(channel.client)
else:
break

Line 33 - add only the size of received data.

...
 if rc > 0:
      result.add(($cast[cstring](addr buffer))[0..rc-1])
 elif rc == LIBSSH2_ERROR_EAGAIN:
...

Read one byte less than the buffer size - C-style reading data due to NUL terminated string:

while true:
    zeroMem(addr buffer, buffer.len)
    rc = channel.impl.channel_read(addr buffer, buffer.len-1)
    if rc > 0:

I would suggest to use both, and than zeroMem(...) can be removed.
The same goes for readError function.