turbotunnel.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package lib
  2. import (
  3. "bufio"
  4. "errors"
  5. "io"
  6. "net"
  7. "time"
  8. "git.torproject.org/pluggable-transports/snowflake.git/common/encapsulation"
  9. )
  10. var errNotImplemented = errors.New("not implemented")
  11. // EncapsulationPacketConn implements the net.PacketConn interface over an
  12. // io.ReadWriteCloser stream, using the encapsulation package to represent
  13. // packets in a stream.
  14. type EncapsulationPacketConn struct {
  15. io.ReadWriteCloser
  16. localAddr net.Addr
  17. remoteAddr net.Addr
  18. bw *bufio.Writer
  19. }
  20. // NewEncapsulationPacketConn makes
  21. func NewEncapsulationPacketConn(
  22. localAddr, remoteAddr net.Addr,
  23. conn io.ReadWriteCloser,
  24. ) *EncapsulationPacketConn {
  25. return &EncapsulationPacketConn{
  26. ReadWriteCloser: conn,
  27. localAddr: localAddr,
  28. remoteAddr: remoteAddr,
  29. bw: bufio.NewWriter(conn),
  30. }
  31. }
  32. // ReadFrom reads an encapsulated packet from the stream.
  33. func (c *EncapsulationPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
  34. data, err := encapsulation.ReadData(c.ReadWriteCloser)
  35. if err != nil {
  36. return 0, c.remoteAddr, err
  37. }
  38. return copy(p, data), c.remoteAddr, nil
  39. }
  40. // WriteTo writes an encapsulated packet to the stream.
  41. func (c *EncapsulationPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
  42. // addr is ignored.
  43. _, err := encapsulation.WriteData(c.bw, p)
  44. if err == nil {
  45. err = c.bw.Flush()
  46. }
  47. if err != nil {
  48. return 0, err
  49. }
  50. return len(p), nil
  51. }
  52. // LocalAddr returns the localAddr value that was passed to
  53. // NewEncapsulationPacketConn.
  54. func (c *EncapsulationPacketConn) LocalAddr() net.Addr {
  55. return c.localAddr
  56. }
  57. func (c *EncapsulationPacketConn) SetDeadline(t time.Time) error { return errNotImplemented }
  58. func (c *EncapsulationPacketConn) SetReadDeadline(t time.Time) error { return errNotImplemented }
  59. func (c *EncapsulationPacketConn) SetWriteDeadline(t time.Time) error { return errNotImplemented }