output.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package kcp
  2. import (
  3. "io"
  4. "sync"
  5. "v2ray.com/core/common/alloc"
  6. v2io "v2ray.com/core/common/io"
  7. "v2ray.com/core/transport/internet"
  8. )
  9. type SegmentWriter interface {
  10. Write(seg Segment)
  11. }
  12. type BufferedSegmentWriter struct {
  13. sync.Mutex
  14. mtu uint32
  15. buffer *alloc.Buffer
  16. writer v2io.Writer
  17. }
  18. func NewSegmentWriter(writer *AuthenticationWriter) *BufferedSegmentWriter {
  19. return &BufferedSegmentWriter{
  20. mtu: writer.Mtu(),
  21. writer: writer,
  22. }
  23. }
  24. func (v *BufferedSegmentWriter) Write(seg Segment) {
  25. v.Lock()
  26. defer v.Unlock()
  27. nBytes := seg.ByteSize()
  28. if uint32(v.buffer.Len()+nBytes) > v.mtu {
  29. v.FlushWithoutLock()
  30. }
  31. if v.buffer == nil {
  32. v.buffer = alloc.NewSmallBuffer()
  33. }
  34. v.buffer.AppendFunc(seg.Bytes())
  35. }
  36. func (v *BufferedSegmentWriter) FlushWithoutLock() {
  37. v.writer.Write(v.buffer)
  38. v.buffer = nil
  39. }
  40. func (v *BufferedSegmentWriter) Flush() {
  41. v.Lock()
  42. defer v.Unlock()
  43. if v.buffer.Len() == 0 {
  44. return
  45. }
  46. v.FlushWithoutLock()
  47. }
  48. type AuthenticationWriter struct {
  49. Authenticator internet.Authenticator
  50. Writer io.Writer
  51. Config *Config
  52. }
  53. func (v *AuthenticationWriter) Write(payload *alloc.Buffer) error {
  54. defer payload.Release()
  55. v.Authenticator.Seal(payload)
  56. _, err := v.Writer.Write(payload.Bytes())
  57. return err
  58. }
  59. func (v *AuthenticationWriter) Release() {}
  60. func (v *AuthenticationWriter) Mtu() uint32 {
  61. return v.Config.Mtu.GetValue() - uint32(v.Authenticator.Overhead())
  62. }