ping_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package ping
  4. import (
  5. "context"
  6. "errors"
  7. "fmt"
  8. "net"
  9. "testing"
  10. "time"
  11. "golang.org/x/net/icmp"
  12. "golang.org/x/net/ipv4"
  13. "golang.org/x/net/ipv6"
  14. "tailscale.com/tstest"
  15. "tailscale.com/util/mak"
  16. )
  17. var (
  18. localhost = &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}
  19. )
  20. func TestPinger(t *testing.T) {
  21. clock := &tstest.Clock{}
  22. ctx := context.Background()
  23. ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
  24. defer cancel()
  25. p, closeP := mockPinger(t, clock)
  26. defer closeP()
  27. bodyData := []byte("data goes here")
  28. // Start a ping in the background
  29. r := make(chan time.Duration, 1)
  30. go func() {
  31. dur, err := p.Send(ctx, localhost, bodyData)
  32. if err != nil {
  33. t.Errorf("p.Send: %v", err)
  34. r <- 0
  35. } else {
  36. r <- dur
  37. }
  38. }()
  39. p.waitOutstanding(t, ctx, 1)
  40. // Fake a response from ourself
  41. fakeResponse := mustMarshal(t, &icmp.Message{
  42. Type: ipv4.ICMPTypeEchoReply,
  43. Code: ipv4.ICMPTypeEchoReply.Protocol(),
  44. Body: &icmp.Echo{
  45. ID: 1234,
  46. Seq: 1,
  47. Data: bodyData,
  48. },
  49. })
  50. const fakeDuration = 100 * time.Millisecond
  51. p.handleResponse(fakeResponse, clock.Now().Add(fakeDuration), v4Type)
  52. select {
  53. case dur := <-r:
  54. want := fakeDuration
  55. if dur != want {
  56. t.Errorf("wanted ping response time = %d; got %d", want, dur)
  57. }
  58. case <-ctx.Done():
  59. t.Fatal("did not get response by timeout")
  60. }
  61. }
  62. func TestV6Pinger(t *testing.T) {
  63. if c, err := net.ListenPacket("udp6", "::1"); err != nil {
  64. // skip test if we can't use IPv6.
  65. t.Skipf("IPv6 not supported: %s", err)
  66. } else {
  67. c.Close()
  68. }
  69. clock := &tstest.Clock{}
  70. ctx := context.Background()
  71. ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
  72. defer cancel()
  73. p, closeP := mockPinger(t, clock)
  74. defer closeP()
  75. bodyData := []byte("data goes here")
  76. // Start a ping in the background
  77. r := make(chan time.Duration, 1)
  78. go func() {
  79. dur, err := p.Send(ctx, &net.IPAddr{IP: net.ParseIP("::")}, bodyData)
  80. if err != nil {
  81. t.Errorf("p.Send: %v", err)
  82. r <- 0
  83. } else {
  84. r <- dur
  85. }
  86. }()
  87. p.waitOutstanding(t, ctx, 1)
  88. // Fake a response from ourself
  89. fakeResponse := mustMarshal(t, &icmp.Message{
  90. Type: ipv6.ICMPTypeEchoReply,
  91. Code: ipv6.ICMPTypeEchoReply.Protocol(),
  92. Body: &icmp.Echo{
  93. ID: 1234,
  94. Seq: 1,
  95. Data: bodyData,
  96. },
  97. })
  98. const fakeDuration = 100 * time.Millisecond
  99. p.handleResponse(fakeResponse, clock.Now().Add(fakeDuration), v6Type)
  100. select {
  101. case dur := <-r:
  102. want := fakeDuration
  103. if dur != want {
  104. t.Errorf("wanted ping response time = %d; got %d", want, dur)
  105. }
  106. case <-ctx.Done():
  107. t.Fatal("did not get response by timeout")
  108. }
  109. }
  110. func TestPingerTimeout(t *testing.T) {
  111. ctx := context.Background()
  112. ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
  113. defer cancel()
  114. clock := &tstest.Clock{}
  115. p, closeP := mockPinger(t, clock)
  116. defer closeP()
  117. // Send a ping in the background
  118. r := make(chan error, 1)
  119. go func() {
  120. _, err := p.Send(ctx, localhost, []byte("data goes here"))
  121. r <- err
  122. }()
  123. // Wait until we're blocking
  124. p.waitOutstanding(t, ctx, 1)
  125. // Close everything down
  126. p.cleanupOutstanding()
  127. // Should have got an error from the ping
  128. err := <-r
  129. if !errors.Is(err, net.ErrClosed) {
  130. t.Errorf("wanted errors.Is(err, net.ErrClosed); got=%v", err)
  131. }
  132. }
  133. func TestPingerMismatch(t *testing.T) {
  134. clock := &tstest.Clock{}
  135. ctx := context.Background()
  136. ctx, cancel := context.WithTimeout(ctx, 1*time.Second) // intentionally short
  137. defer cancel()
  138. p, closeP := mockPinger(t, clock)
  139. defer closeP()
  140. bodyData := []byte("data goes here")
  141. // Start a ping in the background
  142. r := make(chan time.Duration, 1)
  143. go func() {
  144. dur, err := p.Send(ctx, localhost, bodyData)
  145. if err != nil && !errors.Is(err, context.DeadlineExceeded) {
  146. t.Errorf("p.Send: %v", err)
  147. r <- 0
  148. } else {
  149. r <- dur
  150. }
  151. }()
  152. p.waitOutstanding(t, ctx, 1)
  153. // "Receive" a bunch of intentionally malformed packets that should not
  154. // result in the Send call above returning
  155. badPackets := []struct {
  156. name string
  157. pkt *icmp.Message
  158. }{
  159. {
  160. name: "wrong type",
  161. pkt: &icmp.Message{
  162. Type: ipv4.ICMPTypeDestinationUnreachable,
  163. Code: 0,
  164. Body: &icmp.DstUnreach{},
  165. },
  166. },
  167. {
  168. name: "wrong id",
  169. pkt: &icmp.Message{
  170. Type: ipv4.ICMPTypeEchoReply,
  171. Code: 0,
  172. Body: &icmp.Echo{
  173. ID: 9999,
  174. Seq: 1,
  175. Data: bodyData,
  176. },
  177. },
  178. },
  179. {
  180. name: "wrong seq",
  181. pkt: &icmp.Message{
  182. Type: ipv4.ICMPTypeEchoReply,
  183. Code: 0,
  184. Body: &icmp.Echo{
  185. ID: 1234,
  186. Seq: 5,
  187. Data: bodyData,
  188. },
  189. },
  190. },
  191. {
  192. name: "bad body",
  193. pkt: &icmp.Message{
  194. Type: ipv4.ICMPTypeEchoReply,
  195. Code: 0,
  196. Body: &icmp.Echo{
  197. ID: 1234,
  198. Seq: 1,
  199. // Intentionally missing first byte
  200. Data: bodyData[1:],
  201. },
  202. },
  203. },
  204. }
  205. const fakeDuration = 100 * time.Millisecond
  206. tm := clock.Now().Add(fakeDuration)
  207. for _, tt := range badPackets {
  208. fakeResponse := mustMarshal(t, tt.pkt)
  209. p.handleResponse(fakeResponse, tm, v4Type)
  210. }
  211. // Also "receive" a packet that does not unmarshal as an ICMP packet
  212. p.handleResponse([]byte("foo"), tm, v4Type)
  213. select {
  214. case <-r:
  215. t.Fatal("wanted timeout")
  216. case <-ctx.Done():
  217. t.Logf("test correctly timed out")
  218. }
  219. }
  220. // udpingPacketConn will convert potentially ICMP destination addrs to UDP
  221. // destination addrs in WriteTo so that a test that is intending to send ICMP
  222. // traffic will instead send UDP traffic, without the higher level Pinger being
  223. // aware of this difference.
  224. type udpingPacketConn struct {
  225. net.PacketConn
  226. // destPort will be configured by the test to be the peer expected to respond to a ping.
  227. destPort uint16
  228. }
  229. func (u *udpingPacketConn) WriteTo(body []byte, dest net.Addr) (int, error) {
  230. switch d := dest.(type) {
  231. case *net.IPAddr:
  232. udpAddr := &net.UDPAddr{
  233. IP: d.IP,
  234. Port: int(u.destPort),
  235. Zone: d.Zone,
  236. }
  237. return u.PacketConn.WriteTo(body, udpAddr)
  238. }
  239. return 0, fmt.Errorf("unimplemented udpingPacketConn for %T", dest)
  240. }
  241. func mockPinger(t *testing.T, clock *tstest.Clock) (*Pinger, func()) {
  242. p := New(context.Background(), t.Logf, nil)
  243. p.timeNow = clock.Now
  244. p.Verbose = true
  245. p.id = 1234
  246. // In tests, we use UDP so that we can test without being root; this
  247. // doesn't matter because we mock out the ICMP reply below to be a real
  248. // ICMP echo reply packet.
  249. conn4, err := net.ListenPacket("udp4", "127.0.0.1:0")
  250. if err != nil {
  251. t.Fatalf("net.ListenPacket: %v", err)
  252. }
  253. conn6, err := net.ListenPacket("udp6", "[::]:0")
  254. if err != nil {
  255. t.Fatalf("net.ListenPacket: %v", err)
  256. }
  257. conn4 = &udpingPacketConn{
  258. destPort: 12345,
  259. PacketConn: conn4,
  260. }
  261. conn6 = &udpingPacketConn{
  262. PacketConn: conn6,
  263. destPort: 12345,
  264. }
  265. mak.Set(&p.conns, v4Type, conn4)
  266. mak.Set(&p.conns, v6Type, conn6)
  267. done := func() {
  268. if err := p.Close(); err != nil {
  269. t.Errorf("error on close: %v", err)
  270. }
  271. }
  272. return p, done
  273. }
  274. func mustMarshal(t *testing.T, m *icmp.Message) []byte {
  275. t.Helper()
  276. b, err := m.Marshal(nil)
  277. if err != nil {
  278. t.Fatal(err)
  279. }
  280. return b
  281. }
  282. func (p *Pinger) waitOutstanding(t *testing.T, ctx context.Context, count int) {
  283. // This is a bit janky, but... we busy-loop to wait for the Send call
  284. // to write to our map so we know that a response will be handled.
  285. var haveMapEntry bool
  286. for !haveMapEntry {
  287. time.Sleep(10 * time.Millisecond)
  288. select {
  289. case <-ctx.Done():
  290. t.Error("no entry in ping map before timeout")
  291. return
  292. default:
  293. }
  294. p.mu.Lock()
  295. haveMapEntry = len(p.pings) == count
  296. p.mu.Unlock()
  297. }
  298. }