summaryrefslogtreecommitdiffhomepage
path: root/pkg/tcpip/network/fragmentation/frag_heap_test.go
blob: 218a24d7bf93525213e0235dcc8b2f90f3d07440 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Copyright 2016 The Netstack Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fragmentation

import (
	"container/heap"
	"reflect"
	"testing"

	"gvisor.googlesource.com/gvisor/pkg/tcpip/buffer"
)

var reassambleTestCases = []struct {
	comment string
	in      []fragment
	want    *buffer.VectorisedView
}{
	{
		comment: "Non-overlapping in-order",
		in: []fragment{
			{offset: 0, vv: vv(1, "0")},
			{offset: 1, vv: vv(1, "1")},
		},
		want: vv(2, "0", "1"),
	},
	{
		comment: "Non-overlapping out-of-order",
		in: []fragment{
			{offset: 1, vv: vv(1, "1")},
			{offset: 0, vv: vv(1, "0")},
		},
		want: vv(2, "0", "1"),
	},
	{
		comment: "Duplicated packets",
		in: []fragment{
			{offset: 0, vv: vv(1, "0")},
			{offset: 0, vv: vv(1, "0")},
		},
		want: vv(1, "0"),
	},
	{
		comment: "Overlapping in-order",
		in: []fragment{
			{offset: 0, vv: vv(2, "01")},
			{offset: 1, vv: vv(2, "12")},
		},
		want: vv(3, "01", "2"),
	},
	{
		comment: "Overlapping out-of-order",
		in: []fragment{
			{offset: 1, vv: vv(2, "12")},
			{offset: 0, vv: vv(2, "01")},
		},
		want: vv(3, "01", "2"),
	},
	{
		comment: "Overlapping subset in-order",
		in: []fragment{
			{offset: 0, vv: vv(3, "012")},
			{offset: 1, vv: vv(1, "1")},
		},
		want: vv(3, "012"),
	},
	{
		comment: "Overlapping subset out-of-order",
		in: []fragment{
			{offset: 1, vv: vv(1, "1")},
			{offset: 0, vv: vv(3, "012")},
		},
		want: vv(3, "012"),
	},
}

func TestReassamble(t *testing.T) {
	for _, c := range reassambleTestCases {
		h := (fragHeap)(make([]fragment, 0, 8))
		heap.Init(&h)
		for _, f := range c.in {
			heap.Push(&h, f)
		}
		got, _ := h.reassemble()

		if !reflect.DeepEqual(got, *c.want) {
			t.Errorf("Test \"%s\" reassembling failed. Got %v. Want %v", c.comment, got, *c.want)
		}
	}
}

func TestReassambleFailsForNonZeroOffset(t *testing.T) {
	h := (fragHeap)(make([]fragment, 0, 8))
	heap.Init(&h)
	heap.Push(&h, fragment{offset: 1, vv: vv(1, "0")})
	_, err := h.reassemble()
	if err == nil {
		t.Errorf("reassemble() did not fail when the first packet had offset != 0")
	}
}

func TestReassambleFailsForHoles(t *testing.T) {
	h := (fragHeap)(make([]fragment, 0, 8))
	heap.Init(&h)
	heap.Push(&h, fragment{offset: 0, vv: vv(1, "0")})
	heap.Push(&h, fragment{offset: 2, vv: vv(1, "1")})
	_, err := h.reassemble()
	if err == nil {
		t.Errorf("reassemble() did not fail when there was a hole in the packet")
	}
}