github.com/sagernet/sing-mux@v0.2.1-0.20240124034317-9bfb33698bb6/client_conn_wait.go (about)

     1  package mux
     2  
     3  import (
     4  	"encoding/binary"
     5  
     6  	"github.com/sagernet/sing/common/buf"
     7  	M "github.com/sagernet/sing/common/metadata"
     8  	N "github.com/sagernet/sing/common/network"
     9  )
    10  
    11  var _ N.PacketReadWaiter = (*clientPacketConn)(nil)
    12  
    13  func (c *clientPacketConn) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool) {
    14  	c.readWaitOptions = options
    15  	return false
    16  }
    17  
    18  func (c *clientPacketConn) WaitReadPacket() (buffer *buf.Buffer, destination M.Socksaddr, err error) {
    19  	if !c.responseRead {
    20  		err = c.readResponse()
    21  		if err != nil {
    22  			return
    23  		}
    24  		c.responseRead = true
    25  	}
    26  	var length uint16
    27  	err = binary.Read(c.conn, binary.BigEndian, &length)
    28  	if err != nil {
    29  		return
    30  	}
    31  	buffer = c.readWaitOptions.NewPacketBuffer()
    32  	_, err = buffer.ReadFullFrom(c.conn, int(length))
    33  	if err != nil {
    34  		buffer.Release()
    35  		return nil, M.Socksaddr{}, err
    36  	}
    37  	c.readWaitOptions.PostReturn(buffer)
    38  	return
    39  }
    40  
    41  var _ N.PacketReadWaiter = (*clientPacketAddrConn)(nil)
    42  
    43  func (c *clientPacketAddrConn) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool) {
    44  	c.readWaitOptions = options
    45  	return false
    46  }
    47  
    48  func (c *clientPacketAddrConn) WaitReadPacket() (buffer *buf.Buffer, destination M.Socksaddr, err error) {
    49  	if !c.responseRead {
    50  		err = c.readResponse()
    51  		if err != nil {
    52  			return
    53  		}
    54  		c.responseRead = true
    55  	}
    56  	destination, err = M.SocksaddrSerializer.ReadAddrPort(c.conn)
    57  	if err != nil {
    58  		return
    59  	}
    60  	var length uint16
    61  	err = binary.Read(c.conn, binary.BigEndian, &length)
    62  	if err != nil {
    63  		return
    64  	}
    65  	buffer = c.readWaitOptions.NewPacketBuffer()
    66  	_, err = buffer.ReadFullFrom(c.conn, int(length))
    67  	if err != nil {
    68  		buffer.Release()
    69  		return nil, M.Socksaddr{}, err
    70  	}
    71  	c.readWaitOptions.PostReturn(buffer)
    72  	return
    73  }