-
Notifications
You must be signed in to change notification settings - Fork 19
/
tcplock.go
57 lines (49 loc) · 990 Bytes
/
tcplock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package sshego
import (
"fmt"
"net"
"sync"
"time"
)
type TcpPort struct {
Port int
Lsn net.Listener
mux sync.Mutex
}
var ErrCouldNotAquirePort = fmt.Errorf("could not acquire " +
"our -xport before the deadline")
func (t *TcpPort) Lock(limitMsec int) error {
t.mux.Lock()
addr := fmt.Sprintf("127.0.0.1:%v", t.Port)
t.mux.Unlock()
start := time.Now()
var deadline time.Time
if limitMsec > 0 {
deadline = start.Add(time.Duration(limitMsec) * time.Millisecond)
}
var lsn net.Listener
var err error
for {
lsn, err = net.Listen("tcp", addr)
if err == nil {
break
}
time.Sleep(10 * time.Millisecond)
if !deadline.IsZero() && time.Now().After(deadline) {
return fmt.Errorf("-xport error: could not acquire our -xport before the deadline, for -xport %v", addr)
}
}
t.mux.Lock()
t.Lsn = lsn
t.mux.Unlock()
return nil
}
func (t *TcpPort) Unlock() {
t.mux.Lock()
defer t.mux.Unlock()
if t.Lsn == nil {
return
}
t.Lsn.Close()
t.Lsn = nil
}