You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/proxy/vmess/io/reader.go

125 lines
2.5 KiB

package io
import (
9 years ago
"hash"
"hash/fnv"
"io"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/transport"
)
9 years ago
// @Private
func AllocBuffer(size int) *alloc.Buffer {
if size < 8*1024-16 {
return alloc.NewBuffer()
}
return alloc.NewLargeBuffer()
}
// @Private
type Validator struct {
actualAuth hash.Hash32
expectedAuth uint32
}
func NewValidator(expectedAuth uint32) *Validator {
return &Validator{
actualAuth: fnv.New32a(),
expectedAuth: expectedAuth,
}
}
func (this *Validator) Consume(b []byte) {
this.actualAuth.Write(b)
}
func (this *Validator) Validate() bool {
return this.actualAuth.Sum32() == this.expectedAuth
}
type AuthChunkReader struct {
9 years ago
reader io.Reader
last *alloc.Buffer
chunkLength int
validator *Validator
}
func NewAuthChunkReader(reader io.Reader) *AuthChunkReader {
return &AuthChunkReader{
9 years ago
reader: reader,
chunkLength: -1,
}
}
func (this *AuthChunkReader) Read() (*alloc.Buffer, error) {
9 years ago
var buffer *alloc.Buffer
if this.last != nil {
buffer = this.last
this.last = nil
} else {
buffer = AllocBuffer(this.chunkLength).Clear()
}
_, err := buffer.FillFrom(this.reader)
if err != nil {
buffer.Release()
return nil, err
}
9 years ago
if this.chunkLength == -1 {
for buffer.Len() < 6 {
_, err := buffer.FillFrom(this.reader)
if err != nil {
buffer.Release()
return nil, err
}
}
length := serial.BytesLiteral(buffer.Value[:2]).Uint16Value()
this.chunkLength = int(length) - 4
this.validator = NewValidator(serial.BytesLiteral(buffer.Value[2:6]).Uint32Value())
buffer.SliceFrom(6)
}
9 years ago
if this.chunkLength == 0 {
buffer.Release()
9 years ago
return nil, io.EOF
}
9 years ago
if buffer.Len() <= this.chunkLength {
this.validator.Consume(buffer.Value)
this.chunkLength -= buffer.Len()
if this.chunkLength == 0 {
if !this.validator.Validate() {
buffer.Release()
return nil, transport.ErrorCorruptedPacket
}
this.chunkLength = -1
this.validator = nil
}
} else {
this.validator.Consume(buffer.Value[:this.chunkLength])
if !this.validator.Validate() {
buffer.Release()
return nil, transport.ErrorCorruptedPacket
}
leftLength := buffer.Len() - this.chunkLength
this.last = AllocBuffer(leftLength).Clear()
this.last.Append(buffer.Value[this.chunkLength:])
buffer.Slice(0, this.chunkLength)
this.chunkLength = -1
this.validator = nil
}
9 years ago
return buffer, nil
}
func (this *AuthChunkReader) Release() {
this.reader = nil
9 years ago
this.last.Release()
this.last = nil
this.validator = nil
}