Debian Codegraph @

replayprotection_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
2 // SPDX-License-Identifier: MIT
3
4 package dtls
5
6 import (
7 "context"
8 "net"
9 "sync"
10 "sync/atomic"
11 "testing"
12 "time"
13
14 "github.com/pion/transport/v4/dpipe"
15 "github.com/pion/transport/v4/test"
16 "github.com/stretchr/testify/assert"
17 )
18
19 func TestReplayProtection(t *testing.T) { //nolint:cyclop
20 // Limit runtime in case of deadlocks
21 lim := test.TimeOut(5 * time.Second)
22 defer lim.Stop()
23
24 // Check for leaking routines
25 report := test.CheckRoutines(t)
26 defer report()
27
28 c0, c1 := dpipe.Pipe()
29 c2, c3 := dpipe.Pipe()
30 conn := []net.Conn{c0, c1, c2, c3}
31
32 var wgRoutines sync.WaitGroup
33 var cntReplays int32 = 1
34
35 ctxReplayDone, replayDone := context.WithCancel(context.Background())
36
37 replaySendDone := func() {
38 cnt := atomic.AddInt32(&cntReplays, -1)
39 if cnt == 0 {
40 replayDone()
41 }
42 }
43
44 replayer := func(ca, cb net.Conn) {
45 defer wgRoutines.Done()
46 // Man in the middle
47 for {
48 b := make([]byte, 2048)
49 n, rerr := ca.Read(b)
50 if rerr != nil {
51 return
52 }
53 _, werr := cb.Write(b[:n])
54 assert.NoError(t, werr)
55
56 atomic.AddInt32(&cntReplays, 1)
57 go func() {
58 defer replaySendDone()
59 // Replay bit later
60 time.Sleep(time.Millisecond)
61 _, werr := cb.Write(b[:n])
62 assert.NoError(t, werr)
63 }()
64 }
65 }
66 wgRoutines.Add(2)
67 go replayer(conn[1], conn[2])
68 go replayer(conn[2], conn[1])
69
70 ca, cb, err := pipeConn(conn[0], conn[3])
71 assert.NoError(t, err)
72
73 const numMsgs = 10
74
75 var received [2][][]byte
76 for i, c := range []net.Conn{ca, cb} {
77 i := i
78 c := c
79 wgRoutines.Add(1)
80 atomic.AddInt32(&cntReplays, 1) // Keep locked until the final message
81 var lastMsgDone sync.Once
82 go func() {
83 defer wgRoutines.Done()
84 for {
85 b := make([]byte, 2048)
86 n, rerr := c.Read(b)
87 if rerr != nil {
88 return
89 }
90 received[i] = append(received[i], b[:n])
91 if b[0] == numMsgs-1 {
92 // Final message received
93 lastMsgDone.Do(func() {
94 defer replaySendDone()
95 })
96 }
97 }
98 }()
99 }
100
101 var sent [][]byte
102 for i := 0; i < numMsgs; i++ {
103 data := []byte{byte(i)}
104 sent = append(sent, data)
105 _, werr := ca.Write(data)
106 assert.NoError(t, werr)
107 _, werr = cb.Write(data)
108 assert.NoError(t, werr)
109 }
110
111 replaySendDone()
112 <-ctxReplayDone.Done()
113 time.Sleep(10 * time.Millisecond) // Ensure all replayed packets are sent
114
115 for i := 0; i < 4; i++ {
116 assert.NoError(t, conn[i].Close())
117 }
118 assert.NoError(t, ca.Close())
119 assert.NoError(t, cb.Close())
120 wgRoutines.Wait()
121
122 for _, r := range received {
123 assert.Equal(t, sent, r)
124 }
125 }