@@ -36,13 +36,20 @@ type Tunnel struct {
3636 Port int
3737 LastConnection time.Time
3838 Mutex sync.Mutex
39+ Started bool
3940}
4041
4142var mut sync.Mutex = sync.Mutex {}
4243
4344func CreateTunnel (remoteHost , remotePort , username , password string ) int {
4445 t , err := Tunnels .Get (remoteHost , remotePort , username )
4546 if err == nil {
47+ for {
48+ if t .Started {
49+ break
50+ }
51+ }
52+
4653 t .LastConnection = time .Now ()
4754 return t .Port
4855 }
@@ -79,14 +86,23 @@ func CreateTunnel(remoteHost, remotePort, username, password string) int {
7986 },
8087 Port : port ,
8188 LastConnection : time .Now (),
89+ Started : false ,
8290 }
8391
92+ Tunnels .Set (remoteHost , remotePort , username , sshTunnel )
93+
8494 hasError := sshTunnel .Start ()
8595 if ! hasError {
86- Tunnels .Set (remoteHost , remotePort , username , sshTunnel )
96+ for {
97+ if sshTunnel .Started {
98+ break
99+ }
100+ }
101+
87102 return port
88103 }
89104
105+ Tunnels .Delete (remoteHost + ":" + remotePort + ":" + username )
90106 return 0
91107}
92108
@@ -171,12 +187,17 @@ func (t *Tunnel) bindTunnel(ctx context.Context, wg *sync.WaitGroup, hasError *b
171187 // The socket is binded. Make sure we close it eventually.
172188 bindCtx , cancel := context .WithCancel (ctx )
173189 defer cancel ()
190+ go func () {
191+ cl .Wait ()
192+ cancel ()
193+ }()
174194 go func () {
175195 <- bindCtx .Done ()
176196 once .Do (func () {}) // Suppress future errors
177197 ln .Close ()
178198 }()
179199
200+ t .Started = true
180201 t .log .Infow ("binded tunnel" , "details" , t )
181202 wg .Done ()
182203 defer t .log .Infow ("collapsed tunnel" , "details" , t )
0 commit comments