direct.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. package ray
  2. import (
  3. "io"
  4. "v2ray.com/core/common/buf"
  5. )
  6. const (
  7. bufferSize = 512
  8. )
  9. // NewRay creates a new Ray for direct traffic transport.
  10. func NewRay() Ray {
  11. return &directRay{
  12. Input: NewStream(),
  13. Output: NewStream(),
  14. }
  15. }
  16. type directRay struct {
  17. Input *Stream
  18. Output *Stream
  19. }
  20. func (v *directRay) OutboundInput() InputStream {
  21. return v.Input
  22. }
  23. func (v *directRay) OutboundOutput() OutputStream {
  24. return v.Output
  25. }
  26. func (v *directRay) InboundInput() OutputStream {
  27. return v.Input
  28. }
  29. func (v *directRay) InboundOutput() InputStream {
  30. return v.Output
  31. }
  32. type Stream struct {
  33. buffer chan *buf.Buffer
  34. srcClose chan bool
  35. destClose chan bool
  36. }
  37. func NewStream() *Stream {
  38. return &Stream{
  39. buffer: make(chan *buf.Buffer, bufferSize),
  40. srcClose: make(chan bool),
  41. destClose: make(chan bool),
  42. }
  43. }
  44. func (v *Stream) Read() (*buf.Buffer, error) {
  45. select {
  46. case <-v.destClose:
  47. return nil, io.ErrClosedPipe
  48. case b := <-v.buffer:
  49. return b, nil
  50. default:
  51. select {
  52. case b := <-v.buffer:
  53. return b, nil
  54. case <-v.srcClose:
  55. return nil, io.EOF
  56. case <-v.destClose:
  57. return nil, io.ErrClosedPipe
  58. }
  59. }
  60. }
  61. func (v *Stream) Write(data *buf.Buffer) (err error) {
  62. if data.IsEmpty() {
  63. return
  64. }
  65. select {
  66. case <-v.destClose:
  67. return io.ErrClosedPipe
  68. case <-v.srcClose:
  69. return io.ErrClosedPipe
  70. default:
  71. select {
  72. case <-v.destClose:
  73. return io.ErrClosedPipe
  74. case <-v.srcClose:
  75. return io.ErrClosedPipe
  76. case v.buffer <- data:
  77. return nil
  78. }
  79. }
  80. }
  81. func (v *Stream) Close() {
  82. defer swallowPanic()
  83. close(v.srcClose)
  84. }
  85. func (v *Stream) ForceClose() {
  86. defer swallowPanic()
  87. close(v.destClose)
  88. v.Close()
  89. n := len(v.buffer)
  90. for i := 0; i < n; i++ {
  91. select {
  92. case b := <-v.buffer:
  93. b.Release()
  94. default:
  95. return
  96. }
  97. }
  98. }
  99. func (v *Stream) Release() {}
  100. func swallowPanic() {
  101. recover()
  102. }