conn.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. //go:build !confonly
  2. // +build !confonly
  3. package encoding
  4. import (
  5. "bytes"
  6. "context"
  7. "io"
  8. "net"
  9. "time"
  10. "google.golang.org/grpc/peer"
  11. )
  12. // GunService is the abstract interface of GunService_TunClient and GunService_TunServer
  13. type GunService interface {
  14. Context() context.Context
  15. Send(*Hunk) error
  16. Recv() (*Hunk, error)
  17. }
  18. // GunConn implements net.Conn for gun tunnel
  19. type GunConn struct {
  20. service GunService
  21. reader io.Reader
  22. over context.CancelFunc
  23. local net.Addr
  24. remote net.Addr
  25. }
  26. // Read implements net.Conn.Read()
  27. func (c *GunConn) Read(b []byte) (n int, err error) {
  28. if c.reader == nil {
  29. h, err := c.service.Recv()
  30. if err != nil {
  31. return 0, newError("unable to read from gun tunnel").Base(err)
  32. }
  33. c.reader = bytes.NewReader(h.Data)
  34. }
  35. n, err = c.reader.Read(b)
  36. if err == io.EOF {
  37. c.reader = nil
  38. return n, nil
  39. }
  40. return n, err
  41. }
  42. // Write implements net.Conn.Write()
  43. func (c *GunConn) Write(b []byte) (n int, err error) {
  44. err = c.service.Send(&Hunk{Data: b})
  45. if err != nil {
  46. return 0, newError("Unable to send data over gun").Base(err)
  47. }
  48. return len(b), nil
  49. }
  50. // Close implements net.Conn.Close()
  51. func (c *GunConn) Close() error {
  52. if c.over != nil {
  53. c.over()
  54. }
  55. return nil
  56. }
  57. // LocalAddr implements net.Conn.LocalAddr()
  58. func (c *GunConn) LocalAddr() net.Addr {
  59. return c.local
  60. }
  61. // RemoteAddr implements net.Conn.RemoteAddr()
  62. func (c *GunConn) RemoteAddr() net.Addr {
  63. return c.remote
  64. }
  65. // SetDeadline implements net.Conn.SetDeadline()
  66. func (*GunConn) SetDeadline(time.Time) error {
  67. return nil
  68. }
  69. // SetReadDeadline implements net.Conn.SetReadDeadline()
  70. func (*GunConn) SetReadDeadline(time.Time) error {
  71. return nil
  72. }
  73. // SetWriteDeadline implements net.Conn.SetWriteDeadline()
  74. func (*GunConn) SetWriteDeadline(time.Time) error {
  75. return nil
  76. }
  77. // NewGunConn creates GunConn which handles gun tunnel
  78. func NewGunConn(service GunService, over context.CancelFunc) *GunConn {
  79. conn := &GunConn{
  80. service: service,
  81. reader: nil,
  82. over: over,
  83. }
  84. conn.local = &net.TCPAddr{
  85. IP: []byte{0, 0, 0, 0},
  86. Port: 0,
  87. }
  88. pr, ok := peer.FromContext(service.Context())
  89. if ok {
  90. conn.remote = pr.Addr
  91. } else {
  92. conn.remote = &net.TCPAddr{
  93. IP: []byte{0, 0, 0, 0},
  94. Port: 0,
  95. }
  96. }
  97. return conn
  98. }