readv_reader.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // +build !windows
  2. package buf
  3. import (
  4. "io"
  5. "runtime"
  6. "syscall"
  7. "unsafe"
  8. "v2ray.com/core/common/platform"
  9. )
  10. type ReadVReader struct {
  11. io.Reader
  12. rawConn syscall.RawConn
  13. iovects []syscall.Iovec
  14. nBuf int32
  15. }
  16. func NewReadVReader(reader io.Reader, rawConn syscall.RawConn) *ReadVReader {
  17. return &ReadVReader{
  18. Reader: reader,
  19. rawConn: rawConn,
  20. nBuf: 1,
  21. }
  22. }
  23. func allocN(n int32) []*Buffer {
  24. bs := make([]*Buffer, 0, n)
  25. for i := int32(0); i < n; i++ {
  26. bs = append(bs, New())
  27. }
  28. return bs
  29. }
  30. func (r *ReadVReader) ReadMultiBuffer() (MultiBuffer, error) {
  31. bs := allocN(r.nBuf)
  32. var iovecs []syscall.Iovec
  33. if r.iovects != nil {
  34. iovecs = r.iovects
  35. }
  36. for idx, b := range bs {
  37. iovecs = append(iovecs, syscall.Iovec{
  38. Base: &(b.v[0]),
  39. })
  40. iovecs[idx].SetLen(int(Size))
  41. }
  42. r.iovects = iovecs[:0]
  43. var nBytes int
  44. err := r.rawConn.Read(func(fd uintptr) bool {
  45. n, _, e := syscall.Syscall(syscall.SYS_READV, fd, uintptr(unsafe.Pointer(&iovecs[0])), uintptr(len(iovecs)))
  46. if e != 0 {
  47. return false
  48. }
  49. nBytes = int(n)
  50. return true
  51. })
  52. if err != nil {
  53. mb := MultiBuffer(bs)
  54. mb.Release()
  55. return nil, err
  56. }
  57. if nBytes == 0 {
  58. mb := MultiBuffer(bs)
  59. mb.Release()
  60. return nil, io.EOF
  61. }
  62. var isFull bool = (nBytes == int(r.nBuf)*Size)
  63. nBuf := 0
  64. for nBuf < len(bs) {
  65. if nBytes <= 0 {
  66. break
  67. }
  68. end := int32(nBytes)
  69. if end > Size {
  70. end = Size
  71. }
  72. bs[nBuf].end = end
  73. nBytes -= int(end)
  74. nBuf++
  75. }
  76. for i := nBuf; i < len(bs); i++ {
  77. bs[i].Release()
  78. bs[i] = nil
  79. }
  80. if isFull && nBuf < 128 {
  81. r.nBuf *= 4
  82. } else {
  83. r.nBuf = int32(nBuf)
  84. }
  85. return MultiBuffer(bs[:nBuf]), nil
  86. }
  87. var useReadv = false
  88. func init() {
  89. const defaultFlagValue = "NOT_DEFINED_AT_ALL"
  90. value := platform.NewEnvFlag("v2ray.buf.readv").GetValue(func() string { return defaultFlagValue })
  91. if value != defaultFlagValue && (runtime.GOOS == "linux" || runtime.GOOS == "darwin") {
  92. useReadv = true
  93. }
  94. }