connforwarder.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package websocket
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "time"
  7. )
  8. type connectionForwarder struct {
  9. io.ReadWriteCloser
  10. shouldWait bool
  11. delayedDialFinish context.Context
  12. finishedDial context.CancelFunc
  13. dialer DelayedDialerForwarded
  14. }
  15. func (c *connectionForwarder) Read(p []byte) (n int, err error) {
  16. if c.shouldWait {
  17. <-c.delayedDialFinish.Done()
  18. if c.ReadWriteCloser == nil {
  19. return 0, newError("unable to read delayed dial websocket connection as it do not exist")
  20. }
  21. }
  22. return c.ReadWriteCloser.Read(p)
  23. }
  24. func (c *connectionForwarder) Write(p []byte) (n int, err error) {
  25. if c.shouldWait {
  26. var err error
  27. c.ReadWriteCloser, err = c.dialer.Dial(p)
  28. c.finishedDial()
  29. if err != nil {
  30. return 0, newError("Unable to proceed with delayed write").Base(err)
  31. }
  32. c.shouldWait = false
  33. return len(p), nil
  34. }
  35. return c.ReadWriteCloser.Write(p)
  36. }
  37. func (c *connectionForwarder) Close() error {
  38. if c.shouldWait {
  39. <-c.delayedDialFinish.Done()
  40. if c.ReadWriteCloser == nil {
  41. return newError("unable to close delayed dial websocket connection as it do not exist")
  42. }
  43. }
  44. return c.ReadWriteCloser.Close()
  45. }
  46. func (c connectionForwarder) LocalAddr() net.Addr {
  47. return &net.UnixAddr{
  48. Name: "not available",
  49. Net: "",
  50. }
  51. }
  52. func (c connectionForwarder) RemoteAddr() net.Addr {
  53. return &net.UnixAddr{
  54. Name: "not available",
  55. Net: "",
  56. }
  57. }
  58. func (c connectionForwarder) SetDeadline(t time.Time) error {
  59. return nil
  60. }
  61. func (c connectionForwarder) SetReadDeadline(t time.Time) error {
  62. return nil
  63. }
  64. func (c connectionForwarder) SetWriteDeadline(t time.Time) error {
  65. return nil
  66. }
  67. type DelayedDialerForwarded interface {
  68. Dial(earlyData []byte) (io.ReadWriteCloser, error)
  69. }