mihomo/transport/vmess/aead.go

125 lines
2.3 KiB
Go
Raw Permalink Normal View History

2018-09-06 10:53:29 +08:00
package vmess
import (
"crypto/cipher"
"encoding/binary"
"errors"
"io"
"sync"
2019-04-23 23:29:36 +08:00
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/common/pool"
2018-09-06 10:53:29 +08:00
)
type aeadWriter struct {
io.Writer
cipher.AEAD
nonce [32]byte
count uint16
iv []byte
writeLock sync.Mutex
2018-09-06 10:53:29 +08:00
}
func newAEADWriter(w io.Writer, aead cipher.AEAD, iv []byte) *aeadWriter {
return &aeadWriter{Writer: w, AEAD: aead, iv: iv}
}
func (w *aeadWriter) Write(b []byte) (n int, err error) {
w.writeLock.Lock()
2020-04-25 00:30:40 +08:00
buf := pool.Get(pool.RelayBufferSize)
defer func() {
w.writeLock.Unlock()
pool.Put(buf)
}()
2018-09-06 10:53:29 +08:00
length := len(b)
for {
if length == 0 {
break
}
readLen := chunkSize - w.Overhead()
if length < readLen {
readLen = length
}
payloadBuf := buf[lenSize : lenSize+chunkSize-w.Overhead()]
copy(payloadBuf, b[n:n+readLen])
binary.BigEndian.PutUint16(buf[:lenSize], uint16(readLen+w.Overhead()))
binary.BigEndian.PutUint16(w.nonce[:2], w.count)
copy(w.nonce[2:], w.iv[2:12])
w.Seal(payloadBuf[:0], w.nonce[:w.NonceSize()], payloadBuf[:readLen], nil)
w.count++
_, err = w.Writer.Write(buf[:lenSize+readLen+w.Overhead()])
if err != nil {
break
}
n += readLen
length -= readLen
}
return
}
type aeadReader struct {
io.Reader
cipher.AEAD
nonce [32]byte
buf []byte
offset int
iv []byte
sizeBuf []byte
count uint16
}
func newAEADReader(r io.Reader, aead cipher.AEAD, iv []byte) *aeadReader {
return &aeadReader{Reader: r, AEAD: aead, iv: iv, sizeBuf: make([]byte, lenSize)}
}
func (r *aeadReader) Read(b []byte) (int, error) {
if r.buf != nil {
n := copy(b, r.buf[r.offset:])
r.offset += n
if r.offset == len(r.buf) {
2020-04-25 00:30:40 +08:00
pool.Put(r.buf)
2018-09-06 10:53:29 +08:00
r.buf = nil
}
return n, nil
}
_, err := io.ReadFull(r.Reader, r.sizeBuf)
if err != nil {
return 0, err
}
size := int(binary.BigEndian.Uint16(r.sizeBuf))
if size > maxSize {
2020-08-25 22:19:59 +08:00
return 0, errors.New("buffer is larger than standard")
2018-09-06 10:53:29 +08:00
}
2020-04-25 00:30:40 +08:00
buf := pool.Get(size)
2018-09-06 10:53:29 +08:00
_, err = io.ReadFull(r.Reader, buf[:size])
if err != nil {
2020-04-25 00:30:40 +08:00
pool.Put(buf)
2018-09-06 10:53:29 +08:00
return 0, err
}
binary.BigEndian.PutUint16(r.nonce[:2], r.count)
copy(r.nonce[2:], r.iv[2:12])
_, err = r.Open(buf[:0], r.nonce[:r.NonceSize()], buf[:size], nil)
r.count++
if err != nil {
return 0, err
}
realLen := size - r.Overhead()
n := copy(b, buf[:realLen])
if len(b) >= realLen {
2020-04-25 00:30:40 +08:00
pool.Put(buf)
2018-09-06 10:53:29 +08:00
return n, nil
}
r.offset = n
r.buf = buf[:realLen]
return n, nil
}