github.com/sagernet/sing-box@v1.9.0-rc.20/transport/trojan/service_wait.go (about)

     1  package trojan
     2  
     3  import (
     4  	"encoding/binary"
     5  
     6  	"github.com/sagernet/sing/common/buf"
     7  	E "github.com/sagernet/sing/common/exceptions"
     8  	M "github.com/sagernet/sing/common/metadata"
     9  	N "github.com/sagernet/sing/common/network"
    10  	"github.com/sagernet/sing/common/rw"
    11  )
    12  
    13  var _ N.PacketReadWaiter = (*PacketConn)(nil)
    14  
    15  func (c *PacketConn) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool) {
    16  	c.readWaitOptions = options
    17  	return false
    18  }
    19  
    20  func (c *PacketConn) WaitReadPacket() (buffer *buf.Buffer, destination M.Socksaddr, err error) {
    21  	destination, err = M.SocksaddrSerializer.ReadAddrPort(c.Conn)
    22  	if err != nil {
    23  		return nil, M.Socksaddr{}, E.Cause(err, "read destination")
    24  	}
    25  
    26  	var length uint16
    27  	err = binary.Read(c.Conn, binary.BigEndian, &length)
    28  	if err != nil {
    29  		return nil, M.Socksaddr{}, E.Cause(err, "read chunk length")
    30  	}
    31  
    32  	err = rw.SkipN(c.Conn, 2)
    33  	if err != nil {
    34  		return nil, M.Socksaddr{}, E.Cause(err, "skip crlf")
    35  	}
    36  
    37  	buffer = c.readWaitOptions.NewPacketBuffer()
    38  	_, err = buffer.ReadFullFrom(c.Conn, int(length))
    39  	if err != nil {
    40  		buffer.Release()
    41  		return
    42  	}
    43  	c.readWaitOptions.PostReturn(buffer)
    44  	return
    45  }