make packetPacker use in-place encryption

ref #217
This commit is contained in:
Lucas Clemente 2016-07-26 15:16:23 +02:00
parent d5255a4075
commit 90aa8cfa95

View file

@ -110,11 +110,15 @@ func (p *packetPacker) packPacket(stopWaitingFrame *frames.StopWaitingFrame, con
} }
} }
payload, err := p.getPayload(payloadFrames, currentPacketNumber) raw := make([]byte, 0, protocol.MaxPacketSize)
if err != nil { buffer := bytes.NewBuffer(raw)
if responsePublicHeader.WritePublicHeader(buffer, p.version) != nil {
return nil, err return nil, err
} }
payloadStartIndex := buffer.Len()
// set entropy bit in Private Header, for QUIC version < 34 // set entropy bit in Private Header, for QUIC version < 34
var entropyBit bool var entropyBit bool
if p.version < protocol.Version34 { if p.version < protocol.Version34 {
@ -123,46 +127,33 @@ func (p *packetPacker) packPacket(stopWaitingFrame *frames.StopWaitingFrame, con
return nil, err return nil, err
} }
if entropyBit { if entropyBit {
payload[0] = 1 buffer.WriteByte(1)
} else {
buffer.WriteByte(0)
} }
} }
var raw bytes.Buffer for _, frame := range payloadFrames {
if err := responsePublicHeader.WritePublicHeader(&raw, p.version); err != nil { frame.Write(buffer, p.version)
return nil, err
} }
ciphertext := p.cryptoSetup.Seal(nil, payload, currentPacketNumber, raw.Bytes()) if protocol.ByteCount(buffer.Len()+12) > protocol.MaxPacketSize {
raw.Write(ciphertext)
if protocol.ByteCount(raw.Len()) > protocol.MaxPacketSize {
return nil, errors.New("PacketPacker BUG: packet too large") return nil, errors.New("PacketPacker BUG: packet too large")
} }
raw = raw[0:buffer.Len()]
p.cryptoSetup.Seal(raw[payloadStartIndex:payloadStartIndex], raw[payloadStartIndex:], currentPacketNumber, raw[:payloadStartIndex])
raw = raw[0 : buffer.Len()+12]
p.lastPacketNumber++ p.lastPacketNumber++
return &packedPacket{ return &packedPacket{
number: currentPacketNumber, number: currentPacketNumber,
entropyBit: entropyBit, entropyBit: entropyBit,
raw: raw.Bytes(), raw: raw,
frames: payloadFrames, frames: payloadFrames,
}, nil }, nil
} }
func (p *packetPacker) getPayload(frames []frames.Frame, currentPacketNumber protocol.PacketNumber) ([]byte, error) {
var payload bytes.Buffer
// reserve 1 byte for the Private Header, for QUIC Version < 34
// the entropy bit is set in sendPayload
if p.version < protocol.Version34 {
payload.WriteByte(0)
}
for _, frame := range frames {
frame.Write(&payload, p.version)
}
return payload.Bytes(), nil
}
func (p *packetPacker) composeNextPacket(stopWaitingFrame *frames.StopWaitingFrame, publicHeaderLength protocol.ByteCount) ([]frames.Frame, error) { func (p *packetPacker) composeNextPacket(stopWaitingFrame *frames.StopWaitingFrame, publicHeaderLength protocol.ByteCount) ([]frames.Frame, error) {
var payloadLength protocol.ByteCount var payloadLength protocol.ByteCount
var payloadFrames []frames.Frame var payloadFrames []frames.Frame