@@ -144,7 +144,7 @@ func NewConn(c net.Conn, side core.Side, recordProtocol string, key []byte, prot
144
144
func (p * conn ) Read (b []byte ) (n int , err error ) {
145
145
if len (p .buf ) == 0 {
146
146
var framedMsg []byte
147
- framedMsg , p . nextFrame , err = ParseFramedMsg (p .nextFrame , altsRecordLengthLimit )
147
+ framedMsg , err = p . parseFramedMsg (p .nextFrame , altsRecordLengthLimit )
148
148
if err != nil {
149
149
return n , err
150
150
}
@@ -184,7 +184,7 @@ func (p *conn) Read(b []byte) (n int, err error) {
184
184
return 0 , err
185
185
}
186
186
p .protected = p .protected [:len (p .protected )+ n ]
187
- framedMsg , p . nextFrame , err = ParseFramedMsg (p .protected , altsRecordLengthLimit )
187
+ framedMsg , err = p . parseFramedMsg (p .protected , altsRecordLengthLimit )
188
188
if err != nil {
189
189
return 0 , err
190
190
}
@@ -225,6 +225,38 @@ func (p *conn) Read(b []byte) (n int, err error) {
225
225
return n , nil
226
226
}
227
227
228
+ // parseFramedMsg parses the provided buffer and returns a frame of the format
229
+ // msgLength+msg iff a full frame is available.
230
+ func (p * conn ) parseFramedMsg (b []byte , maxLen uint32 ) ([]byte , error ) {
231
+ // If the size field is not complete, return the provided buffer as
232
+ // remaining buffer.
233
+ p .nextFrame = b
234
+ length , sufficientBytes := parseMessageLength (b )
235
+ if ! sufficientBytes {
236
+ return nil , nil
237
+ }
238
+ if length > maxLen {
239
+ return nil , fmt .Errorf ("received the frame length %d larger than the limit %d" , length , maxLen )
240
+ }
241
+ if len (b ) < int (length )+ 4 { // account for the first 4 msg length bytes.
242
+ // Frame is not complete yet.
243
+ return nil , nil
244
+ }
245
+ p .nextFrame = b [MsgLenFieldSize + length :]
246
+ return b [:MsgLenFieldSize + length ], nil
247
+ }
248
+
249
+ // parseMessageLength returns the message length based on frame header. It also
250
+ // returns a boolean indicating if the buffer contains sufficient bytes to parse
251
+ // the length header. If there are insufficient bytes, (0, false) is returned.
252
+ func parseMessageLength (b []byte ) (uint32 , bool ) {
253
+ if len (b ) < MsgLenFieldSize {
254
+ return 0 , false
255
+ }
256
+ msgLenField := b [:MsgLenFieldSize ]
257
+ return binary .LittleEndian .Uint32 (msgLenField ), true
258
+ }
259
+
228
260
// Write encrypts, frames, and writes bytes from b to the underlying connection.
229
261
func (p * conn ) Write (b []byte ) (n int , err error ) {
230
262
n = len (b )
0 commit comments