protocol_test.go 15 KB

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