outbound.go 1.8 KB

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