@@ -28,9 +28,10 @@ type Client struct {
2828 ID string
2929 net.Conn
3030 * ssh.ServerConn
31- Listeners map [string ]net.Listener
32- Addr string
33- Port uint32
31+ Listeners map [string ]net.Listener
32+ Addr string
33+ Port uint32
34+ ListenMutex * sync.Mutex
3435}
3536
3637func NewSSHServer () * SSHServer {
@@ -86,9 +87,20 @@ func (s *SSHServer) listen(addr string, domain string) error {
8687 continue
8788 }
8889
89- client := & Client {randID (), tcpConn , sshConn , make (map [string ]net.Listener ), "" , 0 }
90+ client := & Client {randID (), tcpConn , sshConn , make (map [string ]net.Listener ), "" , 0 , & sync. Mutex {} }
9091 log .Printf ("New SSH connection from %s (%s)" , sshConn .RemoteAddr (), sshConn .ClientVersion ())
9192
93+ go func () {
94+ err := client .ServerConn .Wait ()
95+ client .ListenMutex .Lock ()
96+ log .Printf ("[%s] SSH connection closed: %s" , client .ID , err )
97+
98+ for bind , listener := range client .Listeners {
99+ log .Printf ("[%s] Closing listener bound to %s" , client .ID , bind )
100+ listener .Close ()
101+ }
102+ }()
103+
92104 go s .handleRequests (client , reqs )
93105 go s .handleChannels (client , chans )
94106 }
@@ -134,18 +146,20 @@ func (s *SSHServer) handleRequests(client *Client, reqs <-chan *ssh.Request) {
134146 log .Printf ("[%s] Out of band request: %v %v" , client .ID , req .Type , req .WantReply )
135147
136148 if req .Type == "tcpip-forward" {
137- req . Reply ( true , [] byte {} )
149+ client . ListenMutex . Lock ( )
138150
139151 listener , bindinfo , err := handleForward (client , req )
140152 if err != nil {
141153 fmt .Printf ("[%s] Error, disconnecting ...\n " , client .ID )
154+ client .ListenMutex .Unlock ()
142155 client .Conn .Close ()
143156 }
144157
145158 client .Addr = bindinfo .Addr
146159 client .Port = bindinfo .Port
147160 client .Listeners [bindinfo .Bound ] = listener
148161 s .clients [client .ID ] = * client
162+ client .ListenMutex .Unlock ()
149163
150164 go handleListener (client , bindinfo , listener )
151165 continue
0 commit comments