Skip to content

Commit d935785

Browse files
committed
Do not panic on empty extensions
Zero length extension is valid per the RFC3550 spec, This is a fix for panic on marshaling empty extensions.
1 parent 62819f5 commit d935785

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

packet.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -337,12 +337,16 @@ func (h Header) MarshalTo(buf []byte) (n int, err error) { //nolint:cyclop
337337
n += copy(buf[n:], extension.payload)
338338
}
339339
default: // RFC3550 Extension
340-
extlen := len(h.Extensions[0].payload)
341-
if extlen%4 != 0 {
342-
// the payload must be in 32-bit words.
343-
return 0, io.ErrShortBuffer
340+
// Zero length extension is valid per the RFC3550 spec
341+
// https://www.rfc-editor.org/rfc/rfc3550#section-5.3.1
342+
if len(h.Extensions) > 0 {
343+
extlen := len(h.Extensions[0].payload)
344+
if extlen%4 != 0 {
345+
// the payload must be in 32-bit words.
346+
return 0, io.ErrShortBuffer
347+
}
348+
n += copy(buf[n:], h.Extensions[0].payload)
344349
}
345-
n += copy(buf[n:], h.Extensions[0].payload)
346350
}
347351

348352
// calculate extensions size and round to 4 bytes boundaries
@@ -382,7 +386,9 @@ func (h Header) MarshalSize() int {
382386
extSize += 2 + len(extension.payload)
383387
}
384388
default:
385-
extSize += len(h.Extensions[0].payload)
389+
if len(h.Extensions) > 0 {
390+
extSize += len(h.Extensions[0].payload)
391+
}
386392
}
387393

388394
// extensions size must have 4 bytes boundaries

packet_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1428,3 +1428,24 @@ func BenchmarkUnmarshal(b *testing.B) {
14281428
}
14291429
})
14301430
}
1431+
1432+
// https://github.com/pion/rtp/issues/315
1433+
func TestMarshalSizePanic(t *testing.T) {
1434+
hdr := &Header{
1435+
Extension: true,
1436+
}
1437+
1438+
assert.Equal(t, 16, hdr.MarshalSize())
1439+
}
1440+
1441+
// https://github.com/pion/rtp/issues/315
1442+
func TestMarshalToPanic(t *testing.T) {
1443+
hdr := &Header{
1444+
Extension: true,
1445+
}
1446+
1447+
buf := make([]byte, 16)
1448+
n, err := hdr.MarshalTo(buf)
1449+
assert.NoError(t, err)
1450+
assert.Equal(t, 16, n)
1451+
}

0 commit comments

Comments
 (0)