-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathudp.go
More file actions
314 lines (266 loc) · 7.08 KB
/
Copy pathudp.go
File metadata and controls
314 lines (266 loc) · 7.08 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package netpipe
import (
"fmt"
"net"
"sync"
"github.com/google/uuid"
)
// UDP wire format (per packet - no length prefix needed):
//
// [1 byte: flags][N bytes: body]
//
// Each UDP packet IS a message boundary, so no framing required.
// Flags byte is identical to TCP: bit 0 = encrypted.
const (
// udpMaxPacket is the max safe UDP payload size.
// 65507 is the theoretical max, but we cap at 64 KB for sanity.
udpMaxPacket = 65507
)
// ---------------------------------------------------------------------------
// UDP Server
// ---------------------------------------------------------------------------
// udpClient tracks a UDP "client" by their remote address.
type udpClient struct {
id string
addr *net.UDPAddr
}
// listenUDP starts the UDP server loop. Called by Server.Listen() when protocol is "udp".
func (s *Server) listenUDP() error {
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", s.config.Port))
if err != nil {
return fmt.Errorf("netpipe: resolve udp addr: %w", err)
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return fmt.Errorf("netpipe: listen udp: %w", err)
}
s.udpConn = conn
fmt.Printf("netpipe server listening on udp :%d\n", s.config.Port)
buf := make([]byte, udpMaxPacket)
for {
n, remoteAddr, err := conn.ReadFromUDP(buf)
if err != nil {
if s.udpConn == nil {
return nil // clean shutdown
}
continue
}
if n < 1 {
continue // need at least the flags byte
}
// identify or register this client by address
clientID := s.getOrRegisterUDPClient(remoteAddr)
flags := buf[0]
body := make([]byte, n-1)
copy(body, buf[1:n])
// Stage 7: pong from client
if flags&flagPong != 0 {
s.meta.touchPong(clientID)
continue
}
// Ignore pings from clients
if flags&flagPing != 0 {
continue
}
// Stage 7: track data activity
s.meta.touchData(clientID)
// Stage 6: stream chunk - buffer and reassemble
if flags&flagStream != 0 {
streamID, index, total, chunk, err := parseStreamBody(body)
if err != nil {
continue
}
assembled, complete := s.streams.addChunkFrom(clientID, streamID, index, total, chunk)
if complete && s.onStream != nil {
s.onStream(clientID, assembled)
}
continue
}
data := body
// auto-decrypt if flagged and key is set
if flags&flagEncrypted != 0 && s.config.EncryptionKey != "" {
plaintext, err := decrypt(body, s.config.EncryptionKey)
if err != nil {
continue // bad key or corrupt - skip
}
data = plaintext
}
if s.onData != nil {
s.onData(clientID, data)
}
}
}
// getOrRegisterUDPClient finds or creates a client entry for a UDP remote address.
func (s *Server) getOrRegisterUDPClient(addr *net.UDPAddr) string {
key := addr.String()
s.udpMu.RLock()
if client, ok := s.udpClients[key]; ok {
s.udpMu.RUnlock()
return client.id
}
s.udpMu.RUnlock()
// new client
id := uuid.New().String()
s.udpMu.Lock()
// double-check after acquiring write lock
if client, ok := s.udpClients[key]; ok {
s.udpMu.Unlock()
return client.id
}
s.udpClients[key] = &udpClient{id: id, addr: addr}
s.udpMu.Unlock()
if s.onConnect != nil {
s.onConnect(id)
}
return id
}
// sendUDP sends a UDP packet with flags to a specific client by UUID.
func (s *Server) sendUDP(clientID string, flags byte, body []byte) error {
s.udpMu.RLock()
var target *net.UDPAddr
for _, c := range s.udpClients {
if c.id == clientID {
target = c.addr
break
}
}
s.udpMu.RUnlock()
if target == nil {
return fmt.Errorf("netpipe: udp client %s not found", clientID)
}
packet := make([]byte, 1+len(body))
packet[0] = flags
copy(packet[1:], body)
_, err := s.udpConn.WriteToUDP(packet, target)
return err
}
// kickUDP removes a UDP client from the registry and fires OnDisconnect.
func (s *Server) kickUDP(clientID string) error {
s.udpMu.Lock()
var found bool
for key, c := range s.udpClients {
if c.id == clientID {
delete(s.udpClients, key)
found = true
break
}
}
s.udpMu.Unlock()
if !found {
return fmt.Errorf("netpipe: udp client %s not found", clientID)
}
if s.onDisconnect != nil {
s.onDisconnect(clientID)
}
return nil
}
// broadcastUDP sends a UDP packet to all known clients.
func (s *Server) broadcastUDP(flags byte, body []byte, excludeID string) {
packet := make([]byte, 1+len(body))
packet[0] = flags
copy(packet[1:], body)
s.udpMu.RLock()
targets := make([]*net.UDPAddr, 0, len(s.udpClients))
for _, c := range s.udpClients {
if c.id != excludeID {
targets = append(targets, c.addr)
}
}
s.udpMu.RUnlock()
for _, addr := range targets {
s.udpConn.WriteToUDP(packet, addr)
}
}
// ---------------------------------------------------------------------------
// UDP Client
// ---------------------------------------------------------------------------
// connectUDP sets up the UDP "connection" (it's really just a bound socket).
func (c *Client) connectUDP() error {
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", c.config.Host, c.config.Port))
if err != nil {
return fmt.Errorf("netpipe: resolve udp addr: %w", err)
}
conn, err := net.DialUDP("udp", nil, addr)
if err != nil {
return fmt.Errorf("netpipe: connect udp: %w", err)
}
c.conn = conn
return nil
}
// sendUDP sends a UDP packet with flags.
func (c *Client) sendUDP(flags byte, body []byte) error {
if c.conn == nil {
return fmt.Errorf("netpipe: not connected")
}
packet := make([]byte, 1+len(body))
packet[0] = flags
copy(packet[1:], body)
_, err := c.conn.Write(packet)
return err
}
// listenUDP runs the UDP receive loop for the client.
func (c *Client) listenUDP() {
if c.conn == nil {
return
}
buf := make([]byte, udpMaxPacket)
for {
n, err := c.conn.Read(buf)
if err != nil {
break
}
if n < 1 {
continue
}
flags := buf[0]
body := make([]byte, n-1)
copy(body, buf[1:n])
// Stage 7: server ping - auto-respond with pong
if flags&flagPing != 0 {
c.sendPong()
continue
}
// Ignore pong from server
if flags&flagPong != 0 {
continue
}
// Stage 6: stream chunk - buffer and reassemble
if flags&flagStream != 0 {
streamID, index, total, chunk, err := parseStreamBody(body)
if err != nil {
continue
}
assembled, complete := c.streams.addChunk(streamID, index, total, chunk)
if complete && c.onStream != nil {
c.onStream(assembled)
}
continue
}
data := body
// auto-decrypt if flagged and key provided
if flags&flagEncrypted != 0 && c.encryptionKey != "" {
plaintext, err := decrypt(body, c.encryptionKey)
if err != nil {
continue
}
data = plaintext
}
if c.onData != nil {
c.onData(data)
}
}
c.conn = nil
if c.onDisconnect != nil {
c.onDisconnect()
}
}
// ---------------------------------------------------------------------------
// UDP fields added to Server and Client - initialised in constructors
// ---------------------------------------------------------------------------
// udpFields holds UDP-specific server state. Embedded via composition
// in the Server struct (see server.go changes).
type udpFields struct {
udpConn *net.UDPConn
udpClients map[string]*udpClient // key = "ip:port"
udpMu sync.RWMutex
}