protocol_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "bytes"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "io"
  10. "io/ioutil"
  11. "runtime"
  12. "sync"
  13. "testing"
  14. "testing/quick"
  15. "time"
  16. "github.com/syncthing/syncthing/lib/rand"
  17. "github.com/syncthing/syncthing/lib/testutils"
  18. )
  19. var (
  20. c0ID = NewDeviceID([]byte{1})
  21. c1ID = NewDeviceID([]byte{2})
  22. quickCfg = &quick.Config{}
  23. )
  24. func TestPing(t *testing.T) {
  25. ar, aw := io.Pipe()
  26. br, bw := io.Pipe()
  27. c0 := NewConnection(c0ID, ar, bw, newTestModel(), "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  28. c0.Start()
  29. c1 := NewConnection(c1ID, br, aw, newTestModel(), "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  30. c1.Start()
  31. c0.ClusterConfig(ClusterConfig{})
  32. c1.ClusterConfig(ClusterConfig{})
  33. if ok := c0.ping(); !ok {
  34. t.Error("c0 ping failed")
  35. }
  36. if ok := c1.ping(); !ok {
  37. t.Error("c1 ping failed")
  38. }
  39. }
  40. var errManual = errors.New("manual close")
  41. func TestClose(t *testing.T) {
  42. m0 := newTestModel()
  43. m1 := newTestModel()
  44. ar, aw := io.Pipe()
  45. br, bw := io.Pipe()
  46. c0 := NewConnection(c0ID, ar, bw, m0, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  47. c0.Start()
  48. c1 := NewConnection(c1ID, br, aw, m1, "name", CompressAlways)
  49. c1.Start()
  50. c0.ClusterConfig(ClusterConfig{})
  51. c1.ClusterConfig(ClusterConfig{})
  52. c0.internalClose(errManual)
  53. <-c0.closed
  54. if err := m0.closedError(); err != errManual {
  55. t.Fatal("Connection should be closed")
  56. }
  57. // None of these should panic, some should return an error
  58. if c0.ping() {
  59. t.Error("Ping should not return true")
  60. }
  61. c0.Index("default", nil)
  62. c0.Index("default", nil)
  63. if _, err := c0.Request("default", "foo", 0, 0, nil, 0, false); err == nil {
  64. t.Error("Request should return an error")
  65. }
  66. }
  67. // TestCloseOnBlockingSend checks that the connection does not deadlock when
  68. // Close is called while the underlying connection is broken (send blocks).
  69. // https://github.com/syncthing/syncthing/pull/5442
  70. func TestCloseOnBlockingSend(t *testing.T) {
  71. oldCloseTimeout := CloseTimeout
  72. CloseTimeout = 100 * time.Millisecond
  73. defer func() {
  74. CloseTimeout = oldCloseTimeout
  75. }()
  76. m := newTestModel()
  77. c := NewConnection(c0ID, &testutils.BlockingRW{}, &testutils.BlockingRW{}, m, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  78. c.Start()
  79. wg := sync.WaitGroup{}
  80. wg.Add(1)
  81. go func() {
  82. c.ClusterConfig(ClusterConfig{})
  83. wg.Done()
  84. }()
  85. wg.Add(1)
  86. go func() {
  87. c.Close(errManual)
  88. wg.Done()
  89. }()
  90. // This simulates an error from ping timeout
  91. wg.Add(1)
  92. go func() {
  93. c.internalClose(ErrTimeout)
  94. wg.Done()
  95. }()
  96. done := make(chan struct{})
  97. go func() {
  98. wg.Wait()
  99. close(done)
  100. }()
  101. select {
  102. case <-done:
  103. case <-time.After(time.Second):
  104. t.Fatal("timed out before all functions returned")
  105. }
  106. }
  107. func TestCloseRace(t *testing.T) {
  108. indexReceived := make(chan struct{})
  109. unblockIndex := make(chan struct{})
  110. m0 := newTestModel()
  111. m0.indexFn = func(_ DeviceID, _ string, _ []FileInfo) {
  112. close(indexReceived)
  113. <-unblockIndex
  114. }
  115. m1 := newTestModel()
  116. ar, aw := io.Pipe()
  117. br, bw := io.Pipe()
  118. c0 := NewConnection(c0ID, ar, bw, m0, "c0", CompressNever).(wireFormatConnection).Connection.(*rawConnection)
  119. c0.Start()
  120. c1 := NewConnection(c1ID, br, aw, m1, "c1", CompressNever)
  121. c1.Start()
  122. c0.ClusterConfig(ClusterConfig{})
  123. c1.ClusterConfig(ClusterConfig{})
  124. c1.Index("default", nil)
  125. select {
  126. case <-indexReceived:
  127. case <-time.After(time.Second):
  128. t.Fatal("timed out before receiving index")
  129. }
  130. go c0.internalClose(errManual)
  131. select {
  132. case <-c0.closed:
  133. case <-time.After(time.Second):
  134. t.Fatal("timed out before c0.closed was closed")
  135. }
  136. select {
  137. case <-m0.closedCh:
  138. t.Errorf("receiver.Closed called before receiver.Index")
  139. default:
  140. }
  141. close(unblockIndex)
  142. if err := m0.closedError(); err != errManual {
  143. t.Fatal("Connection should be closed")
  144. }
  145. }
  146. func TestClusterConfigFirst(t *testing.T) {
  147. m := newTestModel()
  148. c := NewConnection(c0ID, &testutils.BlockingRW{}, &testutils.NoopRW{}, m, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  149. c.Start()
  150. select {
  151. case c.outbox <- asyncMessage{&Ping{}, nil}:
  152. t.Fatal("able to send ping before cluster config")
  153. case <-time.After(100 * time.Millisecond):
  154. // Allow some time for c.writerLoop to setup after c.Start
  155. }
  156. c.ClusterConfig(ClusterConfig{})
  157. done := make(chan struct{})
  158. if ok := c.send(&Ping{}, done); !ok {
  159. t.Fatal("send ping after cluster config returned false")
  160. }
  161. select {
  162. case <-done:
  163. case <-time.After(time.Second):
  164. t.Fatal("timed out before ping was sent")
  165. }
  166. done = make(chan struct{})
  167. go func() {
  168. c.internalClose(errManual)
  169. close(done)
  170. }()
  171. select {
  172. case <-done:
  173. case <-time.After(5 * time.Second):
  174. t.Fatal("Close didn't return before timeout")
  175. }
  176. if err := m.closedError(); err != errManual {
  177. t.Fatal("Connection should be closed")
  178. }
  179. }
  180. // TestCloseTimeout checks that calling Close times out and proceeds, if sending
  181. // the close message does not succeed.
  182. func TestCloseTimeout(t *testing.T) {
  183. oldCloseTimeout := CloseTimeout
  184. CloseTimeout = 100 * time.Millisecond
  185. defer func() {
  186. CloseTimeout = oldCloseTimeout
  187. }()
  188. m := newTestModel()
  189. c := NewConnection(c0ID, &testutils.BlockingRW{}, &testutils.BlockingRW{}, m, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  190. c.Start()
  191. done := make(chan struct{})
  192. go func() {
  193. c.Close(errManual)
  194. close(done)
  195. }()
  196. select {
  197. case <-done:
  198. case <-time.After(5 * CloseTimeout):
  199. t.Fatal("timed out before Close returned")
  200. }
  201. }
  202. func TestMarshalIndexMessage(t *testing.T) {
  203. if testing.Short() {
  204. quickCfg.MaxCount = 10
  205. }
  206. f := func(m1 Index) bool {
  207. if len(m1.Files) == 0 {
  208. m1.Files = nil
  209. }
  210. for i, f := range m1.Files {
  211. if len(f.Blocks) == 0 {
  212. m1.Files[i].Blocks = nil
  213. } else {
  214. for j := range f.Blocks {
  215. f.Blocks[j].Offset = 0
  216. if len(f.Blocks[j].Hash) == 0 {
  217. f.Blocks[j].Hash = nil
  218. }
  219. }
  220. }
  221. if len(f.Version.Counters) == 0 {
  222. m1.Files[i].Version.Counters = nil
  223. }
  224. }
  225. return testMarshal(t, "index", &m1, &Index{})
  226. }
  227. if err := quick.Check(f, quickCfg); err != nil {
  228. t.Error(err)
  229. }
  230. }
  231. func TestMarshalRequestMessage(t *testing.T) {
  232. if testing.Short() {
  233. quickCfg.MaxCount = 10
  234. }
  235. f := func(m1 Request) bool {
  236. if len(m1.Hash) == 0 {
  237. m1.Hash = nil
  238. }
  239. return testMarshal(t, "request", &m1, &Request{})
  240. }
  241. if err := quick.Check(f, quickCfg); err != nil {
  242. t.Error(err)
  243. }
  244. }
  245. func TestMarshalResponseMessage(t *testing.T) {
  246. if testing.Short() {
  247. quickCfg.MaxCount = 10
  248. }
  249. f := func(m1 Response) bool {
  250. if len(m1.Data) == 0 {
  251. m1.Data = nil
  252. }
  253. return testMarshal(t, "response", &m1, &Response{})
  254. }
  255. if err := quick.Check(f, quickCfg); err != nil {
  256. t.Error(err)
  257. }
  258. }
  259. func TestMarshalClusterConfigMessage(t *testing.T) {
  260. if testing.Short() {
  261. quickCfg.MaxCount = 10
  262. }
  263. f := func(m1 ClusterConfig) bool {
  264. if len(m1.Folders) == 0 {
  265. m1.Folders = nil
  266. }
  267. for i := range m1.Folders {
  268. if len(m1.Folders[i].Devices) == 0 {
  269. m1.Folders[i].Devices = nil
  270. }
  271. }
  272. return testMarshal(t, "clusterconfig", &m1, &ClusterConfig{})
  273. }
  274. if err := quick.Check(f, quickCfg); err != nil {
  275. t.Error(err)
  276. }
  277. }
  278. func TestMarshalCloseMessage(t *testing.T) {
  279. if testing.Short() {
  280. quickCfg.MaxCount = 10
  281. }
  282. f := func(m1 Close) bool {
  283. return testMarshal(t, "close", &m1, &Close{})
  284. }
  285. if err := quick.Check(f, quickCfg); err != nil {
  286. t.Error(err)
  287. }
  288. }
  289. func TestMarshalFDPU(t *testing.T) {
  290. if testing.Short() {
  291. quickCfg.MaxCount = 10
  292. }
  293. f := func(m1 FileDownloadProgressUpdate) bool {
  294. if len(m1.Version.Counters) == 0 {
  295. m1.Version.Counters = nil
  296. }
  297. return testMarshal(t, "close", &m1, &FileDownloadProgressUpdate{})
  298. }
  299. if err := quick.Check(f, quickCfg); err != nil {
  300. t.Error(err)
  301. }
  302. }
  303. func TestUnmarshalFDPUv16v17(t *testing.T) {
  304. var fdpu FileDownloadProgressUpdate
  305. m0, _ := hex.DecodeString("08cda1e2e3011278f3918787f3b89b8af2958887f0aa9389f3a08588f3aa8f96f39aa8a5f48b9188f19286a0f3848da4f3aba799f3beb489f0a285b9f487b684f2a3bda2f48598b4f2938a89f2a28badf187a0a2f2aebdbdf4849494f4808fbbf2b3a2adf2bb95bff0a6ada4f198ab9af29a9c8bf1abb793f3baabb2f188a6ba1a0020bb9390f60220f6d9e42220b0c7e2b2fdffffffff0120fdb2dfcdfbffffffff0120cedab1d50120bd8784c0feffffffff0120ace99591fdffffffff0120eed7d09af9ffffffff01")
  306. if err := fdpu.Unmarshal(m0); err != nil {
  307. t.Fatal("Unmarshalling message from v0.14.16:", err)
  308. }
  309. m1, _ := hex.DecodeString("0880f1969905128401f099b192f0abb1b9f3b280aff19e9aa2f3b89e84f484b39df1a7a6b0f1aea4b1f0adac94f3b39caaf1939281f1928a8af0abb1b0f0a8b3b3f3a88e94f2bd85acf29c97a9f2969da6f0b7a188f1908ea2f09a9c9bf19d86a6f29aada8f389bb95f0bf9d88f1a09d89f1b1a4b5f29b9eabf298a59df1b2a589f2979ebdf0b69880f18986b21a440a1508c7d8fb8897ca93d90910e8c4d8e8f2f8f0ccee010a1508afa8ffd8c085b393c50110e5bdedc3bddefe9b0b0a1408a1bedddba4cac5da3c10b8e5d9958ca7e3ec19225ae2f88cb2f8ffffffff018ceda99cfbffffffff01b9c298a407e295e8e9fcffffffff01f3b9ade5fcffffffff01c08bfea9fdffffffff01a2c2e5e1ffffffffff0186dcc5dafdffffffff01e9ffc7e507c9d89db8fdffffffff01")
  310. if err := fdpu.Unmarshal(m1); err != nil {
  311. t.Fatal("Unmarshalling message from v0.14.16:", err)
  312. }
  313. }
  314. func testMarshal(t *testing.T, prefix string, m1, m2 message) bool {
  315. buf, err := m1.Marshal()
  316. if err != nil {
  317. t.Fatal(err)
  318. }
  319. err = m2.Unmarshal(buf)
  320. if err != nil {
  321. t.Fatal(err)
  322. }
  323. bs1, _ := json.MarshalIndent(m1, "", " ")
  324. bs2, _ := json.MarshalIndent(m2, "", " ")
  325. if !bytes.Equal(bs1, bs2) {
  326. ioutil.WriteFile(prefix+"-1.txt", bs1, 0644)
  327. ioutil.WriteFile(prefix+"-2.txt", bs2, 0644)
  328. return false
  329. }
  330. return true
  331. }
  332. func TestLZ4Compression(t *testing.T) {
  333. c := new(rawConnection)
  334. for i := 0; i < 10; i++ {
  335. dataLen := 150 + rand.Intn(150)
  336. data := make([]byte, dataLen)
  337. _, err := io.ReadFull(rand.Reader, data[100:])
  338. if err != nil {
  339. t.Fatal(err)
  340. }
  341. comp, err := c.lz4Compress(data)
  342. if err != nil {
  343. t.Errorf("compressing %d bytes: %v", dataLen, err)
  344. continue
  345. }
  346. res, err := c.lz4Decompress(comp)
  347. if err != nil {
  348. t.Errorf("decompressing %d bytes to %d: %v", len(comp), dataLen, err)
  349. continue
  350. }
  351. if len(res) != len(data) {
  352. t.Errorf("Incorrect len %d != expected %d", len(res), len(data))
  353. }
  354. if !bytes.Equal(data, res) {
  355. t.Error("Incorrect decompressed data")
  356. }
  357. t.Logf("OK #%d, %d -> %d -> %d", i, dataLen, len(comp), dataLen)
  358. }
  359. }
  360. func TestCheckFilename(t *testing.T) {
  361. cases := []struct {
  362. name string
  363. ok bool
  364. }{
  365. // Valid filenames
  366. {"foo", true},
  367. {"foo/bar/baz", true},
  368. {"foo/bar:baz", true}, // colon is ok in general, will be filtered on windows
  369. {`\`, true}, // path separator on the wire is forward slash, so as above
  370. {`\.`, true},
  371. {`\..`, true},
  372. {".foo", true},
  373. {"foo..", true},
  374. // Invalid filenames
  375. {"foo/..", false},
  376. {"foo/../bar", false},
  377. {"../foo/../bar", false},
  378. {"", false},
  379. {".", false},
  380. {"..", false},
  381. {"/", false},
  382. {"/.", false},
  383. {"/..", false},
  384. {"/foo", false},
  385. {"./foo", false},
  386. {"foo./", false},
  387. {"foo/.", false},
  388. {"foo/", false},
  389. }
  390. for _, tc := range cases {
  391. err := checkFilename(tc.name)
  392. if (err == nil) != tc.ok {
  393. t.Errorf("Unexpected result for checkFilename(%q): %v", tc.name, err)
  394. }
  395. }
  396. }
  397. func TestCheckConsistency(t *testing.T) {
  398. cases := []struct {
  399. fi FileInfo
  400. ok bool
  401. }{
  402. {
  403. // valid
  404. fi: FileInfo{
  405. Name: "foo",
  406. Type: FileInfoTypeFile,
  407. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  408. },
  409. ok: true,
  410. },
  411. {
  412. // deleted with blocks
  413. fi: FileInfo{
  414. Name: "foo",
  415. Deleted: true,
  416. Type: FileInfoTypeFile,
  417. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  418. },
  419. ok: false,
  420. },
  421. {
  422. // no blocks
  423. fi: FileInfo{
  424. Name: "foo",
  425. Type: FileInfoTypeFile,
  426. },
  427. ok: false,
  428. },
  429. {
  430. // directory with blocks
  431. fi: FileInfo{
  432. Name: "foo",
  433. Type: FileInfoTypeDirectory,
  434. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  435. },
  436. ok: false,
  437. },
  438. }
  439. for _, tc := range cases {
  440. err := checkFileInfoConsistency(tc.fi)
  441. if tc.ok && err != nil {
  442. t.Errorf("Unexpected error %v (want nil) for %v", err, tc.fi)
  443. }
  444. if !tc.ok && err == nil {
  445. t.Errorf("Unexpected nil error for %v", tc.fi)
  446. }
  447. }
  448. }
  449. func TestBlockSize(t *testing.T) {
  450. cases := []struct {
  451. fileSize int64
  452. blockSize int
  453. }{
  454. {1 << KiB, 128 << KiB},
  455. {1 << MiB, 128 << KiB},
  456. {499 << MiB, 256 << KiB},
  457. {500 << MiB, 512 << KiB},
  458. {501 << MiB, 512 << KiB},
  459. {1 << GiB, 1 << MiB},
  460. {2 << GiB, 2 << MiB},
  461. {3 << GiB, 2 << MiB},
  462. {500 << GiB, 16 << MiB},
  463. {50000 << GiB, 16 << MiB},
  464. }
  465. for _, tc := range cases {
  466. size := BlockSize(tc.fileSize)
  467. if size != tc.blockSize {
  468. t.Errorf("BlockSize(%d), size=%d, expected %d", tc.fileSize, size, tc.blockSize)
  469. }
  470. }
  471. }
  472. var blockSize int
  473. func BenchmarkBlockSize(b *testing.B) {
  474. for i := 0; i < b.N; i++ {
  475. blockSize = BlockSize(16 << 30)
  476. }
  477. }
  478. func TestLocalFlagBits(t *testing.T) {
  479. var f FileInfo
  480. if f.IsIgnored() || f.MustRescan() || f.IsInvalid() {
  481. t.Error("file should have no weird bits set by default")
  482. }
  483. f.SetIgnored(42)
  484. if !f.IsIgnored() || f.MustRescan() || !f.IsInvalid() {
  485. t.Error("file should be ignored and invalid")
  486. }
  487. f.SetMustRescan(42)
  488. if f.IsIgnored() || !f.MustRescan() || !f.IsInvalid() {
  489. t.Error("file should be must-rescan and invalid")
  490. }
  491. f.SetUnsupported(42)
  492. if f.IsIgnored() || f.MustRescan() || !f.IsInvalid() {
  493. t.Error("file should be invalid")
  494. }
  495. }
  496. func TestIsEquivalent(t *testing.T) {
  497. b := func(v bool) *bool {
  498. return &v
  499. }
  500. type testCase struct {
  501. a FileInfo
  502. b FileInfo
  503. ignPerms *bool // nil means should not matter, we'll test both variants
  504. ignBlocks *bool
  505. ignFlags uint32
  506. eq bool
  507. }
  508. cases := []testCase{
  509. // Empty FileInfos are equivalent
  510. {eq: true},
  511. // Various basic attributes, all of which cause ineqality when
  512. // they differ
  513. {
  514. a: FileInfo{Name: "foo"},
  515. b: FileInfo{Name: "bar"},
  516. eq: false,
  517. },
  518. {
  519. a: FileInfo{Type: FileInfoTypeFile},
  520. b: FileInfo{Type: FileInfoTypeDirectory},
  521. eq: false,
  522. },
  523. {
  524. a: FileInfo{Size: 1234},
  525. b: FileInfo{Size: 2345},
  526. eq: false,
  527. },
  528. {
  529. a: FileInfo{Deleted: false},
  530. b: FileInfo{Deleted: true},
  531. eq: false,
  532. },
  533. {
  534. a: FileInfo{RawInvalid: false},
  535. b: FileInfo{RawInvalid: true},
  536. eq: false,
  537. },
  538. {
  539. a: FileInfo{ModifiedS: 1234},
  540. b: FileInfo{ModifiedS: 2345},
  541. eq: false,
  542. },
  543. {
  544. a: FileInfo{ModifiedNs: 1234},
  545. b: FileInfo{ModifiedNs: 2345},
  546. eq: false,
  547. },
  548. // Special handling of local flags and invalidity. "MustRescan"
  549. // files are never equivalent to each other. Otherwise, equivalence
  550. // is based just on whether the file becomes IsInvalid() or not, not
  551. // the specific reason or flag bits.
  552. {
  553. a: FileInfo{LocalFlags: FlagLocalMustRescan},
  554. b: FileInfo{LocalFlags: FlagLocalMustRescan},
  555. eq: false,
  556. },
  557. {
  558. a: FileInfo{RawInvalid: true},
  559. b: FileInfo{RawInvalid: true},
  560. eq: true,
  561. },
  562. {
  563. a: FileInfo{LocalFlags: FlagLocalUnsupported},
  564. b: FileInfo{LocalFlags: FlagLocalUnsupported},
  565. eq: true,
  566. },
  567. {
  568. a: FileInfo{RawInvalid: true},
  569. b: FileInfo{LocalFlags: FlagLocalUnsupported},
  570. eq: true,
  571. },
  572. {
  573. a: FileInfo{LocalFlags: 0},
  574. b: FileInfo{LocalFlags: FlagLocalReceiveOnly},
  575. eq: false,
  576. },
  577. {
  578. a: FileInfo{LocalFlags: 0},
  579. b: FileInfo{LocalFlags: FlagLocalReceiveOnly},
  580. ignFlags: FlagLocalReceiveOnly,
  581. eq: true,
  582. },
  583. // Difference in blocks is not OK
  584. {
  585. a: FileInfo{Blocks: []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}},
  586. b: FileInfo{Blocks: []BlockInfo{{Hash: []byte{2, 3, 4, 5}}}},
  587. ignBlocks: b(false),
  588. eq: false,
  589. },
  590. // ... unless we say it is
  591. {
  592. a: FileInfo{Blocks: []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}},
  593. b: FileInfo{Blocks: []BlockInfo{{Hash: []byte{2, 3, 4, 5}}}},
  594. ignBlocks: b(true),
  595. eq: true,
  596. },
  597. // Difference in permissions is not OK.
  598. {
  599. a: FileInfo{Permissions: 0444},
  600. b: FileInfo{Permissions: 0666},
  601. ignPerms: b(false),
  602. eq: false,
  603. },
  604. // ... unless we say it is
  605. {
  606. a: FileInfo{Permissions: 0666},
  607. b: FileInfo{Permissions: 0444},
  608. ignPerms: b(true),
  609. eq: true,
  610. },
  611. // These attributes are not checked at all
  612. {
  613. a: FileInfo{NoPermissions: false},
  614. b: FileInfo{NoPermissions: true},
  615. eq: true,
  616. },
  617. {
  618. a: FileInfo{Version: Vector{Counters: []Counter{{ID: 1, Value: 42}}}},
  619. b: FileInfo{Version: Vector{Counters: []Counter{{ID: 42, Value: 1}}}},
  620. eq: true,
  621. },
  622. {
  623. a: FileInfo{Sequence: 1},
  624. b: FileInfo{Sequence: 2},
  625. eq: true,
  626. },
  627. // The block size is not checked (but this would fail the blocks
  628. // check in real world)
  629. {
  630. a: FileInfo{RawBlockSize: 1},
  631. b: FileInfo{RawBlockSize: 2},
  632. eq: true,
  633. },
  634. // The symlink target is checked for symlinks
  635. {
  636. a: FileInfo{Type: FileInfoTypeSymlink, SymlinkTarget: "a"},
  637. b: FileInfo{Type: FileInfoTypeSymlink, SymlinkTarget: "b"},
  638. eq: false,
  639. },
  640. // ... but not for non-symlinks
  641. {
  642. a: FileInfo{Type: FileInfoTypeFile, SymlinkTarget: "a"},
  643. b: FileInfo{Type: FileInfoTypeFile, SymlinkTarget: "b"},
  644. eq: true,
  645. },
  646. }
  647. if runtime.GOOS == "windows" {
  648. // On windows we only check the user writable bit of the permission
  649. // set, so these are equivalent.
  650. cases = append(cases, testCase{
  651. a: FileInfo{Permissions: 0777},
  652. b: FileInfo{Permissions: 0600},
  653. ignPerms: b(false),
  654. eq: true,
  655. })
  656. }
  657. for i, tc := range cases {
  658. // Check the standard attributes with all permutations of the
  659. // special ignore flags, unless the value of those flags are given
  660. // in the tests.
  661. for _, ignPerms := range []bool{true, false} {
  662. for _, ignBlocks := range []bool{true, false} {
  663. if tc.ignPerms != nil && *tc.ignPerms != ignPerms {
  664. continue
  665. }
  666. if tc.ignBlocks != nil && *tc.ignBlocks != ignBlocks {
  667. continue
  668. }
  669. if res := tc.a.isEquivalent(tc.b, 0, ignPerms, ignBlocks, tc.ignFlags); res != tc.eq {
  670. t.Errorf("Case %d:\na: %v\nb: %v\na.IsEquivalent(b, %v, %v) => %v, expected %v", i, tc.a, tc.b, ignPerms, ignBlocks, res, tc.eq)
  671. }
  672. if res := tc.b.isEquivalent(tc.a, 0, ignPerms, ignBlocks, tc.ignFlags); res != tc.eq {
  673. t.Errorf("Case %d:\na: %v\nb: %v\nb.IsEquivalent(a, %v, %v) => %v, expected %v", i, tc.a, tc.b, ignPerms, ignBlocks, res, tc.eq)
  674. }
  675. }
  676. }
  677. }
  678. }
  679. func TestSha256OfEmptyBlock(t *testing.T) {
  680. // every block size should have a correct entry in sha256OfEmptyBlock
  681. for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
  682. expected := sha256.Sum256(make([]byte, blockSize))
  683. if sha256OfEmptyBlock[blockSize] != expected {
  684. t.Error("missing or wrong hash for block of size", blockSize)
  685. }
  686. }
  687. }
  688. // TestClusterConfigAfterClose checks that ClusterConfig does not deadlock when
  689. // ClusterConfig is called on a closed connection.
  690. func TestClusterConfigAfterClose(t *testing.T) {
  691. m := newTestModel()
  692. c := NewConnection(c0ID, &testutils.BlockingRW{}, &testutils.BlockingRW{}, m, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  693. c.Start()
  694. c.internalClose(errManual)
  695. done := make(chan struct{})
  696. go func() {
  697. c.ClusterConfig(ClusterConfig{})
  698. close(done)
  699. }()
  700. select {
  701. case <-done:
  702. case <-time.After(time.Second):
  703. t.Fatal("timed out before Cluster Config returned")
  704. }
  705. }
  706. func TestDispatcherToCloseDeadlock(t *testing.T) {
  707. // Verify that we don't deadlock when calling Close() from within one of
  708. // the model callbacks (ClusterConfig).
  709. m := newTestModel()
  710. c := NewConnection(c0ID, &testutils.BlockingRW{}, &testutils.NoopRW{}, m, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  711. m.ccFn = func(devID DeviceID, cc ClusterConfig) {
  712. c.Close(errManual)
  713. }
  714. c.Start()
  715. c.inbox <- &ClusterConfig{}
  716. select {
  717. case <-c.dispatcherLoopStopped:
  718. case <-time.After(time.Second):
  719. t.Fatal("timed out before dispatcher loop terminated")
  720. }
  721. }