protocol_test.go 15 KB

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