outbound.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package commander
  2. import (
  3. "context"
  4. "sync"
  5. "v2ray.com/core"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/net"
  8. "v2ray.com/core/common/signal"
  9. "v2ray.com/core/transport/pipe"
  10. )
  11. // OutboundListener is a net.Listener for listening gRPC connections.
  12. type OutboundListener struct {
  13. buffer chan net.Conn
  14. done *signal.Done
  15. }
  16. func (l *OutboundListener) add(conn net.Conn) {
  17. select {
  18. case l.buffer <- conn:
  19. case <-l.done.Wait():
  20. common.Ignore(conn.Close(), "We can do nothing if Close() returns error.")
  21. default:
  22. common.Ignore(conn.Close(), "We can do nothing if Close() returns error.")
  23. }
  24. }
  25. // Accept implements net.Listener.
  26. func (l *OutboundListener) Accept() (net.Conn, error) {
  27. select {
  28. case <-l.done.Wait():
  29. return nil, newError("listen closed")
  30. case c := <-l.buffer:
  31. return c, nil
  32. }
  33. }
  34. // Close implement net.Listener.
  35. func (l *OutboundListener) Close() error {
  36. common.Must(l.done.Close())
  37. L:
  38. for {
  39. select {
  40. case c := <-l.buffer:
  41. common.Ignore(c.Close(), "We can do nothing if errored.")
  42. default:
  43. break L
  44. }
  45. }
  46. return nil
  47. }
  48. // Addr implements net.Listener.
  49. func (l *OutboundListener) Addr() net.Addr {
  50. return &net.TCPAddr{
  51. IP: net.IP{0, 0, 0, 0},
  52. Port: 0,
  53. }
  54. }
  55. // Outbound is a core.OutboundHandler that handles gRPC connections.
  56. type Outbound struct {
  57. tag string
  58. listener *OutboundListener
  59. access sync.RWMutex
  60. closed bool
  61. }
  62. // Dispatch implements core.OutboundHandler.
  63. func (co *Outbound) Dispatch(ctx context.Context, link *core.Link) {
  64. co.access.RLock()
  65. if co.closed {
  66. pipe.CloseError(link.Reader)
  67. pipe.CloseError(link.Writer)
  68. co.access.RUnlock()
  69. return
  70. }
  71. closeSignal := signal.NewNotifier()
  72. c := net.NewConnection(net.ConnectionInputMulti(link.Writer), net.ConnectionOutputMulti(link.Reader), net.ConnectionOnClose(closeSignal))
  73. co.listener.add(c)
  74. co.access.RUnlock()
  75. <-closeSignal.Wait()
  76. }
  77. // Tag implements core.OutboundHandler.
  78. func (co *Outbound) Tag() string {
  79. return co.tag
  80. }
  81. // Start implements common.Runnable.
  82. func (co *Outbound) Start() error {
  83. co.access.Lock()
  84. co.closed = false
  85. co.access.Unlock()
  86. return nil
  87. }
  88. // Close implements common.Closable.
  89. func (co *Outbound) Close() error {
  90. co.access.Lock()
  91. defer co.access.Unlock()
  92. co.closed = true
  93. return co.listener.Close()
  94. }