pyscripter / Ssh-Pascal

Delphi ssh library wrapping libssh2
MIT License
80 stars 33 forks source link

Is it safe to use multiple `ISshExec` of the same session in multiple threads? #5

Closed edwinyzh closed 3 years ago

edwinyzh commented 3 years ago

Hello,

Is it safe to create multiple ISshExec out of the same session, and then use those ISshExec instances in multiple threads? Or do I have to use standalone session for each thread?

Upate 1: After looking at TSshExec.Exec, the code access FSession without any locking mechanism, so I assume it's not thread-safe...

Update 2: After looking at /CLibs/BuildWin32Lib.cmd, it seems that the dlls were not compiled with the -D_REENTRANT flag, so I assume adding that flag will improve the thread-safety as well.

Update 3: The following two quotes from a thread in the libssh2 mail list are worth noting:

All use of libssh2 must be synchronized. You need to make sure that only one thread calls libssh2 at a time.

Update 4: Another useful quote:

As you may know, the SSH protocol is not really thread safe on the wire. The lowest level TCP connection (session) can only be used by one channel at a time. This must of course be respected by programs using libssh2.

edwinyzh commented 3 years ago

Check all the update 1..4 I added above in the OP, here are my conclusions:

pyscripter commented 3 years ago

I think you could have different sessions running in different threads. Have not tested it.

edwinyzh commented 3 years ago

I'm doing it now (have different ssh sessions in different threads), but will need more tests to confirm the stability.

On the other hand, to improve the thread-safety of libssh2, it'd suggest to add the -D_REENTRANT flag when compiling the libssh2 DLL, although I'm not in a good position to create a PR for this since I'm not familiar with building c projects. :)

pyscripter commented 3 years ago

-D_REENTRANT flag

This flag is for GCC only. I am linking with the thread-safe version of the std. library of Visual Studio anyway.

-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded

pyscripter commented 3 years ago

If I remember well it is only channels that cannot be used by a different threads simultaneously. Using different channels of the same session could also be thread safe.