forked from shadowsocks/shadowsocks-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe.go
100 lines (94 loc) · 2.64 KB
/
pipe.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
package shadowsocks
import (
"bytes"
"encoding/binary"
"io"
"net"
"time"
)
func SetReadTimeout(c net.Conn) {
if readTimeout != 0 {
c.SetReadDeadline(time.Now().Add(readTimeout))
}
}
// PipeThenClose copies data from src to dst, closes dst when done.
func PipeThenClose(src, dst net.Conn) {
defer dst.Close()
buf := leakyBuf.Get()
defer leakyBuf.Put(buf)
for {
SetReadTimeout(src)
n, err := src.Read(buf)
// read may return EOF with n > 0
// should always process n > 0 bytes before handling error
if n > 0 {
// Note: avoid overwrite err returned by Read.
if _, err := dst.Write(buf[0:n]); err != nil {
Debug.Println("write:", err)
break
}
}
if err != nil {
// Always "use of closed network connection", but no easy way to
// identify this specific error. So just leave the error along for now.
// More info here: https://code.google.com/p/go/issues/detail?id=4373
/*
if bool(Debug) && err != io.EOF {
Debug.Println("read:", err)
}
*/
break
}
}
}
// PipeThenClose copies data from src to dst, closes dst when done, with ota verification.
func PipeThenCloseOta(src *Conn, dst net.Conn) {
const (
dataLenLen = 2
hmacSha1Len = 10
idxData0 = dataLenLen + hmacSha1Len
)
defer func() {
dst.Close()
}()
// sometimes it have to fill large block
buf := leakyBuf.Get()
defer leakyBuf.Put(buf)
for i := 1; ; i += 1 {
SetReadTimeout(src)
if n, err := io.ReadFull(src, buf[:dataLenLen+hmacSha1Len]); err != nil {
if err == io.EOF {
break
}
Debug.Printf("conn=%p #%v read header error n=%v: %v", src, i, n, err)
break
}
dataLen := binary.BigEndian.Uint16(buf[:dataLenLen])
expectedHmacSha1 := buf[dataLenLen:idxData0]
var dataBuf []byte
if len(buf) < int(idxData0+dataLen) {
dataBuf = make([]byte, dataLen)
} else {
dataBuf = buf[idxData0 : idxData0+dataLen]
}
if n, err := io.ReadFull(src, dataBuf); err != nil {
if err == io.EOF {
break
}
Debug.Printf("conn=%p #%v read data error n=%v: %v", src, i, n, err)
break
}
chunkIdBytes := make([]byte, 4)
chunkId := src.GetAndIncrChunkId()
binary.BigEndian.PutUint32(chunkIdBytes, chunkId)
actualHmacSha1 := HmacSha1(append(src.GetIv(), chunkIdBytes...), dataBuf)
if !bytes.Equal(expectedHmacSha1, actualHmacSha1) {
Debug.Printf("conn=%p #%v read data hmac-sha1 mismatch, iv=%v chunkId=%v src=%v dst=%v len=%v expeced=%v actual=%v", src, i, src.GetIv(), chunkId, src.RemoteAddr(), dst.RemoteAddr(), dataLen, expectedHmacSha1, actualHmacSha1)
break
}
if n, err := dst.Write(dataBuf); err != nil {
Debug.Printf("conn=%p #%v write data error n=%v: %v", dst, i, n, err)
break
}
}
}