outbound.go 2.2 KB

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