direct.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. }
  57. }
  58. }
  59. func (v *Stream) Write(data *buf.Buffer) (err error) {
  60. if data.IsEmpty() {
  61. return
  62. }
  63. select {
  64. case <-v.destClose:
  65. return io.ErrClosedPipe
  66. case <-v.srcClose:
  67. return io.ErrClosedPipe
  68. default:
  69. select {
  70. case <-v.destClose:
  71. return io.ErrClosedPipe
  72. case <-v.srcClose:
  73. return io.ErrClosedPipe
  74. case v.buffer <- data:
  75. return nil
  76. }
  77. }
  78. }
  79. func (v *Stream) Close() {
  80. defer swallowPanic()
  81. close(v.srcClose)
  82. }
  83. func (v *Stream) Release() {
  84. defer swallowPanic()
  85. close(v.destClose)
  86. v.Close()
  87. n := len(v.buffer)
  88. for i := 0; i < n; i++ {
  89. select {
  90. case b := <-v.buffer:
  91. b.Release()
  92. default:
  93. return
  94. }
  95. }
  96. }
  97. func swallowPanic() {
  98. recover()
  99. }