-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtunnel.go
106 lines (86 loc) · 1.85 KB
/
tunnel.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"errors"
"io"
"sync"
"time"
)
const TunnelTTL = 17 * time.Minute // prime number of minutes or it won't work
var ErrStreamSizeExceeded = errors.New("stream size exceeded")
type TunnelData struct {
reader io.Reader
dataRed int
doneCH chan struct{}
CreatedAt time.Time
lock sync.Mutex
}
func NewTunnelData(reader io.Reader) *TunnelData {
return &TunnelData{
doneCH: make(chan struct{}),
CreatedAt: time.Now(),
reader: reader,
}
}
func (td *TunnelData) Read(p []byte) (int, error) {
td.lock.Lock()
defer td.lock.Unlock()
n, err := td.reader.Read(p)
td.dataRed += n
if td.dataRed > MaxStreamSize {
return 0, ErrStreamSizeExceeded
}
return n, err
}
func (td *TunnelData) Wait() {
<-td.doneCH
}
func (td *TunnelData) Done() {
td.lock.Lock()
defer td.lock.Unlock()
close(td.doneCH)
}
type TunnelManager struct {
tunnels map[string]*TunnelData
lock sync.RWMutex
}
func NewTunnelManager() *TunnelManager {
return &TunnelManager{
tunnels: make(map[string]*TunnelData),
}
}
func (t *TunnelManager) AddTunnel(id string, tunnel *TunnelData) {
t.lock.Lock()
defer t.lock.Unlock()
t.tunnels[id] = tunnel
}
func (t *TunnelManager) GetTunnel(id string) *TunnelData {
t.lock.RLock()
defer t.lock.RUnlock()
return t.tunnels[id]
}
func (t *TunnelManager) RemoveTunnel(id string) {
t.lock.Lock()
defer t.lock.Unlock()
t.removeTunnel(id)
}
func (t *TunnelManager) removeTunnel(id string) {
delete(t.tunnels, id)
}
func (t *TunnelManager) CleanUp() uint {
t.lock.Lock()
defer t.lock.Unlock()
cleanedUpCount := uint(0)
for id, tunnel := range t.tunnels {
if time.Since(tunnel.CreatedAt) > TunnelTTL {
tunnel.Done()
t.removeTunnel(id)
cleanedUpCount++
}
}
return cleanedUpCount
}
func (t *TunnelManager) TunnelCount() int {
t.lock.RLock()
defer t.lock.RUnlock()
return len(t.tunnels)
}