github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/protocol/socks/packet_wait.go (about)

     1  package socks
     2  
     3  import (
     4  	"github.com/sagernet/sing/common/buf"
     5  	"github.com/sagernet/sing/common/bufio"
     6  	M "github.com/sagernet/sing/common/metadata"
     7  	N "github.com/sagernet/sing/common/network"
     8  )
     9  
    10  var _ N.PacketReadWaitCreator = (*AssociatePacketConn)(nil)
    11  
    12  func (c *AssociatePacketConn) CreateReadWaiter() (N.PacketReadWaiter, bool) {
    13  	readWaiter, isReadWaiter := bufio.CreateReadWaiter(c.conn)
    14  	if !isReadWaiter {
    15  		return nil, false
    16  	}
    17  	return &AssociatePacketReadWaiter{c, readWaiter}, true
    18  }
    19  
    20  var _ N.PacketReadWaiter = (*AssociatePacketReadWaiter)(nil)
    21  
    22  type AssociatePacketReadWaiter struct {
    23  	conn       *AssociatePacketConn
    24  	readWaiter N.ReadWaiter
    25  }
    26  
    27  func (w *AssociatePacketReadWaiter) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool) {
    28  	return w.readWaiter.InitializeReadWaiter(options)
    29  }
    30  
    31  func (w *AssociatePacketReadWaiter) WaitReadPacket() (buffer *buf.Buffer, destination M.Socksaddr, err error) {
    32  	buffer, err = w.readWaiter.WaitReadBuffer()
    33  	if err != nil {
    34  		return
    35  	}
    36  	if buffer.Len() < 3 {
    37  		buffer.Release()
    38  		return nil, M.Socksaddr{}, ErrInvalidPacket
    39  	}
    40  	buffer.Advance(3)
    41  	destination, err = M.SocksaddrSerializer.ReadAddrPort(buffer)
    42  	if err != nil {
    43  		buffer.Release()
    44  		return
    45  	}
    46  	w.conn.remoteAddr = destination
    47  	return
    48  }