sys_conn.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package quic
  2. import (
  3. "net"
  4. "syscall"
  5. "time"
  6. "github.com/Psiphon-Labs/quic-go/internal/protocol"
  7. "github.com/Psiphon-Labs/quic-go/internal/utils"
  8. )
  9. // OOBCapablePacketConn is a connection that allows the reading of ECN bits from the IP header.
  10. // If the PacketConn passed to Dial or Listen satisfies this interface, quic-go will use it.
  11. // In this case, ReadMsgUDP() will be used instead of ReadFrom() to read packets.
  12. type OOBCapablePacketConn interface {
  13. net.PacketConn
  14. SyscallConn() (syscall.RawConn, error)
  15. ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)
  16. WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error)
  17. }
  18. var _ OOBCapablePacketConn = &net.UDPConn{}
  19. func wrapConn(pc net.PacketConn) (rawConn, error) {
  20. conn, ok := pc.(interface {
  21. SyscallConn() (syscall.RawConn, error)
  22. })
  23. if ok {
  24. rawConn, err := conn.SyscallConn()
  25. if err != nil {
  26. return nil, err
  27. }
  28. if _, ok := pc.LocalAddr().(*net.UDPAddr); ok {
  29. // Only set DF on sockets that we expect to be able to handle that configuration.
  30. err = setDF(rawConn)
  31. if err != nil {
  32. return nil, err
  33. }
  34. }
  35. }
  36. c, ok := pc.(OOBCapablePacketConn)
  37. if !ok {
  38. utils.DefaultLogger.Infof("PacketConn is not a net.UDPConn. Disabling optimizations possible on UDP connections.")
  39. return &basicConn{PacketConn: pc}, nil
  40. }
  41. return newConn(c)
  42. }
  43. // The basicConn is the most trivial implementation of a connection.
  44. // It reads a single packet from the underlying net.PacketConn.
  45. // It is used when
  46. // * the net.PacketConn is not a OOBCapablePacketConn, and
  47. // * when the OS doesn't support OOB.
  48. type basicConn struct {
  49. net.PacketConn
  50. }
  51. var _ rawConn = &basicConn{}
  52. func (c *basicConn) ReadPacket() (*receivedPacket, error) {
  53. buffer := getPacketBuffer()
  54. // The packet size should not exceed protocol.MaxPacketBufferSize bytes
  55. // If it does, we only read a truncated packet, which will then end up undecryptable
  56. buffer.Data = buffer.Data[:protocol.MaxPacketBufferSize]
  57. n, addr, err := c.PacketConn.ReadFrom(buffer.Data)
  58. if err != nil {
  59. return nil, err
  60. }
  61. return &receivedPacket{
  62. remoteAddr: addr,
  63. rcvTime: time.Now(),
  64. data: buffer.Data[:n],
  65. buffer: buffer,
  66. }, nil
  67. }
  68. func (c *basicConn) WritePacket(b []byte, addr net.Addr, _ []byte) (n int, err error) {
  69. return c.PacketConn.WriteTo(b, addr)
  70. }