Store forwarded TCP listen port in SSH_FWD_TCP_PORT env variable
Using 0 for the port number with -R dynamically allocates a listen port on the server. The allocated port is printed to standard output, which is not very useful for automation scripts, forcing ssh users to implement workarounds:
- https://serverfault.com/questions/1074254/ssh-with-a-dynamically-allocated-remote-forwarded-port-how-to-find-the-port-n
- https://serverfault.com/questions/856280/get-local-port-when-using-ssh-forwarding-with-dynamic-0-port
- https://unix.stackexchange.com/questions/584479/recording-the-dynamically-allocated-port-number-with-ssh-remote-port-forwarding
This change stores the allocated port in SSH_FWD_TCP_PORT environment variable.
The problem with this concept is that from a protocol perspective, port forwards can be added and deleted and any time during a an SSH session, but an environment variable can only be populated when a shell is started. This means the environment variables are not necessarily going to be correct (for example, even if specified and client startup time, there's no requirement for a client to send a port forward request first).
This implementation has an addition problem in that it can't handle multiple port forward requests.
Given the architectural problems with doing this, I'm not sure it's worth pursuing.
@daztucker thank you for the feedback. While it seems that solving this for the case when socket is forwarded after the startup is difficult, do you think it could make sense to add a new option, which will enable this feature and populate some env variable on startup if set. It could also handle the case of multiple forwarded ports by concatenating them. Something along the lines of:
ssh -R 7319:/path/to/socket1 -R 7320:/path/to/socket2 -o "PopulateFwdTCPPort=yes" <host>
echo $SSH_FWD_TCP_PORT
7319:7320
The problem with this concept is that from a protocol perspective, port forwards can be added and deleted and any time during a an SSH session, but an environment variable can only be populated when a shell is started.
Printing to standard error (which is current behavior) also "suffers" from this. Once printed cannot be changed. Actually, it is worse because ENV could be updated.
This implementation has an addition problem in that it can't handle multiple port forward requests.
I didn't tried -R 0 multiple times, perhaps it is printing to stderr multiple times, but even so stderr is not super friendly for processing:
- it mixes errors with useful information
- because of "plain text" nature of message it is hard to parse and easy to break compatibility for users
- it provokes even more brittle workarounds involving multiple
sshcalls or port forwarding
Adding environment (or perhaps token instead?) solves all those problems.