outbound.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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("listern 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. type CommanderOutbound struct {
  50. tag string
  51. listener *OutboundListener
  52. access sync.RWMutex
  53. closed bool
  54. }
  55. func (co *CommanderOutbound) Dispatch(ctx context.Context, r ray.OutboundRay) {
  56. co.access.RLock()
  57. if co.closed {
  58. r.OutboundInput().CloseError()
  59. r.OutboundOutput().CloseError()
  60. co.access.RUnlock()
  61. return
  62. }
  63. closeSignal := signal.NewNotifier()
  64. c := ray.NewConnection(r.OutboundInput(), r.OutboundOutput(), ray.ConnCloseSignal(closeSignal))
  65. co.listener.add(c)
  66. co.access.RUnlock()
  67. <-closeSignal.Wait()
  68. return
  69. }
  70. func (co *CommanderOutbound) Tag() string {
  71. return co.tag
  72. }
  73. func (co *CommanderOutbound) Start() error {
  74. co.access.Lock()
  75. co.closed = false
  76. co.access.Unlock()
  77. return nil
  78. }
  79. func (co *CommanderOutbound) Close() error {
  80. co.access.Lock()
  81. co.closed = true
  82. co.listener.Close()
  83. co.access.Unlock()
  84. return nil
  85. }