Skip to content

Commit

Permalink
proxy: udp tweaks
Browse files Browse the repository at this point in the history
Signed-off-by: Mark Pashmfouroush <[email protected]>
  • Loading branch information
markpash committed Apr 12, 2024
1 parent 8f930cd commit 29dd4bf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
20 changes: 11 additions & 9 deletions proxy/pkg/socks5/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"io"
"math"
"net"
"strconv"
"strings"
Expand All @@ -20,7 +19,7 @@ var (
)

const (
maxUdpPacket = math.MaxUint16 - 28
maxUdpPacket = 2048
)

const (
Expand Down Expand Up @@ -207,11 +206,14 @@ func readAddr(r io.Reader) (*address, error) {
default:
return nil, errUnrecognizedAddrType
}

var port [2]byte
if _, err := io.ReadFull(r, port[:]); err != nil {
return nil, err
}

address.Port = int(binary.BigEndian.Uint16(port[:]))

return address, nil
}

Expand Down Expand Up @@ -321,8 +323,8 @@ func (cc *udpCustomConn) RemoteAddr() net.Addr {

func (cc *udpCustomConn) asyncReadPackets() {
go func() {
tempBuf := make([]byte, maxUdpPacket)
for {
tempBuf := make([]byte, maxUdpPacket)
n, addr, err := cc.ReadFrom(tempBuf)
if err != nil {
cc.packetQueue <- &readStruct{
Expand All @@ -331,18 +333,18 @@ func (cc *udpCustomConn) asyncReadPackets() {
}
break
}
if cc.sourceAddr == nil {
cc.sourceAddr = addr
}
packetData := tempBuf[:n]
if len(packetData) < 3 {
if n < 3 {
cc.packetQueue <- &readStruct{
data: nil,
err: err,
}
break
}
reader := bytes.NewBuffer(packetData[3:])
if cc.sourceAddr == nil {
cc.sourceAddr = addr
}

reader := bytes.NewBuffer(tempBuf[3:n])
targetAddr, err := readAddr(reader)

if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions proxy/pkg/socks5/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,17 +396,20 @@ func (s *Server) embedHandleAssociate(req *request, udpConn net.PacketConn) erro
s.Logger.Debug(err.Error())
continue
}

if targetAddr == nil {
targetAddr = &net.UDPAddr{
IP: addr.IP,
Port: addr.Port,
}
wantTarget = targetAddr.String()
}

if addr.String() != wantTarget {
s.Logger.Debug("ignore non-target addresses", "address", addr)
continue
}

_, err = udpConn.WriteTo(reader.Bytes(), targetAddr)
if err != nil {
return err
Expand Down

0 comments on commit 29dd4bf

Please sign in to comment.