direct.go 1.7 KB

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