github.com/MerlinKodo/sing-tun@v0.1.15/stack_gvisor_err.go (about)

     1  //go:build with_gvisor
     2  
     3  package tun
     4  
     5  import (
     6  	"net"
     7  
     8  	E "github.com/sagernet/sing/common/exceptions"
     9  
    10  	"github.com/MerlinKodo/gvisor/pkg/tcpip"
    11  	"github.com/MerlinKodo/gvisor/pkg/tcpip/adapters/gonet"
    12  )
    13  
    14  type gTCPConn struct {
    15  	*gonet.TCPConn
    16  }
    17  
    18  func (c *gTCPConn) Upstream() any {
    19  	return c.TCPConn
    20  }
    21  
    22  func (c *gTCPConn) Write(b []byte) (n int, err error) {
    23  	n, err = c.TCPConn.Write(b)
    24  	if err == nil {
    25  		return
    26  	}
    27  	err = wrapError(err)
    28  	return
    29  }
    30  
    31  func wrapStackError(err tcpip.Error) error {
    32  	switch err.(type) {
    33  	case *tcpip.ErrClosedForSend,
    34  		*tcpip.ErrClosedForReceive,
    35  		*tcpip.ErrAborted:
    36  		return net.ErrClosed
    37  	}
    38  	return E.New(err.String())
    39  }
    40  
    41  func wrapError(err error) error {
    42  	if opErr, isOpErr := err.(*net.OpError); isOpErr {
    43  		switch opErr.Err.Error() {
    44  		case "endpoint is closed for send",
    45  			"endpoint is closed for receive",
    46  			"operation aborted":
    47  			return net.ErrClosed
    48  		}
    49  	}
    50  	return err
    51  }