-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassociate_multi.go
More file actions
71 lines (59 loc) · 1.84 KB
/
Copy pathassociate_multi.go
File metadata and controls
71 lines (59 loc) · 1.84 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
package socks5
import (
"context"
"github.com/meteorite/scope"
"net"
)
type MultiUDPPortAssociate struct {
ctxServer ContextGo
listenIP net.IP
udpNet string
connFactory RemoteUDPConnFactory
log ErrorLogger
}
// Creates new MultiUDPPortAssociate.
func MakeMultiUDPPortAssociate(
ctxServer ContextGo, listenIP net.IP, udpNet string, connFactory RemoteUDPConnFactory, log ErrorLogger,
) *MultiUDPPortAssociate {
return &MultiUDPPortAssociate{
ctxServer: ctxServer,
listenIP: listenIP,
udpNet: udpNet,
connFactory: connFactory,
log: log,
}
}
func (m *MultiUDPPortAssociate) OnAssociate(ctx context.Context, conn net.Conn) error {
from, _, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
return onAssociateSendError(conn, err)
}
c, err := net.ListenUDP(m.udpNet, &net.UDPAddr{IP: m.listenIP})
if err != nil {
return onAssociateSendError(conn, err)
}
ctxClient, _ := scope.Group(ctx)
defer ctxClient.AddCloser(c).WaitQuietly()
one := makeOneClientUDPRemotes(ctxClient)
ctxClient.Go(func() error { return m.serveOneUDPPort(c, from, one) })
udpAddr := &AddrSpec{IP: m.listenIP, Port: c.LocalAddr().(*net.UDPAddr).Port}
return onAssociateReplyUdpAddrAndWaitForClose(conn, udpAddr, m.log)
}
func (m *MultiUDPPortAssociate) serveOneUDPPort(udpConn *net.UDPConn, clientIP string, one *oneClientUDPRemotes) error {
sendBack := MakeSendBackTo(udpConn)
buffer := make([]byte, m.connFactory.MaxUDPPacketSize())
for {
n, src, err := udpConn.ReadFromUDP(buffer)
if err != nil {
return err
}
fromIP := src.IP.String()
if fromIP != clientIP {
m.log.Printf("udp packet from unauthorized IP: %s != %s", fromIP, clientIP)
continue
}
if err := one.forwardClientPktToRemote(m.ctxServer, src, buffer[:n], m.connFactory, sendBack); err != nil {
m.log.Printf("%v", err)
}
}
}