github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/proxy/vlite/inbound/connAdp.go (about)

     1  package inbound
     2  
     3  import (
     4  	"io"
     5  	"net"
     6  
     7  	"github.com/v2fly/v2ray-core/v5/common/buf"
     8  	"github.com/v2fly/v2ray-core/v5/common/signal/done"
     9  )
    10  
    11  func newUDPConnAdaptor(conn net.Conn, done *done.Instance) net.Conn {
    12  	return &udpConnAdp{
    13  		Conn:              conn,
    14  		reader:            buf.NewPacketReader(conn),
    15  		cachedMultiBuffer: nil,
    16  		finished:          done,
    17  	}
    18  }
    19  
    20  type udpConnAdp struct {
    21  	net.Conn
    22  	reader buf.Reader
    23  
    24  	cachedMultiBuffer buf.MultiBuffer
    25  
    26  	finished *done.Instance
    27  }
    28  
    29  func (u *udpConnAdp) Read(p []byte) (n int, err error) {
    30  	if u.cachedMultiBuffer.IsEmpty() {
    31  		u.cachedMultiBuffer, err = u.reader.ReadMultiBuffer()
    32  		if err != nil {
    33  			return 0, newError("unable to read from connection").Base(err)
    34  		}
    35  	}
    36  	var buffer *buf.Buffer
    37  	u.cachedMultiBuffer, buffer = buf.SplitFirst(u.cachedMultiBuffer)
    38  	defer buffer.Release()
    39  	n = copy(p, buffer.Bytes())
    40  	if n != int(buffer.Len()) {
    41  		return 0, io.ErrShortBuffer
    42  	}
    43  	return n, nil
    44  }
    45  
    46  func (u *udpConnAdp) Close() error {
    47  	u.finished.Close()
    48  	return u.Conn.Close()
    49  }