userspace_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package wgengine
  5. import (
  6. "fmt"
  7. "reflect"
  8. "testing"
  9. "go4.org/mem"
  10. "inet.af/netaddr"
  11. "tailscale.com/net/dns"
  12. "tailscale.com/net/tstun"
  13. "tailscale.com/tailcfg"
  14. "tailscale.com/tstest"
  15. "tailscale.com/tstime/mono"
  16. "tailscale.com/types/key"
  17. "tailscale.com/types/netmap"
  18. "tailscale.com/wgengine/router"
  19. "tailscale.com/wgengine/wgcfg"
  20. )
  21. func TestNoteReceiveActivity(t *testing.T) {
  22. now := mono.Time(123456)
  23. var logBuf tstest.MemLogger
  24. confc := make(chan bool, 1)
  25. gotConf := func() bool {
  26. select {
  27. case <-confc:
  28. return true
  29. default:
  30. return false
  31. }
  32. }
  33. e := &userspaceEngine{
  34. timeNow: func() mono.Time { return now },
  35. recvActivityAt: map[key.NodePublic]mono.Time{},
  36. logf: logBuf.Logf,
  37. tundev: new(tstun.Wrapper),
  38. testMaybeReconfigHook: func() { confc <- true },
  39. trimmedNodes: map[key.NodePublic]bool{},
  40. }
  41. ra := e.recvActivityAt
  42. nk := key.NewNode().Public()
  43. // Activity on an untracked key should do nothing.
  44. e.noteRecvActivity(nk)
  45. if len(ra) != 0 {
  46. t.Fatalf("unexpected growth in map: now has %d keys; want 0", len(ra))
  47. }
  48. if logBuf.Len() != 0 {
  49. t.Fatalf("unexpected log write (and thus activity): %s", logBuf.Bytes())
  50. }
  51. // Now track it, but don't mark it trimmed, so shouldn't update.
  52. ra[nk] = 0
  53. e.noteRecvActivity(nk)
  54. if len(ra) != 1 {
  55. t.Fatalf("unexpected growth in map: now has %d keys; want 1", len(ra))
  56. }
  57. if got := ra[nk]; got != now {
  58. t.Fatalf("time in map = %v; want %v", got, now)
  59. }
  60. if gotConf() {
  61. t.Fatalf("unexpected reconfig")
  62. }
  63. // Now mark it trimmed and expect an update.
  64. e.trimmedNodes[nk] = true
  65. e.noteRecvActivity(nk)
  66. if len(ra) != 1 {
  67. t.Fatalf("unexpected growth in map: now has %d keys; want 1", len(ra))
  68. }
  69. if got := ra[nk]; got != now {
  70. t.Fatalf("time in map = %v; want %v", got, now)
  71. }
  72. if !gotConf() {
  73. t.Fatalf("didn't get expected reconfig")
  74. }
  75. }
  76. func TestUserspaceEngineReconfig(t *testing.T) {
  77. e, err := NewFakeUserspaceEngine(t.Logf, 0)
  78. if err != nil {
  79. t.Fatal(err)
  80. }
  81. t.Cleanup(e.Close)
  82. ue := e.(*userspaceEngine)
  83. routerCfg := &router.Config{}
  84. for _, nodeHex := range []string{
  85. "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  86. "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
  87. } {
  88. nm := &netmap.NetworkMap{
  89. Peers: []*tailcfg.Node{
  90. {
  91. Key: nkFromHex(nodeHex),
  92. },
  93. },
  94. }
  95. nk, err := key.ParseNodePublicUntyped(mem.S(nodeHex))
  96. if err != nil {
  97. t.Fatal(err)
  98. }
  99. cfg := &wgcfg.Config{
  100. Peers: []wgcfg.Peer{
  101. {
  102. PublicKey: nk,
  103. AllowedIPs: []netaddr.IPPrefix{
  104. netaddr.IPPrefixFrom(netaddr.IPv4(100, 100, 99, 1), 32),
  105. },
  106. },
  107. },
  108. }
  109. e.SetNetworkMap(nm)
  110. err = e.Reconfig(cfg, routerCfg, &dns.Config{}, nil)
  111. if err != nil {
  112. t.Fatal(err)
  113. }
  114. wantRecvAt := map[key.NodePublic]mono.Time{
  115. nkFromHex(nodeHex): 0,
  116. }
  117. if got := ue.recvActivityAt; !reflect.DeepEqual(got, wantRecvAt) {
  118. t.Errorf("wrong recvActivityAt\n got: %v\nwant: %v\n", got, wantRecvAt)
  119. }
  120. wantTrimmedNodes := map[key.NodePublic]bool{
  121. nkFromHex(nodeHex): true,
  122. }
  123. if got := ue.trimmedNodes; !reflect.DeepEqual(got, wantTrimmedNodes) {
  124. t.Errorf("wrong wantTrimmedNodes\n got: %v\nwant: %v\n", got, wantTrimmedNodes)
  125. }
  126. }
  127. }
  128. func TestUserspaceEnginePortReconfig(t *testing.T) {
  129. const defaultPort = 49983
  130. // Keep making a wgengine until we find an unused port
  131. var ue *userspaceEngine
  132. for i := 0; i < 100; i++ {
  133. attempt := uint16(defaultPort + i)
  134. e, err := NewFakeUserspaceEngine(t.Logf, attempt)
  135. if err != nil {
  136. t.Fatal(err)
  137. }
  138. ue = e.(*userspaceEngine)
  139. if ue.magicConn.LocalPort() == attempt {
  140. break
  141. }
  142. ue.Close()
  143. ue = nil
  144. }
  145. if ue == nil {
  146. t.Fatal("could not create a wgengine with a specific port")
  147. }
  148. t.Cleanup(ue.Close)
  149. startingPort := ue.magicConn.LocalPort()
  150. nodeKey, err := key.ParseNodePublicUntyped(mem.S("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))
  151. if err != nil {
  152. t.Fatal(err)
  153. }
  154. cfg := &wgcfg.Config{
  155. Peers: []wgcfg.Peer{
  156. {
  157. PublicKey: nodeKey,
  158. AllowedIPs: []netaddr.IPPrefix{
  159. netaddr.IPPrefixFrom(netaddr.IPv4(100, 100, 99, 1), 32),
  160. },
  161. },
  162. },
  163. }
  164. routerCfg := &router.Config{}
  165. if err := ue.Reconfig(cfg, routerCfg, &dns.Config{}, nil); err != nil {
  166. t.Fatal(err)
  167. }
  168. if got := ue.magicConn.LocalPort(); got != startingPort {
  169. t.Errorf("no debug setting changed local port to %d from %d", got, startingPort)
  170. }
  171. if err := ue.Reconfig(cfg, routerCfg, &dns.Config{}, &tailcfg.Debug{RandomizeClientPort: true}); err != nil {
  172. t.Fatal(err)
  173. }
  174. if got := ue.magicConn.LocalPort(); got == startingPort {
  175. t.Errorf("debug setting did not change local port from %d", startingPort)
  176. }
  177. lastPort := ue.magicConn.LocalPort()
  178. if err := ue.Reconfig(cfg, routerCfg, &dns.Config{}, nil); err != nil {
  179. t.Fatal(err)
  180. }
  181. if startingPort == defaultPort {
  182. // Only try this if we managed to bind defaultPort the first time.
  183. // Otherwise, assume someone else on the computer is using defaultPort
  184. // and so Reconfig would have caused magicSockt to bind some other port.
  185. if got := ue.magicConn.LocalPort(); got != defaultPort {
  186. t.Errorf("debug setting did not change local port from %d to %d", startingPort, defaultPort)
  187. }
  188. }
  189. if got := ue.magicConn.LocalPort(); got == lastPort {
  190. t.Errorf("Reconfig did not change local port from %d", lastPort)
  191. }
  192. }
  193. func nkFromHex(hex string) key.NodePublic {
  194. if len(hex) != 64 {
  195. panic(fmt.Sprintf("%q is len %d; want 64", hex, len(hex)))
  196. }
  197. k, err := key.ParseNodePublicUntyped(mem.S(hex[:64]))
  198. if err != nil {
  199. panic(fmt.Sprintf("%q is not hex: %v", hex, err))
  200. }
  201. return k
  202. }
  203. // an experiment to see if genLocalAddrFunc was worth it. As of Go
  204. // 1.16, it still very much is. (30-40x faster)
  205. func BenchmarkGenLocalAddrFunc(b *testing.B) {
  206. la1 := netaddr.MustParseIP("1.2.3.4")
  207. la2 := netaddr.MustParseIP("::4")
  208. lanot := netaddr.MustParseIP("5.5.5.5")
  209. var x bool
  210. b.Run("map1", func(b *testing.B) {
  211. b.ReportAllocs()
  212. b.ResetTimer()
  213. m := map[netaddr.IP]bool{
  214. la1: true,
  215. }
  216. for i := 0; i < b.N; i++ {
  217. x = m[la1]
  218. x = m[lanot]
  219. }
  220. })
  221. b.Run("map2", func(b *testing.B) {
  222. b.ReportAllocs()
  223. b.ResetTimer()
  224. m := map[netaddr.IP]bool{
  225. la1: true,
  226. la2: true,
  227. }
  228. for i := 0; i < b.N; i++ {
  229. x = m[la1]
  230. x = m[lanot]
  231. }
  232. })
  233. b.Run("or1", func(b *testing.B) {
  234. b.ReportAllocs()
  235. b.ResetTimer()
  236. f := func(t netaddr.IP) bool {
  237. return t == la1
  238. }
  239. for i := 0; i < b.N; i++ {
  240. x = f(la1)
  241. x = f(lanot)
  242. }
  243. })
  244. b.Run("or2", func(b *testing.B) {
  245. b.ReportAllocs()
  246. b.ResetTimer()
  247. f := func(t netaddr.IP) bool {
  248. return t == la1 || t == la2
  249. }
  250. for i := 0; i < b.N; i++ {
  251. x = f(la1)
  252. x = f(lanot)
  253. }
  254. })
  255. b.Logf("x = %v", x)
  256. }