1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-09 11:51:02 -05:00
v2fly/transport/internet/kcp/io.go

93 lines
1.6 KiB
Go
Raw Normal View History

2016-12-08 10:27:41 -05:00
package kcp
import (
"crypto/cipher"
"crypto/rand"
"io"
"v2ray.com/core/transport/internet"
)
type PacketReader interface {
Read([]byte) []Segment
}
type PacketWriter interface {
Overhead() int
io.Writer
}
type KCPPacketReader struct {
Security cipher.AEAD
Header internet.PacketHeader
}
2017-04-13 16:17:58 -04:00
func (r *KCPPacketReader) Read(b []byte) []Segment {
if r.Header != nil {
b = b[r.Header.Size():]
2016-12-08 10:27:41 -05:00
}
2017-04-13 16:17:58 -04:00
if r.Security != nil {
nonceSize := r.Security.NonceSize()
out, err := r.Security.Open(b[nonceSize:nonceSize], b[:nonceSize], b[nonceSize:], nil)
2016-12-08 10:27:41 -05:00
if err != nil {
return nil
}
b = out
}
var result []Segment
for len(b) > 0 {
seg, x := ReadSegment(b)
if seg == nil {
break
}
result = append(result, seg)
b = x
}
return result
}
type KCPPacketWriter struct {
Header internet.PacketHeader
Security cipher.AEAD
Writer io.Writer
buffer [32 * 1024]byte
}
2017-04-13 16:17:58 -04:00
func (w *KCPPacketWriter) Overhead() int {
2016-12-08 10:27:41 -05:00
overhead := 0
2017-04-13 16:17:58 -04:00
if w.Header != nil {
overhead += w.Header.Size()
2016-12-08 10:27:41 -05:00
}
2017-04-13 16:17:58 -04:00
if w.Security != nil {
overhead += w.Security.Overhead()
2016-12-08 10:27:41 -05:00
}
return overhead
}
2017-04-13 16:17:58 -04:00
func (w *KCPPacketWriter) Write(b []byte) (int, error) {
x := w.buffer[:]
2016-12-08 10:27:41 -05:00
size := 0
2017-04-13 16:17:58 -04:00
if w.Header != nil {
nBytes, _ := w.Header.Write(x)
2016-12-08 10:27:41 -05:00
size += nBytes
x = x[nBytes:]
}
2017-04-13 16:17:58 -04:00
if w.Security != nil {
nonceSize := w.Security.NonceSize()
2016-12-08 10:27:41 -05:00
var nonce []byte
if nonceSize > 0 {
nonce = x[:nonceSize]
rand.Read(nonce)
x = x[nonceSize:]
}
2017-04-13 16:17:58 -04:00
x = w.Security.Seal(x[:0], nonce, b, nil)
2016-12-08 10:27:41 -05:00
size += nonceSize + len(x)
} else {
size += copy(x, b)
}
2017-04-13 16:17:58 -04:00
_, err := w.Writer.Write(w.buffer[:size])
2016-12-08 10:27:41 -05:00
return len(b), err
}