forked from fortuna/ss-example
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathudp.go
226 lines (197 loc) · 7.04 KB
/
udp.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Copyright 2018 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"errors"
"fmt"
"net"
"time"
"github.com/Jigsaw-Code/outline-ss-server/metrics"
"sync"
"github.com/shadowsocks/go-shadowsocks2/shadowaead"
"github.com/shadowsocks/go-shadowsocks2/socks"
)
type mode int
const udpBufSize = 64 * 1024
// upack decripts src into dst. It tries each cipher until it finds one that authenticates
// correctly. dst and src must not overlap.
func unpack(dst, src []byte, ciphers map[string]shadowaead.Cipher) ([]byte, string, shadowaead.Cipher, error) {
for id, cipher := range ciphers {
logger.Debugf("Trying UDP cipher %v", id)
buf, err := shadowaead.Unpack(dst, src, cipher)
if err != nil {
logger.Debugf("Failed UDP cipher %v: %v", id, err)
continue
}
logger.Debugf("Selected UDP cipher %v", id)
return buf, id, cipher, nil
}
return nil, "", nil, errors.New("could not find valid cipher")
}
// Listen on addr for encrypted packets and basically do UDP NAT.
// We take the ciphers as a pointer because it gets replaced on config updates.
func runUDPService(clientConn net.PacketConn, ciphers *map[string]shadowaead.Cipher, m metrics.ShadowsocksMetrics) {
defer clientConn.Close()
nm := newNATmap(config.UDPTimeout, m)
cipherBuf := make([]byte, udpBufSize)
textBuf := make([]byte, udpBufSize)
for {
func() (connError *connectionError) {
defer func() {
if r := recover(); r != nil {
logger.Errorf("Panic in UDP loop: %v", r)
}
}()
clientLocation := ""
keyID := ""
var clientProxyBytes, proxyTargetBytes int
defer func() {
status := "OK"
if connError != nil {
logger.Debugf("UDP Error: %v: %v", connError.message, connError.cause)
status = connError.status
}
m.AddUDPPacketFromClient(clientLocation, keyID, status, clientProxyBytes, proxyTargetBytes)
}()
clientProxyBytes, clientAddr, err := clientConn.ReadFrom(cipherBuf)
clientLocation, locErr := m.GetLocation(clientAddr)
if locErr != nil {
logger.Errorf("Failed location lookup: %v", locErr)
}
logger.Debugf("Got location \"%v\" for IP %v", clientLocation, clientAddr.String())
if err != nil {
return &connectionError{"ERR_READ", "Failed to read from client", err}
}
defer logger.Debugf("UDP done with %v", clientAddr.String())
logger.Debugf("UDP Request from %v with %v bytes", clientAddr, clientProxyBytes)
buf, keyID, cipher, err := unpack(textBuf, cipherBuf[:clientProxyBytes], *ciphers)
if err != nil {
return &connectionError{"ERR_CIPHER", "Failed to upack data from client", err}
}
tgtAddr := socks.SplitAddr(buf)
if tgtAddr == nil {
return &connectionError{"ERR_READ_ADDRESS", "Failed to get target address", nil}
}
tgtUDPAddr, err := net.ResolveUDPAddr("udp", tgtAddr.String())
if err != nil {
return &connectionError{"ERR_RESOLVE_ADDRESS", fmt.Sprintf("Failed to resolve target address %v", tgtAddr.String()), err}
}
if !tgtUDPAddr.IP.IsGlobalUnicast() {
return &connectionError{"ERR_ADDRESS_INVALID", fmt.Sprintf("Target address is not global unicast: %v", tgtAddr.String()), err}
}
payload := buf[len(tgtAddr):]
targetConn := nm.Get(clientAddr.String())
if targetConn == nil {
targetConn, err = net.ListenPacket("udp", "")
if err != nil {
return &connectionError{"ERR_CREATE_SOCKET", "Failed to create UDP socket", err}
}
nm.Add(clientAddr, clientConn, cipher, targetConn, clientLocation, keyID)
}
logger.Debugf("UDP Nat: client %v <-> proxy exit %v", clientAddr, targetConn.LocalAddr())
proxyTargetBytes, err = targetConn.WriteTo(payload, tgtUDPAddr) // accept only UDPAddr despite the signature
if err != nil {
return &connectionError{"ERR_WRITE", "Failed to write to target", err}
}
return nil
}()
}
}
// Packet NAT table
type natmap struct {
sync.RWMutex
keyConn map[string]net.PacketConn
timeout time.Duration
metrics metrics.ShadowsocksMetrics
}
func newNATmap(timeout time.Duration, sm metrics.ShadowsocksMetrics) *natmap {
m := &natmap{metrics: sm}
m.keyConn = make(map[string]net.PacketConn)
m.timeout = timeout
return m
}
func (m *natmap) Get(key string) net.PacketConn {
m.RLock()
defer m.RUnlock()
return m.keyConn[key]
}
func (m *natmap) set(key string, pc net.PacketConn) {
m.Lock()
defer m.Unlock()
m.keyConn[key] = pc
}
func (m *natmap) del(key string) net.PacketConn {
m.Lock()
defer m.Unlock()
pc, ok := m.keyConn[key]
if ok {
delete(m.keyConn, key)
return pc
}
return nil
}
func (m *natmap) Add(clientAddr net.Addr, clientConn net.PacketConn, cipher shadowaead.Cipher, targetConn net.PacketConn, clientLocation, keyID string) {
m.set(clientAddr.String(), targetConn)
m.metrics.AddUdpNatEntry()
go func() {
timedCopy(clientAddr, clientConn, cipher, targetConn, m.timeout, clientLocation, keyID, m.metrics)
m.metrics.RemoveUdpNatEntry()
if pc := m.del(clientAddr.String()); pc != nil {
pc.Close()
}
}()
}
// copy from src to dst at target with read timeout
func timedCopy(clientAddr net.Addr, clientConn net.PacketConn, cipher shadowaead.Cipher, targetConn net.PacketConn,
timeout time.Duration, clientLocation, keyID string, sm metrics.ShadowsocksMetrics) {
textBuf := make([]byte, udpBufSize)
cipherBuf := make([]byte, udpBufSize)
expired := false
for !expired {
var targetProxyBytes, proxyClientBytes int
connError := func() (connError *connectionError) {
targetConn.SetReadDeadline(time.Now().Add(timeout))
targetProxyBytes, raddr, err := targetConn.ReadFrom(textBuf)
if err != nil {
if netErr, ok := err.(net.Error); ok {
if netErr.Timeout() {
expired = true
return nil
}
}
return &connectionError{"ERR_READ", "Failed to read from target", err}
}
srcAddr := socks.ParseAddr(raddr.String())
logger.Debugf("UDP response from %v to %v", srcAddr, clientAddr)
// Shift data buffer to prepend with srcAddr.
copy(textBuf[len(srcAddr):], textBuf[:targetProxyBytes])
copy(textBuf, srcAddr)
buf, err := shadowaead.Pack(cipherBuf, textBuf[:len(srcAddr)+targetProxyBytes], cipher)
if err != nil {
return &connectionError{"ERR_PACK", "Failed to pack data to client", err}
}
proxyClientBytes, err = clientConn.WriteTo(buf, clientAddr)
if err != nil {
return &connectionError{"ERR_WRITE", "Failed to write to client", err}
}
return nil
}()
status := "OK"
if connError != nil {
logger.Debugf("UDP Error: %v: %v", connError.message, connError.cause)
status = connError.status
}
sm.AddUDPPacketFromTarget(clientLocation, keyID, status, targetProxyBytes, proxyClientBytes)
}
}