/
proxy.go
144 lines (112 loc) · 2.52 KB
/
proxy.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package tcp
/**
* proxy.go - proxy utils
*
* @author Yaroslav Pogrebnyak <yyyaroslav@gmail.com>
*/
import (
"io"
"net"
"time"
"github.com/yyyar/gobetween/core"
"github.com/yyyar/gobetween/logging"
)
const (
/* Buffer size to handle data from socket */
BUFFER_SIZE = 16 * 1024
/* Interval of pushing aggregated read/write stats */
PROXY_STATS_PUSH_INTERVAL = 1 * time.Second
)
/**
* Perform copy/proxy data from 'from' to 'to' socket, counting r/w stats and
* dropping connection if timeout exceeded
*/
func proxy(to net.Conn, from net.Conn, timeout time.Duration) <-chan core.ReadWriteCount {
log := logging.For("proxy")
stats := make(chan core.ReadWriteCount)
outStats := make(chan core.ReadWriteCount)
rwcBuffer := core.ReadWriteCount{}
ticker := time.NewTicker(PROXY_STATS_PUSH_INTERVAL)
flushed := false
// Stats collecting goroutine
go func() {
if timeout > 0 {
from.SetReadDeadline(time.Now().Add(timeout))
}
for {
select {
case <-ticker.C:
if !rwcBuffer.IsZero() {
outStats <- rwcBuffer
}
flushed = true
case rwc, ok := <-stats:
if !ok {
ticker.Stop()
if !flushed && !rwcBuffer.IsZero() {
outStats <- rwcBuffer
}
close(outStats)
return
}
if timeout > 0 && rwc.CountRead > 0 {
from.SetReadDeadline(time.Now().Add(timeout))
}
// Remove non blocking
if flushed {
rwcBuffer = rwc
} else {
rwcBuffer.CountWrite += rwc.CountWrite
rwcBuffer.CountRead += rwc.CountRead
}
flushed = false
}
}
}()
// Run proxy copier
go func() {
err := Copy(to, from, stats)
// hack to determine normal close. TODO: fix when it will be exposed in golang
e, ok := err.(*net.OpError)
if err != nil && (!ok || e.Err.Error() != "use of closed network connection") {
log.Warn(err)
}
to.Close()
from.Close()
// Stop stats collecting goroutine
close(stats)
}()
return outStats
}
/**
* It's build by analogy of io.Copy
*/
func Copy(to io.Writer, from io.Reader, ch chan<- core.ReadWriteCount) error {
buf := make([]byte, BUFFER_SIZE)
var err error = nil
for {
readN, readErr := from.Read(buf)
if readN > 0 {
writeN, writeErr := to.Write(buf[0:readN])
if writeN > 0 {
ch <- core.ReadWriteCount{CountRead: uint(readN), CountWrite: uint(writeN)}
}
if writeErr != nil {
err = writeErr
break
}
if readN != writeN {
err = io.ErrShortWrite
break
}
}
if readErr == io.EOF {
break
}
if readErr != nil {
err = readErr
break
}
}
return err
}