mihirsamdarshi / ssh-test

Testing out creating local port forwarding using various Rust libraries
MIT License
3 stars 2 forks source link

will method read_stream block? #1

Open yangshoulai opened 1 year ago

yangshoulai commented 1 year ago

In async-ssh2-lite/src/main.js line 49, if the read stream size exactly equal BUFFER_SIZE, method read_buf_bytes will return true, will current method block in next loop? I am a newer to Rust and I am searching for ssh local port forwarding, Thank you very much if you could answer my question。

mihirsamdarshi commented 1 year ago

Hi @yangshoulai, thanks for the question.

If I understand correctly, you’re asking about this bit of code

https://github.com/mihirsamdarshi/ssh-test/blob/64210f7677ab6bd957da4ee5f000b0dfd26f3cc9/async-ssh2-lite/src/main.rs#L47-L58

No, the method will not block in the next loop. The method read_buf_bytes() checks how many bytes (n) were read from the stream. If n is 0, this basically translates to there being no more data to read on the stream. Let's say BUFFER_SIZE is 4KB and your file is also 4KB. This does not mean the last read() will block, because the operating system typically knows the file size ahead of the read operations, thus it will read 4KB and then report EOF (end of file), i.e., it will return 0 to the read() on the next loop indicating there is nothing left to read, and hence that will not block. If it's 0, it's usually because the file has already finished (EOF has been reached), and subsequent read() calls will therefore return 0 immediately. The behavior of the code is essentially relying on the read() system call's behavior on an EOF.

As such, the function will run through the loop until it reads the entire stream and once that's done, the next stream.read call will immediately return 0, this returns false from read_buf_bytes() and the loop breaks. Therefore, read_stream() won't block even if the read stream size is exactly equal to BUFFER_SIZE.

yangshoulai commented 1 year ago

Thank you very much for your detailed explanation. I have learned a lot. Finally, I found this lib ssh_jumper, It helped me solved my problem, but thanks again for your help.

TheBlindM commented 8 months ago

Thank you very much for your detailed explanation. I have learned a lot. Finally, I found this lib ssh_jumper, It helped me solved my problem, but thanks again for your help.

May I ask how "ssh_jumper" is used together with async ssh2 lite?

mihirsamdarshi commented 8 months ago

Hi @TheBlindM I think that ssh_jumper uses async ssh2 lite under the hood