protocol_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. // Copyright (C) 2014 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 protocol
  7. import (
  8. "bytes"
  9. "context"
  10. "encoding/hex"
  11. "errors"
  12. "io"
  13. "sync"
  14. "testing"
  15. "time"
  16. lz4 "github.com/pierrec/lz4/v4"
  17. "google.golang.org/protobuf/proto"
  18. "github.com/syncthing/syncthing/internal/gen/bep"
  19. "github.com/syncthing/syncthing/lib/rand"
  20. "github.com/syncthing/syncthing/lib/testutil"
  21. )
  22. var (
  23. c0ID = NewDeviceID([]byte{1})
  24. c1ID = NewDeviceID([]byte{2})
  25. )
  26. func TestPing(t *testing.T) {
  27. ar, aw := io.Pipe()
  28. br, bw := io.Pipe()
  29. c0 := getRawConnection(NewConnection(c0ID, ar, bw, testutil.NoopCloser{}, newTestModel(), new(mockedConnectionInfo), CompressionAlways, testKeyGen))
  30. c0.Start()
  31. defer closeAndWait(c0, ar, bw)
  32. c1 := getRawConnection(NewConnection(c1ID, br, aw, testutil.NoopCloser{}, newTestModel(), new(mockedConnectionInfo), CompressionAlways, testKeyGen))
  33. c1.Start()
  34. defer closeAndWait(c1, ar, bw)
  35. c0.ClusterConfig(&ClusterConfig{}, nil)
  36. c1.ClusterConfig(&ClusterConfig{}, nil)
  37. if ok := c0.ping(); !ok {
  38. t.Error("c0 ping failed")
  39. }
  40. if ok := c1.ping(); !ok {
  41. t.Error("c1 ping failed")
  42. }
  43. }
  44. var errManual = errors.New("manual close")
  45. func TestClose(t *testing.T) {
  46. m0 := newTestModel()
  47. m1 := newTestModel()
  48. ar, aw := io.Pipe()
  49. br, bw := io.Pipe()
  50. c0 := getRawConnection(NewConnection(c0ID, ar, bw, testutil.NoopCloser{}, m0, new(mockedConnectionInfo), CompressionAlways, testKeyGen))
  51. c0.Start()
  52. defer closeAndWait(c0, ar, bw)
  53. c1 := NewConnection(c1ID, br, aw, testutil.NoopCloser{}, m1, new(mockedConnectionInfo), CompressionAlways, testKeyGen)
  54. c1.Start()
  55. defer closeAndWait(c1, ar, bw)
  56. c0.ClusterConfig(&ClusterConfig{}, nil)
  57. c1.ClusterConfig(&ClusterConfig{}, nil)
  58. c0.internalClose(errManual)
  59. <-c0.closed
  60. if err := m0.closedError(); err != errManual {
  61. t.Fatal("Connection should be closed")
  62. }
  63. // None of these should panic, some should return an error
  64. if c0.ping() {
  65. t.Error("Ping should not return true")
  66. }
  67. ctx := context.Background()
  68. c0.Index(ctx, &Index{Folder: "default"})
  69. c0.Index(ctx, &Index{Folder: "default"})
  70. if _, err := c0.Request(ctx, &Request{Folder: "default", Name: "foo"}); err == nil {
  71. t.Error("Request should return an error")
  72. }
  73. }
  74. // TestCloseOnBlockingSend checks that the connection does not deadlock when
  75. // Close is called while the underlying connection is broken (send blocks).
  76. // https://github.com/syncthing/syncthing/pull/5442
  77. func TestCloseOnBlockingSend(t *testing.T) {
  78. oldCloseTimeout := CloseTimeout
  79. CloseTimeout = 100 * time.Millisecond
  80. defer func() {
  81. CloseTimeout = oldCloseTimeout
  82. }()
  83. m := newTestModel()
  84. rw := testutil.NewBlockingRW()
  85. c := getRawConnection(NewConnection(c0ID, rw, rw, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, testKeyGen))
  86. c.Start()
  87. defer closeAndWait(c, rw)
  88. wg := sync.WaitGroup{}
  89. wg.Add(1)
  90. go func() {
  91. c.ClusterConfig(&ClusterConfig{}, nil)
  92. wg.Done()
  93. }()
  94. wg.Add(1)
  95. go func() {
  96. c.Close(errManual)
  97. wg.Done()
  98. }()
  99. // This simulates an error from ping timeout
  100. wg.Add(1)
  101. go func() {
  102. c.internalClose(ErrTimeout)
  103. wg.Done()
  104. }()
  105. done := make(chan struct{})
  106. go func() {
  107. wg.Wait()
  108. close(done)
  109. }()
  110. select {
  111. case <-done:
  112. case <-time.After(time.Second):
  113. t.Fatal("timed out before all functions returned")
  114. }
  115. }
  116. func TestCloseRace(t *testing.T) {
  117. indexReceived := make(chan struct{})
  118. unblockIndex := make(chan struct{})
  119. m0 := newTestModel()
  120. m0.indexFn = func(string, []FileInfo) {
  121. close(indexReceived)
  122. <-unblockIndex
  123. }
  124. m1 := newTestModel()
  125. ar, aw := io.Pipe()
  126. br, bw := io.Pipe()
  127. c0 := getRawConnection(NewConnection(c0ID, ar, bw, testutil.NoopCloser{}, m0, new(mockedConnectionInfo), CompressionNever, testKeyGen))
  128. c0.Start()
  129. defer closeAndWait(c0, ar, bw)
  130. c1 := NewConnection(c1ID, br, aw, testutil.NoopCloser{}, m1, new(mockedConnectionInfo), CompressionNever, testKeyGen)
  131. c1.Start()
  132. defer closeAndWait(c1, ar, bw)
  133. c0.ClusterConfig(&ClusterConfig{}, nil)
  134. c1.ClusterConfig(&ClusterConfig{}, nil)
  135. c1.Index(context.Background(), &Index{Folder: "default"})
  136. select {
  137. case <-indexReceived:
  138. case <-time.After(time.Second):
  139. t.Fatal("timed out before receiving index")
  140. }
  141. go c0.internalClose(errManual)
  142. select {
  143. case <-c0.closed:
  144. case <-time.After(time.Second):
  145. t.Fatal("timed out before c0.closed was closed")
  146. }
  147. select {
  148. case <-m0.closedCh:
  149. t.Errorf("receiver.Closed called before receiver.Index")
  150. default:
  151. }
  152. close(unblockIndex)
  153. if err := m0.closedError(); err != errManual {
  154. t.Fatal("Connection should be closed")
  155. }
  156. }
  157. func TestClusterConfigFirst(t *testing.T) {
  158. m := newTestModel()
  159. rw := testutil.NewBlockingRW()
  160. c := getRawConnection(NewConnection(c0ID, rw, &testutil.NoopRW{}, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, testKeyGen))
  161. c.Start()
  162. defer closeAndWait(c, rw)
  163. select {
  164. case c.outbox <- asyncMessage{&bep.Ping{}, nil}:
  165. t.Fatal("able to send ping before cluster config")
  166. case <-time.After(100 * time.Millisecond):
  167. // Allow some time for c.writerLoop to set up after c.Start
  168. }
  169. c.ClusterConfig(&ClusterConfig{}, nil)
  170. done := make(chan struct{})
  171. if ok := c.send(context.Background(), &bep.Ping{}, done); !ok {
  172. t.Fatal("send ping after cluster config returned false")
  173. }
  174. select {
  175. case <-done:
  176. case <-time.After(time.Second):
  177. t.Fatal("timed out before ping was sent")
  178. }
  179. done = make(chan struct{})
  180. go func() {
  181. c.internalClose(errManual)
  182. close(done)
  183. }()
  184. select {
  185. case <-done:
  186. case <-time.After(5 * time.Second):
  187. t.Fatal("Close didn't return before timeout")
  188. }
  189. if err := m.closedError(); err != errManual {
  190. t.Fatal("Connection should be closed")
  191. }
  192. }
  193. // TestCloseTimeout checks that calling Close times out and proceeds, if sending
  194. // the close message does not succeed.
  195. func TestCloseTimeout(t *testing.T) {
  196. oldCloseTimeout := CloseTimeout
  197. CloseTimeout = 100 * time.Millisecond
  198. defer func() {
  199. CloseTimeout = oldCloseTimeout
  200. }()
  201. m := newTestModel()
  202. rw := testutil.NewBlockingRW()
  203. c := getRawConnection(NewConnection(c0ID, rw, rw, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, testKeyGen))
  204. c.Start()
  205. defer closeAndWait(c, rw)
  206. done := make(chan struct{})
  207. go func() {
  208. c.Close(errManual)
  209. close(done)
  210. }()
  211. select {
  212. case <-done:
  213. case <-time.After(5 * CloseTimeout):
  214. t.Fatal("timed out before Close returned")
  215. }
  216. }
  217. func TestUnmarshalFDPUv16v17(t *testing.T) {
  218. var fdpu bep.FileDownloadProgressUpdate
  219. m0, _ := hex.DecodeString("08cda1e2e3011278f3918787f3b89b8af2958887f0aa9389f3a08588f3aa8f96f39aa8a5f48b9188f19286a0f3848da4f3aba799f3beb489f0a285b9f487b684f2a3bda2f48598b4f2938a89f2a28badf187a0a2f2aebdbdf4849494f4808fbbf2b3a2adf2bb95bff0a6ada4f198ab9af29a9c8bf1abb793f3baabb2f188a6ba1a0020bb9390f60220f6d9e42220b0c7e2b2fdffffffff0120fdb2dfcdfbffffffff0120cedab1d50120bd8784c0feffffffff0120ace99591fdffffffff0120eed7d09af9ffffffff01")
  220. if err := proto.Unmarshal(m0, &fdpu); err != nil {
  221. t.Fatal("Unmarshalling message from v0.14.16:", err)
  222. }
  223. m1, _ := hex.DecodeString("0880f1969905128401f099b192f0abb1b9f3b280aff19e9aa2f3b89e84f484b39df1a7a6b0f1aea4b1f0adac94f3b39caaf1939281f1928a8af0abb1b0f0a8b3b3f3a88e94f2bd85acf29c97a9f2969da6f0b7a188f1908ea2f09a9c9bf19d86a6f29aada8f389bb95f0bf9d88f1a09d89f1b1a4b5f29b9eabf298a59df1b2a589f2979ebdf0b69880f18986b21a440a1508c7d8fb8897ca93d90910e8c4d8e8f2f8f0ccee010a1508afa8ffd8c085b393c50110e5bdedc3bddefe9b0b0a1408a1bedddba4cac5da3c10b8e5d9958ca7e3ec19225ae2f88cb2f8ffffffff018ceda99cfbffffffff01b9c298a407e295e8e9fcffffffff01f3b9ade5fcffffffff01c08bfea9fdffffffff01a2c2e5e1ffffffffff0186dcc5dafdffffffff01e9ffc7e507c9d89db8fdffffffff01")
  224. if err := proto.Unmarshal(m1, &fdpu); err != nil {
  225. t.Fatal("Unmarshalling message from v0.14.16:", err)
  226. }
  227. }
  228. func TestWriteCompressed(t *testing.T) {
  229. for _, random := range []bool{false, true} {
  230. buf := new(bytes.Buffer)
  231. c := &rawConnection{
  232. cr: &countingReader{Reader: buf},
  233. cw: &countingWriter{Writer: buf},
  234. compression: CompressionAlways,
  235. }
  236. msg := (&Response{Data: make([]byte, 10240)}).toWire()
  237. if random {
  238. // This should make the message incompressible.
  239. rand.Read(msg.Data)
  240. }
  241. if err := c.writeMessage(msg); err != nil {
  242. t.Fatal(err)
  243. }
  244. got, err := c.readMessage(make([]byte, 4))
  245. if err != nil {
  246. t.Fatal(err)
  247. }
  248. if !bytes.Equal(got.(*bep.Response).Data, msg.Data) {
  249. t.Error("received the wrong message")
  250. }
  251. hdr := &bep.Header{Type: typeOf(msg)}
  252. size := int64(2 + proto.Size(hdr) + 4 + proto.Size(msg))
  253. if c.cr.Tot() > size {
  254. t.Errorf("compression enlarged message from %d to %d",
  255. size, c.cr.Tot())
  256. }
  257. }
  258. }
  259. func TestLZ4Compression(t *testing.T) {
  260. for i := 0; i < 10; i++ {
  261. dataLen := 150 + rand.Intn(150)
  262. data := make([]byte, dataLen)
  263. _, err := io.ReadFull(rand.Reader, data[100:])
  264. if err != nil {
  265. t.Fatal(err)
  266. }
  267. comp := make([]byte, lz4.CompressBlockBound(dataLen))
  268. compLen, err := lz4Compress(data, comp)
  269. if err != nil {
  270. t.Errorf("compressing %d bytes: %v", dataLen, err)
  271. continue
  272. }
  273. res, err := lz4Decompress(comp[:compLen])
  274. if err != nil {
  275. t.Errorf("decompressing %d bytes to %d: %v", len(comp), dataLen, err)
  276. continue
  277. }
  278. if len(res) != len(data) {
  279. t.Errorf("Incorrect len %d != expected %d", len(res), len(data))
  280. }
  281. if !bytes.Equal(data, res) {
  282. t.Error("Incorrect decompressed data")
  283. }
  284. t.Logf("OK #%d, %d -> %d -> %d", i, dataLen, len(comp), dataLen)
  285. }
  286. }
  287. func TestLZ4CompressionUpdate(t *testing.T) {
  288. uncompressed := []byte("this is some arbitrary yet fairly compressible data")
  289. // Compressed, as created by the LZ4 implementation in Syncthing 1.18.6 and earlier.
  290. oldCompressed, _ := hex.DecodeString("00000033f0247468697320697320736f6d65206172626974726172792079657420666169726c7920636f6d707265737369626c652064617461")
  291. // Verify that we can decompress
  292. res, err := lz4Decompress(oldCompressed)
  293. if err != nil {
  294. t.Fatal(err)
  295. }
  296. if !bytes.Equal(uncompressed, res) {
  297. t.Fatal("result does not match")
  298. }
  299. // Verify that our current compression is equivalent
  300. buf := make([]byte, 128)
  301. n, err := lz4Compress(uncompressed, buf)
  302. if err != nil {
  303. t.Fatal(err)
  304. }
  305. if !bytes.Equal(oldCompressed, buf[:n]) {
  306. t.Logf("%x", oldCompressed)
  307. t.Logf("%x", buf[:n])
  308. t.Fatal("compression does not match")
  309. }
  310. }
  311. func TestCheckFilename(t *testing.T) {
  312. cases := []struct {
  313. name string
  314. ok bool
  315. }{
  316. // Valid filenames
  317. {"foo", true},
  318. {"foo/bar/baz", true},
  319. {"foo/bar:baz", true}, // colon is ok in general, will be filtered on windows
  320. {`\`, true}, // path separator on the wire is forward slash, so as above
  321. {`\.`, true},
  322. {`\..`, true},
  323. {".foo", true},
  324. {"foo..", true},
  325. // Invalid filenames
  326. {"foo/..", false},
  327. {"foo/../bar", false},
  328. {"../foo/../bar", false},
  329. {"", false},
  330. {".", false},
  331. {"..", false},
  332. {"/", false},
  333. {"/.", false},
  334. {"/..", false},
  335. {"/foo", false},
  336. {"./foo", false},
  337. {"foo./", false},
  338. {"foo/.", false},
  339. {"foo/", false},
  340. }
  341. for _, tc := range cases {
  342. err := checkFilename(tc.name)
  343. if (err == nil) != tc.ok {
  344. t.Errorf("Unexpected result for checkFilename(%q): %v", tc.name, err)
  345. }
  346. }
  347. }
  348. func TestCheckConsistency(t *testing.T) {
  349. cases := []struct {
  350. fi FileInfo
  351. ok bool
  352. }{
  353. {
  354. // valid
  355. fi: FileInfo{
  356. Name: "foo",
  357. Type: FileInfoTypeFile,
  358. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  359. },
  360. ok: true,
  361. },
  362. {
  363. // deleted with blocks
  364. fi: FileInfo{
  365. Name: "foo",
  366. Deleted: true,
  367. Type: FileInfoTypeFile,
  368. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  369. },
  370. ok: false,
  371. },
  372. {
  373. // no blocks
  374. fi: FileInfo{
  375. Name: "foo",
  376. Type: FileInfoTypeFile,
  377. },
  378. ok: false,
  379. },
  380. {
  381. // directory with blocks
  382. fi: FileInfo{
  383. Name: "foo",
  384. Type: FileInfoTypeDirectory,
  385. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  386. },
  387. ok: false,
  388. },
  389. }
  390. for _, tc := range cases {
  391. err := checkFileInfoConsistency(tc.fi)
  392. if tc.ok && err != nil {
  393. t.Errorf("Unexpected error %v (want nil) for %v", err, tc.fi)
  394. }
  395. if !tc.ok && err == nil {
  396. t.Errorf("Unexpected nil error for %v", tc.fi)
  397. }
  398. }
  399. }
  400. func TestBlockSize(t *testing.T) {
  401. cases := []struct {
  402. fileSize int64
  403. blockSize int
  404. }{
  405. {1 << KiB, 128 << KiB},
  406. {1 << MiB, 128 << KiB},
  407. {499 << MiB, 256 << KiB},
  408. {500 << MiB, 512 << KiB},
  409. {501 << MiB, 512 << KiB},
  410. {1 << GiB, 1 << MiB},
  411. {2 << GiB, 2 << MiB},
  412. {3 << GiB, 2 << MiB},
  413. {500 << GiB, 16 << MiB},
  414. {50000 << GiB, 16 << MiB},
  415. }
  416. for _, tc := range cases {
  417. size := BlockSize(tc.fileSize)
  418. if size != tc.blockSize {
  419. t.Errorf("BlockSize(%d), size=%d, expected %d", tc.fileSize, size, tc.blockSize)
  420. }
  421. }
  422. }
  423. var blockSize int
  424. func BenchmarkBlockSize(b *testing.B) {
  425. for i := 0; i < b.N; i++ {
  426. blockSize = BlockSize(16 << 30)
  427. }
  428. }
  429. // TestClusterConfigAfterClose checks that ClusterConfig does not deadlock when
  430. // ClusterConfig is called on a closed connection.
  431. func TestClusterConfigAfterClose(t *testing.T) {
  432. m := newTestModel()
  433. rw := testutil.NewBlockingRW()
  434. c := getRawConnection(NewConnection(c0ID, rw, rw, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, testKeyGen))
  435. c.Start()
  436. defer closeAndWait(c, rw)
  437. c.internalClose(errManual)
  438. done := make(chan struct{})
  439. go func() {
  440. c.ClusterConfig(&ClusterConfig{}, nil)
  441. close(done)
  442. }()
  443. select {
  444. case <-done:
  445. case <-time.After(time.Second):
  446. t.Fatal("timed out before Cluster Config returned")
  447. }
  448. }
  449. func TestDispatcherToCloseDeadlock(t *testing.T) {
  450. // Verify that we don't deadlock when calling Close() from within one of
  451. // the model callbacks (ClusterConfig).
  452. m := newTestModel()
  453. rw := testutil.NewBlockingRW()
  454. c := getRawConnection(NewConnection(c0ID, rw, &testutil.NoopRW{}, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, testKeyGen))
  455. m.ccFn = func(*ClusterConfig) {
  456. c.Close(errManual)
  457. }
  458. c.Start()
  459. defer closeAndWait(c, rw)
  460. c.inbox <- &bep.ClusterConfig{}
  461. select {
  462. case <-c.dispatcherLoopStopped:
  463. case <-time.After(time.Second):
  464. t.Fatal("timed out before dispatcher loop terminated")
  465. }
  466. }
  467. func TestIndexIDString(t *testing.T) {
  468. // Index ID is a 64 bit, zero padded hex integer.
  469. var i IndexID = 42
  470. if i.String() != "0x000000000000002A" {
  471. t.Error(i.String())
  472. }
  473. }
  474. func closeAndWait(c interface{}, closers ...io.Closer) {
  475. for _, closer := range closers {
  476. closer.Close()
  477. }
  478. var raw *rawConnection
  479. switch i := c.(type) {
  480. case *rawConnection:
  481. raw = i
  482. default:
  483. raw = getRawConnection(c.(Connection))
  484. }
  485. raw.internalClose(ErrClosed)
  486. raw.loopWG.Wait()
  487. }
  488. func getRawConnection(c Connection) *rawConnection {
  489. var raw *rawConnection
  490. switch i := c.(type) {
  491. case wireFormatConnection:
  492. raw = i.Connection.(encryptedConnection).conn
  493. case encryptedConnection:
  494. raw = i.conn
  495. }
  496. return raw
  497. }