connections_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package connections
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "errors"
  11. "fmt"
  12. "math/rand"
  13. "net"
  14. "net/url"
  15. "strings"
  16. "testing"
  17. "time"
  18. "github.com/thejerf/suture/v4"
  19. "github.com/syncthing/syncthing/lib/config"
  20. "github.com/syncthing/syncthing/lib/events"
  21. "github.com/syncthing/syncthing/lib/nat"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. "github.com/syncthing/syncthing/lib/sync"
  24. "github.com/syncthing/syncthing/lib/tlsutil"
  25. )
  26. func TestFixupPort(t *testing.T) {
  27. cases := [][2]string{
  28. {"tcp://1.2.3.4:5", "tcp://1.2.3.4:5"},
  29. {"tcp://1.2.3.4:", "tcp://1.2.3.4:22000"},
  30. {"tcp://1.2.3.4", "tcp://1.2.3.4:22000"},
  31. {"tcp://[fe80::1]", "tcp://[fe80::1]:22000"},
  32. {"tcp://[fe80::1]:", "tcp://[fe80::1]:22000"},
  33. {"tcp://[fe80::1]:22000", "tcp://[fe80::1]:22000"},
  34. {"tcp://[fe80::1]:22000", "tcp://[fe80::1]:22000"},
  35. {"tcp://[fe80::1%25abc]", "tcp://[fe80::1%25abc]:22000"},
  36. {"tcp://[fe80::1%25abc]:", "tcp://[fe80::1%25abc]:22000"},
  37. {"tcp://[fe80::1%25abc]:22000", "tcp://[fe80::1%25abc]:22000"},
  38. {"tcp://[fe80::1%25abc]:22000", "tcp://[fe80::1%25abc]:22000"},
  39. }
  40. for _, tc := range cases {
  41. u0, err := url.Parse(tc[0])
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. u1 := fixupPort(u0, 22000).String()
  46. if u1 != tc[1] {
  47. t.Errorf("fixupPort(%q, 22000) => %q, expected %q", tc[0], u1, tc[1])
  48. }
  49. }
  50. }
  51. func TestAllowedNetworks(t *testing.T) {
  52. cases := []struct {
  53. host string
  54. allowed []string
  55. ok bool
  56. }{
  57. {
  58. "192.168.0.1",
  59. nil,
  60. false,
  61. },
  62. {
  63. "192.168.0.1",
  64. []string{},
  65. false,
  66. },
  67. {
  68. "fe80::1",
  69. nil,
  70. false,
  71. },
  72. {
  73. "fe80::1",
  74. []string{},
  75. false,
  76. },
  77. {
  78. "192.168.0.1",
  79. []string{"fe80::/48", "192.168.0.0/24"},
  80. true,
  81. },
  82. {
  83. "fe80::1",
  84. []string{"192.168.0.0/24", "fe80::/48"},
  85. true,
  86. },
  87. {
  88. "192.168.0.1",
  89. []string{"192.168.1.0/24", "fe80::/48"},
  90. false,
  91. },
  92. {
  93. "fe80::1",
  94. []string{"fe82::/48", "192.168.1.0/24"},
  95. false,
  96. },
  97. {
  98. "192.168.0.1:4242",
  99. []string{"fe80::/48", "192.168.0.0/24"},
  100. true,
  101. },
  102. {
  103. "[fe80::1]:4242",
  104. []string{"192.168.0.0/24", "fe80::/48"},
  105. true,
  106. },
  107. {
  108. "10.20.30.40",
  109. []string{"!10.20.30.0/24", "10.0.0.0/8"},
  110. false,
  111. },
  112. {
  113. "10.20.30.40",
  114. []string{"10.0.0.0/8", "!10.20.30.0/24"},
  115. true,
  116. },
  117. {
  118. "[fe80::1]:4242",
  119. []string{"192.168.0.0/24", "!fe00::/8", "fe80::/48"},
  120. false,
  121. },
  122. }
  123. for _, tc := range cases {
  124. res := IsAllowedNetwork(tc.host, tc.allowed)
  125. if res != tc.ok {
  126. t.Errorf("allowedNetwork(%q, %q) == %v, want %v", tc.host, tc.allowed, res, tc.ok)
  127. }
  128. }
  129. }
  130. func TestGetDialer(t *testing.T) {
  131. mustParseURI := func(v string) *url.URL {
  132. uri, err := url.Parse(v)
  133. if err != nil {
  134. panic(err)
  135. }
  136. return uri
  137. }
  138. cases := []struct {
  139. uri *url.URL
  140. ok bool
  141. disabled bool
  142. deprecated bool
  143. }{
  144. {mustParseURI("tcp://1.2.3.4:5678"), true, false, false}, // ok
  145. {mustParseURI("tcp4://1.2.3.4:5678"), true, false, false}, // ok
  146. {mustParseURI("kcp://1.2.3.4:5678"), false, false, true}, // deprecated
  147. {mustParseURI("relay://1.2.3.4:5678"), false, true, false}, // disabled
  148. {mustParseURI("http://1.2.3.4:5678"), false, false, false}, // generally bad
  149. {mustParseURI("bananas!"), false, false, false}, // wat
  150. }
  151. cfg := config.New(protocol.LocalDeviceID)
  152. cfg.Options.RelaysEnabled = false
  153. for _, tc := range cases {
  154. df, err := getDialerFactory(cfg, tc.uri)
  155. if tc.ok && err != nil {
  156. t.Errorf("getDialerFactory(%q) => %v, expected nil err", tc.uri, err)
  157. }
  158. if tc.ok && df == nil {
  159. t.Errorf("getDialerFactory(%q) => nil factory, expected non-nil", tc.uri)
  160. }
  161. if tc.deprecated && err != errDeprecated {
  162. t.Errorf("getDialerFactory(%q) => %v, expected %v", tc.uri, err, errDeprecated)
  163. }
  164. if tc.disabled && err != errDisabled {
  165. t.Errorf("getDialerFactory(%q) => %v, expected %v", tc.uri, err, errDisabled)
  166. }
  167. lf, err := getListenerFactory(cfg, tc.uri)
  168. if tc.ok && err != nil {
  169. t.Errorf("getListenerFactory(%q) => %v, expected nil err", tc.uri, err)
  170. }
  171. if tc.ok && lf == nil {
  172. t.Errorf("getListenerFactory(%q) => nil factory, expected non-nil", tc.uri)
  173. }
  174. if tc.deprecated && err != errDeprecated {
  175. t.Errorf("getListenerFactory(%q) => %v, expected %v", tc.uri, err, errDeprecated)
  176. }
  177. if tc.disabled && err != errDisabled {
  178. t.Errorf("getListenerFactory(%q) => %v, expected %v", tc.uri, err, errDisabled)
  179. }
  180. }
  181. }
  182. func TestConnectionStatus(t *testing.T) {
  183. s := newConnectionStatusHandler()
  184. addr := "testAddr"
  185. testErr := errors.New("testErr")
  186. if stats := s.ConnectionStatus(); len(stats) != 0 {
  187. t.Fatal("newly created connectionStatusHandler isn't empty:", len(stats))
  188. }
  189. check := func(in, out error) {
  190. t.Helper()
  191. s.setConnectionStatus(addr, in)
  192. switch stat, ok := s.ConnectionStatus()[addr]; {
  193. case !ok:
  194. t.Fatal("entry missing")
  195. case out == nil:
  196. if stat.Error != nil {
  197. t.Fatal("expected nil error, got", stat.Error)
  198. }
  199. case *stat.Error != out.Error():
  200. t.Fatalf("expected %v error, got %v", out.Error(), *stat.Error)
  201. }
  202. }
  203. check(nil, nil)
  204. check(context.Canceled, nil)
  205. check(testErr, testErr)
  206. check(context.Canceled, testErr)
  207. check(nil, nil)
  208. }
  209. func TestNextDialRegistryCleanup(t *testing.T) {
  210. now := time.Now()
  211. firsts := []time.Time{
  212. now.Add(-dialCoolDownInterval + time.Second),
  213. now.Add(-dialCoolDownDelay + time.Second),
  214. now.Add(-2 * dialCoolDownDelay),
  215. }
  216. r := make(nextDialRegistry)
  217. // Cases where the device should be cleaned up
  218. r[protocol.LocalDeviceID] = nextDialDevice{}
  219. r.sleepDurationAndCleanup(now)
  220. if l := len(r); l > 0 {
  221. t.Errorf("Expected empty to be cleaned up, got length %v", l)
  222. }
  223. for _, dev := range []nextDialDevice{
  224. // attempts below threshold, outside of interval
  225. {
  226. attempts: 1,
  227. coolDownIntervalStart: firsts[1],
  228. },
  229. {
  230. attempts: 1,
  231. coolDownIntervalStart: firsts[2],
  232. },
  233. // Threshold reached, but outside of cooldown delay
  234. {
  235. attempts: dialCoolDownMaxAttemps,
  236. coolDownIntervalStart: firsts[2],
  237. },
  238. } {
  239. r[protocol.LocalDeviceID] = dev
  240. r.sleepDurationAndCleanup(now)
  241. if l := len(r); l > 0 {
  242. t.Errorf("attempts: %v, start: %v: Expected all cleaned up, got length %v", dev.attempts, dev.coolDownIntervalStart, l)
  243. }
  244. }
  245. // Cases where the device should stay monitored
  246. for _, dev := range []nextDialDevice{
  247. // attempts below threshold, inside of interval
  248. {
  249. attempts: 1,
  250. coolDownIntervalStart: firsts[0],
  251. },
  252. // attempts at threshold, inside delay
  253. {
  254. attempts: dialCoolDownMaxAttemps,
  255. coolDownIntervalStart: firsts[0],
  256. },
  257. {
  258. attempts: dialCoolDownMaxAttemps,
  259. coolDownIntervalStart: firsts[1],
  260. },
  261. } {
  262. r[protocol.LocalDeviceID] = dev
  263. r.sleepDurationAndCleanup(now)
  264. if l := len(r); l != 1 {
  265. t.Errorf("attempts: %v, start: %v: Expected device still tracked, got length %v", dev.attempts, dev.coolDownIntervalStart, l)
  266. }
  267. }
  268. }
  269. func BenchmarkConnections(pb *testing.B) {
  270. addrs := []string{
  271. "tcp://127.0.0.1:0",
  272. "quic://127.0.0.1:0",
  273. "relay://127.0.0.1:22067",
  274. }
  275. sizes := []int{
  276. 1 << 10,
  277. 1 << 15,
  278. 1 << 20,
  279. 1 << 22,
  280. }
  281. haveRelay := false
  282. // Check if we have a relay running locally
  283. conn, err := net.DialTimeout("tcp", "127.0.0.1:22067", 100*time.Millisecond)
  284. if err == nil {
  285. haveRelay = true
  286. _ = conn.Close()
  287. }
  288. for _, addr := range addrs {
  289. for _, sz := range sizes {
  290. for _, direction := range []string{"cs", "sc"} {
  291. proto := strings.SplitN(addr, ":", 2)[0]
  292. pb.Run(fmt.Sprintf("%s_%d_%s", proto, sz, direction), func(b *testing.B) {
  293. if proto == "relay" && !haveRelay {
  294. b.Skip("could not connect to relay")
  295. }
  296. withConnectionPair(b, addr, func(client, server internalConn) {
  297. if direction == "sc" {
  298. server, client = client, server
  299. }
  300. data := make([]byte, sz)
  301. if _, err := rand.Read(data); err != nil {
  302. b.Fatal(err)
  303. }
  304. total := 0
  305. wg := sync.NewWaitGroup()
  306. b.ResetTimer()
  307. for i := 0; i < b.N; i++ {
  308. wg.Add(2)
  309. go func() {
  310. if err := sendMsg(client, data); err != nil {
  311. b.Fatal(err)
  312. }
  313. wg.Done()
  314. }()
  315. go func() {
  316. if err := recvMsg(server, data); err != nil {
  317. b.Fatal(err)
  318. }
  319. total += sz
  320. wg.Done()
  321. }()
  322. wg.Wait()
  323. }
  324. b.ReportAllocs()
  325. b.SetBytes(int64(total / b.N))
  326. })
  327. })
  328. }
  329. }
  330. }
  331. }
  332. func sendMsg(c internalConn, buf []byte) error {
  333. n, err := c.Write(buf)
  334. if n != len(buf) || err != nil {
  335. return err
  336. }
  337. return nil
  338. }
  339. func recvMsg(c internalConn, buf []byte) error {
  340. for read := 0; read != len(buf); {
  341. n, err := c.Read(buf)
  342. read += n
  343. if err != nil {
  344. return err
  345. }
  346. }
  347. return nil
  348. }
  349. func withConnectionPair(b *testing.B, connUri string, h func(client, server internalConn)) {
  350. // Root of the service tree.
  351. supervisor := suture.New("main", suture.Spec{
  352. PassThroughPanics: true,
  353. })
  354. cert := mustGetCert(b)
  355. deviceId := protocol.NewDeviceID(cert.Certificate[0])
  356. tlsCfg := tlsutil.SecureDefaultTLS13()
  357. tlsCfg.Certificates = []tls.Certificate{cert}
  358. tlsCfg.NextProtos = []string{"bench"}
  359. tlsCfg.ClientAuth = tls.RequestClientCert
  360. tlsCfg.SessionTicketsDisabled = true
  361. tlsCfg.InsecureSkipVerify = true
  362. ctx, cancel := context.WithCancel(context.Background())
  363. defer cancel()
  364. supervisor.ServeBackground(ctx)
  365. cfg := config.Configuration{
  366. Options: config.OptionsConfiguration{
  367. RelaysEnabled: true,
  368. },
  369. }
  370. wcfg := config.Wrap("", cfg, deviceId, events.NoopLogger)
  371. uri, err := url.Parse(connUri)
  372. if err != nil {
  373. b.Fatal(err)
  374. }
  375. lf, err := getListenerFactory(cfg, uri)
  376. if err != nil {
  377. b.Fatal(err)
  378. }
  379. natSvc := nat.NewService(deviceId, wcfg)
  380. conns := make(chan internalConn, 1)
  381. listenSvc := lf.New(uri, wcfg, tlsCfg, conns, natSvc)
  382. supervisor.Add(listenSvc)
  383. var addr *url.URL
  384. for {
  385. addrs := listenSvc.LANAddresses()
  386. if len(addrs) > 0 {
  387. if !strings.HasSuffix(addrs[0].Host, ":0") {
  388. addr = addrs[0]
  389. break
  390. }
  391. }
  392. time.Sleep(time.Millisecond)
  393. }
  394. df, err := getDialerFactory(cfg, addr)
  395. if err != nil {
  396. b.Fatal(err)
  397. }
  398. dialer := df.New(cfg.Options, tlsCfg)
  399. // Relays might take some time to register the device, so dial multiple times
  400. clientConn, err := dialer.Dial(ctx, deviceId, addr)
  401. if err != nil {
  402. for i := 0; i < 10 && err != nil; i++ {
  403. clientConn, err = dialer.Dial(ctx, deviceId, addr)
  404. time.Sleep(100 * time.Millisecond)
  405. }
  406. if err != nil {
  407. b.Fatal(err)
  408. }
  409. }
  410. data := []byte("hello")
  411. // Quic does not start a stream until some data is sent through, so send something for the AcceptStream
  412. // to fire on the other side.
  413. if err := sendMsg(clientConn, data); err != nil {
  414. b.Fatal(err)
  415. }
  416. serverConn := <-conns
  417. if err := recvMsg(serverConn, data); err != nil {
  418. b.Fatal(err)
  419. }
  420. h(clientConn, serverConn)
  421. _ = clientConn.Close()
  422. _ = serverConn.Close()
  423. }
  424. func mustGetCert(b *testing.B) tls.Certificate {
  425. cert, err := tlsutil.NewCertificateInMemory("bench", 10)
  426. if err != nil {
  427. b.Fatal(err)
  428. }
  429. return cert
  430. }