-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathudp.go
189 lines (163 loc) · 5.53 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
// +build !windows
package dns
import (
"net"
"sync"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
type SessionUDPFactory interface {
// SetSocketOptions sets the required UDP socket options on 'conn'.
// Must be called before 'conn' is passed to ReadRequest()
SetSocketOptions(conn *net.UDPConn) error
// InitPool initializes a pool of buffers to be used with SessionUDP.
// Must be called before calling ReadRequest()
InitPool(msgSize int)
// ReadRequest reads a single request from 'conn'.
// Returns the message buffer and the SessionUDP instance
// that is used to send the response.
ReadRequest(conn *net.UDPConn) ([]byte, SessionUDP, error)
// ReadRequestConn reads a single request from 'conn'.
// Returns the message buffer and the source address
ReadRequestConn(conn net.PacketConn) ([]byte, net.Addr, error)
}
// SessionUDP holds manages a UDP Request/Response transaction.
type SessionUDP interface {
// Discard returns the SessionUDP back to the factory pool.
// Must be called whenever the request is not needed any more.
Discard()
// RemoteAddr returns the remote address of the last read UDP request
RemoteAddr() net.Addr
// LocalAddr returns the local address of the last read UDP request
LocalAddr() net.Addr
// WriteResponse writes a response to the UDP request managed
// by this SessionUDP. The response is sent to the UDP
// address the request came from.
WriteResponse(b []byte) (int, error)
}
// This is the required size of the OOB buffer to pass to ReadMsgUDP.
var udpOOBSize = func() int {
// We can't know whether we'll get an IPv4 control message or an
// IPv6 control message ahead of time. To get around this, we size
// the buffer equal to the largest of the two.
oob4 := ipv4.NewControlMessage(ipv4.FlagDst | ipv4.FlagInterface)
oob6 := ipv6.NewControlMessage(ipv6.FlagDst | ipv6.FlagInterface)
if len(oob4) > len(oob6) {
return len(oob4)
}
return len(oob6)
}()
type sessionUDPFactory struct {
// A pool for UDP message buffers.
udpPool sync.Pool
}
// sessionUDP implements the SessionUDP, holding the connection to use
// for the response, the remote address and the associated out-of-band
// data.
type sessionUDP struct {
f *sessionUDPFactory // owner
conn *net.UDPConn
raddr *net.UDPAddr
m []byte
oob []byte
}
var defaultSessionUDPFactory = &sessionUDPFactory{}
// SetSocketOptions sets the required UDP socket options on 'conn'.
func (s *sessionUDPFactory) SetSocketOptions(conn *net.UDPConn) error {
// Try setting the flags for both families and ignore the errors unless they
// both error.
err6 := ipv6.NewPacketConn(conn).SetControlMessage(ipv6.FlagDst|ipv6.FlagInterface, true)
err4 := ipv4.NewPacketConn(conn).SetControlMessage(ipv4.FlagDst|ipv4.FlagInterface, true)
if err6 != nil && err4 != nil {
return err4
}
return nil
}
// InitPool initializes a pool of buffers to be used with SessionUDP.
func (f *sessionUDPFactory) InitPool(msgSize int) {
f.udpPool.New = func() interface{} {
return &sessionUDP{
f: f,
m: make([]byte, msgSize),
oob: make([]byte, udpOOBSize),
}
}
}
// ReadRequest reads a single request from 'conn' and returns the request context
func (f *sessionUDPFactory) ReadRequest(conn *net.UDPConn) ([]byte, SessionUDP, error) {
s := f.udpPool.Get().(*sessionUDP)
n, oobn, _, raddr, err := conn.ReadMsgUDP(s.m, s.oob)
if err != nil {
s.Discard()
return nil, nil, err
}
// Keep context for response
s.conn = conn
s.raddr = raddr
s.m = s.m[:n] // Re-slice to the actual size
s.oob = s.oob[:oobn] // Re-slice to the actual size
return s.m, s, err
}
func (f *sessionUDPFactory) ReadRequestConn(conn net.PacketConn) ([]byte, net.Addr, error) {
s := f.udpPool.Get().(*sessionUDP)
n, addr, err := conn.ReadFrom(s.m)
if err != nil {
s.Discard()
return nil, nil, err
}
s.m = s.m[:n] // Re-slice to the actual size
return s.m, addr, err
}
// Discard returns 's' to the factory pool
func (s *sessionUDP) Discard() {
s.conn = nil
s.raddr = nil
s.m = s.m[:cap(s.m)]
s.oob = s.oob[:cap(s.oob)]
s.f.udpPool.Put(s)
}
// RemoteAddr returns the remote network address for the current request.
func (s *sessionUDP) RemoteAddr() net.Addr { return s.raddr }
// LocalAddr returns the local network address for the current request.
func (s *sessionUDP) LocalAddr() net.Addr { return s.conn.LocalAddr() }
// WriteResponse writes a response to a request received earlier
func (s *sessionUDP) WriteResponse(b []byte) (int, error) {
oob := correctSource(s.oob)
n, _, err := s.conn.WriteMsgUDP(b, oob, s.raddr)
return n, err
}
// parseDstFromOOB takes oob data and returns the destination IP.
func parseDstFromOOB(oob []byte) net.IP {
// Start with IPv6 and then fallback to IPv4
// TODO(fastest963): Figure out a way to prefer one or the other. Looking at
// the lvl of the header for a 0 or 41 isn't cross-platform.
cm6 := new(ipv6.ControlMessage)
if cm6.Parse(oob) == nil && cm6.Dst != nil {
return cm6.Dst
}
cm4 := new(ipv4.ControlMessage)
if cm4.Parse(oob) == nil && cm4.Dst != nil {
return cm4.Dst
}
return nil
}
// correctSource takes oob data and returns new oob data with the Src equal to the Dst
func correctSource(oob []byte) []byte {
dst := parseDstFromOOB(oob)
if dst == nil {
return nil
}
// If the dst is definitely an IPv6, then use ipv6's ControlMessage to
// respond otherwise use ipv4's because ipv6's marshal ignores ipv4
// addresses.
if dst.To4() == nil {
cm := new(ipv6.ControlMessage)
cm.Src = dst
oob = cm.Marshal()
} else {
cm := new(ipv4.ControlMessage)
cm.Src = dst
oob = cm.Marshal()
}
return oob
}