github.com/ooni/psiphon/tunnel-core@v0.0.0-20230105123940-fe12a24c96ee/oovendor/quic-go/send_conn.go (about)

     1  package quic
     2  
     3  import (
     4  	"net"
     5  )
     6  
     7  // A sendConn allows sending using a simple Write() on a non-connected packet conn.
     8  type sendConn interface {
     9  	Write([]byte) error
    10  	Close() error
    11  	LocalAddr() net.Addr
    12  	RemoteAddr() net.Addr
    13  }
    14  
    15  type sconn struct {
    16  	connection
    17  
    18  	remoteAddr net.Addr
    19  	info       *packetInfo
    20  	oob        []byte
    21  }
    22  
    23  var _ sendConn = &sconn{}
    24  
    25  func newSendConn(c connection, remote net.Addr, info *packetInfo) sendConn {
    26  	return &sconn{
    27  		connection: c,
    28  		remoteAddr: remote,
    29  		info:       info,
    30  		oob:        info.OOB(),
    31  	}
    32  }
    33  
    34  func (c *sconn) Write(p []byte) error {
    35  	_, err := c.WritePacket(p, c.remoteAddr, c.oob)
    36  	return err
    37  }
    38  
    39  func (c *sconn) RemoteAddr() net.Addr {
    40  	return c.remoteAddr
    41  }
    42  
    43  func (c *sconn) LocalAddr() net.Addr {
    44  	addr := c.connection.LocalAddr()
    45  	if c.info != nil {
    46  		if udpAddr, ok := addr.(*net.UDPAddr); ok {
    47  			addrCopy := *udpAddr
    48  			addrCopy.IP = c.info.addr
    49  			addr = &addrCopy
    50  		}
    51  	}
    52  	return addr
    53  }
    54  
    55  type spconn struct {
    56  	net.PacketConn
    57  
    58  	remoteAddr net.Addr
    59  }
    60  
    61  var _ sendConn = &spconn{}
    62  
    63  func newSendPconn(c net.PacketConn, remote net.Addr) sendConn {
    64  	return &spconn{PacketConn: c, remoteAddr: remote}
    65  }
    66  
    67  func (c *spconn) Write(p []byte) error {
    68  	_, err := c.WriteTo(p, c.remoteAddr)
    69  	return err
    70  }
    71  
    72  func (c *spconn) RemoteAddr() net.Addr {
    73  	return c.remoteAddr
    74  }