Debian Codegraph @

vnet/conn.go

raw symbols SCIP
1 package vnet
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "math"
8 "net"
9 "sync"
10 "time"
11
12 "github.com/pion/transport/v2"
13 )
14
15 const (
16 maxReadQueueSize = 1024
17 )
18
19 var (
20 errObsCannotBeNil = errors.New("obs cannot be nil")
21 errUseClosedNetworkConn = errors.New("use of closed network connection")
22 errAddrNotUDPAddr = errors.New("addr is not a net.UDPAddr")
23 errLocAddr = errors.New("something went wrong with locAddr")
24 errAlreadyClosed = errors.New("already closed")
25 errNoRemAddr = errors.New("no remAddr defined")
26 )
27
28 // vNet implements this
29 type connObserver interface {
30 write(c Chunk) error
31 onClosed(addr net.Addr)
32 determineSourceIP(locIP, dstIP net.IP) net.IP
33 }
34
35 // UDPConn is the implementation of the Conn and PacketConn interfaces for UDP network connections.
36 // compatible with net.PacketConn and net.Conn
37 type UDPConn struct {
38 locAddr *net.UDPAddr // read-only
39 remAddr *net.UDPAddr // read-only
40 obs connObserver // read-only
41 readCh chan Chunk // thread-safe
42 closed bool // requires mutex
43 mu sync.Mutex // to mutex closed flag
44 readTimer *time.Timer // thread-safe
45 }
46
47 var _ transport.UDPConn = &UDPConn{}
48
49 func newUDPConn(locAddr, remAddr *net.UDPAddr, obs connObserver) (*UDPConn, error) {
50 if obs == nil {
51 return nil, errObsCannotBeNil
52 }
53
54 return &UDPConn{
55 locAddr: locAddr,
56 remAddr: remAddr,
57 obs: obs,
58 readCh: make(chan Chunk, maxReadQueueSize),
59 readTimer: time.NewTimer(time.Duration(math.MaxInt64)),
60 }, nil
61 }
62
63 // Close closes the connection.
64 // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
65 func (c *UDPConn) Close() error {
66 c.mu.Lock()
67 defer c.mu.Unlock()
68
69 if c.closed {
70 return errAlreadyClosed
71 }
72 c.closed = true
73 close(c.readCh)
74
75 c.obs.onClosed(c.locAddr)
76 return nil
77 }
78
79 // LocalAddr returns the local network address.
80 func (c *UDPConn) LocalAddr() net.Addr {
81 return c.locAddr
82 }
83
84 // RemoteAddr returns the remote network address.
85 func (c *UDPConn) RemoteAddr() net.Addr {
86 return c.remAddr
87 }
88
89 // SetDeadline sets the read and write deadlines associated
90 // with the connection. It is equivalent to calling both
91 // SetReadDeadline and SetWriteDeadline.
92 //
93 // A deadline is an absolute time after which I/O operations
94 // fail with a timeout (see type Error) instead of
95 // blocking. The deadline applies to all future and pending
96 // I/O, not just the immediately following call to ReadFrom or
97 // WriteTo. After a deadline has been exceeded, the connection
98 // can be refreshed by setting a deadline in the future.
99 //
100 // An idle timeout can be implemented by repeatedly extending
101 // the deadline after successful ReadFrom or WriteTo calls.
102 //
103 // A zero value for t means I/O operations will not time out.
104 func (c *UDPConn) SetDeadline(t time.Time) error {
105 return c.SetReadDeadline(t)
106 }
107
108 // SetReadDeadline sets the deadline for future ReadFrom calls
109 // and any currently-blocked ReadFrom call.
110 // A zero value for t means ReadFrom will not time out.
111 func (c *UDPConn) SetReadDeadline(t time.Time) error {
112 var d time.Duration
113 var noDeadline time.Time
114 if t == noDeadline {
115 d = time.Duration(math.MaxInt64)
116 } else {
117 d = time.Until(t)
118 }
119 c.readTimer.Reset(d)
120 return nil
121 }
122
123 // SetWriteDeadline sets the deadline for future WriteTo calls
124 // and any currently-blocked WriteTo call.
125 // Even if write times out, it may return n > 0, indicating that
126 // some of the data was successfully written.
127 // A zero value for t means WriteTo will not time out.
128 func (c *UDPConn) SetWriteDeadline(t time.Time) error {
129 // Write never blocks.
130 return nil
131 }
132
133 // Read reads data from the connection.
134 // Read can be made to time out and return an Error with Timeout() == true
135 // after a fixed time limit; see SetDeadline and SetReadDeadline.
136 func (c *UDPConn) Read(b []byte) (int, error) {
137 n, _, err := c.ReadFrom(b)
138 return n, err
139 }
140
141 // ReadFrom reads a packet from the connection,
142 // copying the payload into p. It returns the number of
143 // bytes copied into p and the return address that
144 // was on the packet.
145 // It returns the number of bytes read (0 <= n <= len(p))
146 // and any error encountered. Callers should always process
147 // the n > 0 bytes returned before considering the error err.
148 // ReadFrom can be made to time out and return
149 // an Error with Timeout() == true after a fixed time limit;
150 // see SetDeadline and SetReadDeadline.
151 func (c *UDPConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
152 loop:
153 for {
154 select {
155 case chunk, ok := <-c.readCh:
156 if !ok {
157 break loop
158 }
159 var err error
160 n := copy(p, chunk.UserData())
161 addr := chunk.SourceAddr()
162 if n < len(chunk.UserData()) {
163 err = io.ErrShortBuffer
164 }
165
166 if c.remAddr != nil {
167 if addr.String() != c.remAddr.String() {
168 break // discard (shouldn't happen)
169 }
170 }
171 return n, addr, err
172
173 case <-c.readTimer.C:
174 return 0, nil, &net.OpError{
175 Op: "read",
176 Net: c.locAddr.Network(),
177 Addr: c.locAddr,
178 Err: newTimeoutError("i/o timeout"),
179 }
180 }
181 }
182
183 return 0, nil, &net.OpError{
184 Op: "read",
185 Net: c.locAddr.Network(),
186 Addr: c.locAddr,
187 Err: errUseClosedNetworkConn,
188 }
189 }
190
191 // ReadFromUDP acts like ReadFrom but returns a UDPAddr.
192 func (c *UDPConn) ReadFromUDP(b []byte) (int, *net.UDPAddr, error) {
193 n, addr, err := c.ReadFrom(b)
194
195 udpAddr, ok := addr.(*net.UDPAddr)
196 if !ok {
197 return -1, nil, fmt.Errorf("%w: %s", transport.ErrNotUDPAddress, addr)
198 }
199
200 return n, udpAddr, err
201 }
202
203 // ReadMsgUDP reads a message from c, copying the payload into b and
204 // the associated out-of-band data into oob. It returns the number of
205 // bytes copied into b, the number of bytes copied into oob, the flags
206 // that were set on the message and the source address of the message.
207 //
208 // The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be
209 // used to manipulate IP-level socket options in oob.
210 func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error) {
211 return -1, -1, -1, nil, transport.ErrNotSupported
212 }
213
214 // Write writes data to the connection.
215 // Write can be made to time out and return an Error with Timeout() == true
216 // after a fixed time limit; see SetDeadline and SetWriteDeadline.
217 func (c *UDPConn) Write(b []byte) (int, error) {
218 if c.remAddr == nil {
219 return 0, errNoRemAddr
220 }
221
222 return c.WriteTo(b, c.remAddr)
223 }
224
225 // WriteTo writes a packet with payload p to addr.
226 // WriteTo can be made to time out and return
227 // an Error with Timeout() == true after a fixed time limit;
228 // see SetDeadline and SetWriteDeadline.
229 // On packet-oriented connections, write timeouts are rare.
230 func (c *UDPConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
231 dstAddr, ok := addr.(*net.UDPAddr)
232 if !ok {
233 return 0, errAddrNotUDPAddr
234 }
235
236 srcIP := c.obs.determineSourceIP(c.locAddr.IP, dstAddr.IP)
237 if srcIP == nil {
238 return 0, errLocAddr
239 }
240 srcAddr := &net.UDPAddr{
241 IP: srcIP,
242 Port: c.locAddr.Port,
243 }
244
245 chunk := newChunkUDP(srcAddr, dstAddr)
246 chunk.userData = make([]byte, len(p))
247 copy(chunk.userData, p)
248 if err := c.obs.write(chunk); err != nil {
249 return 0, err
250 }
251 return len(p), nil
252 }
253
254 // WriteToUDP acts like WriteTo but takes a UDPAddr.
255 func (c *UDPConn) WriteToUDP(b []byte, addr *net.UDPAddr) (int, error) {
256 return c.WriteTo(b, addr)
257 }
258
259 // WriteMsgUDP writes a message to addr via c if c isn't connected, or
260 // to c's remote address if c is connected (in which case addr must be
261 // nil). The payload is copied from b and the associated out-of-band
262 // data is copied from oob. It returns the number of payload and
263 // out-of-band bytes written.
264 //
265 // The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be
266 // used to manipulate IP-level socket options in oob.
267 func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error) {
268 return -1, -1, transport.ErrNotSupported
269 }
270
271 // SetReadBuffer sets the size of the operating system's
272 // receive buffer associated with the connection.
273 func (c *UDPConn) SetReadBuffer(bytes int) error {
274 return transport.ErrNotSupported
275 }
276
277 // SetWriteBuffer sets the size of the operating system's
278 // transmit buffer associated with the connection.
279 func (c *UDPConn) SetWriteBuffer(bytes int) error {
280 return transport.ErrNotSupported
281 }
282
283 func (c *UDPConn) onInboundChunk(chunk Chunk) {
284 c.mu.Lock()
285 defer c.mu.Unlock()
286
287 if c.closed {
288 return
289 }
290
291 select {
292 case c.readCh <- chunk:
293 default:
294 }
295 }