-
Notifications
You must be signed in to change notification settings - Fork 1
/
tunnel.go
54 lines (40 loc) · 993 Bytes
/
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
// Package tunnel implements the tunneling logic for copying data between two
// network connections both sides.
package tunnel
import (
"fmt"
"io"
"sync"
"github.com/AdguardTeam/golibs/log"
)
// Tunnel passes data between two connections.
func Tunnel(pipeName string, left io.ReadWriter, right io.ReadWriter) {
wg := &sync.WaitGroup{}
wg.Add(2)
go pipe(fmt.Sprintf("%s left->right", pipeName), left, right, wg)
go pipe(fmt.Sprintf("%s left<-right", pipeName), right, left, wg)
wg.Wait()
}
// pipe copies data from reader r to writer w.
func pipe(pipeName string, r io.Reader, w io.Writer, wg *sync.WaitGroup) {
defer wg.Done()
buf := make([]byte, 65536)
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
log.Debug("failed to read: %v", err)
return
}
if n == 0 {
continue
}
log.Debug("%s: copying %d bytes", pipeName, n)
_, err = w.Write(buf[:n])
if err != nil {
log.Debug("failed to write: %v", err)
return
}
}
}