connections_test.go 11 KB

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