protocol_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "io"
  11. "io/ioutil"
  12. "runtime"
  13. "sync"
  14. "testing"
  15. "testing/quick"
  16. "time"
  17. lz4 "github.com/bkaradzic/go-lz4"
  18. "github.com/syncthing/syncthing/lib/rand"
  19. "github.com/syncthing/syncthing/lib/testutils"
  20. )
  21. var (
  22. c0ID = NewDeviceID([]byte{1})
  23. c1ID = NewDeviceID([]byte{2})
  24. quickCfg = &quick.Config{}
  25. )
  26. func TestPing(t *testing.T) {
  27. ar, aw := io.Pipe()
  28. br, bw := io.Pipe()
  29. c0 := getRawConnection(NewConnection(c0ID, ar, bw, testutils.NoopCloser{}, newTestModel(), new(mockedConnectionInfo), CompressionAlways, nil))
  30. c0.Start()
  31. defer closeAndWait(c0, ar, bw)
  32. c1 := getRawConnection(NewConnection(c1ID, br, aw, testutils.NoopCloser{}, newTestModel(), new(mockedConnectionInfo), CompressionAlways, nil))
  33. c1.Start()
  34. defer closeAndWait(c1, ar, bw)
  35. c0.ClusterConfig(ClusterConfig{})
  36. c1.ClusterConfig(ClusterConfig{})
  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, testutils.NoopCloser{}, m0, new(mockedConnectionInfo), CompressionAlways, nil))
  51. c0.Start()
  52. defer closeAndWait(c0, ar, bw)
  53. c1 := NewConnection(c1ID, br, aw, testutils.NoopCloser{}, m1, new(mockedConnectionInfo), CompressionAlways, nil)
  54. c1.Start()
  55. defer closeAndWait(c1, ar, bw)
  56. c0.ClusterConfig(ClusterConfig{})
  57. c1.ClusterConfig(ClusterConfig{})
  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, "default", nil)
  69. c0.Index(ctx, "default", nil)
  70. if _, err := c0.Request(ctx, "default", "foo", 0, 0, 0, nil, 0, false); 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 := testutils.NewBlockingRW()
  85. c := getRawConnection(NewConnection(c0ID, rw, rw, testutils.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil))
  86. c.Start()
  87. defer closeAndWait(c, rw)
  88. wg := sync.WaitGroup{}
  89. wg.Add(1)
  90. go func() {
  91. c.ClusterConfig(ClusterConfig{})
  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(_ DeviceID, _ 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, testutils.NoopCloser{}, m0, new(mockedConnectionInfo), CompressionNever, nil))
  128. c0.Start()
  129. defer closeAndWait(c0, ar, bw)
  130. c1 := NewConnection(c1ID, br, aw, testutils.NoopCloser{}, m1, new(mockedConnectionInfo), CompressionNever, nil)
  131. c1.Start()
  132. defer closeAndWait(c1, ar, bw)
  133. c0.ClusterConfig(ClusterConfig{})
  134. c1.ClusterConfig(ClusterConfig{})
  135. c1.Index(context.Background(), "default", nil)
  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 := testutils.NewBlockingRW()
  160. c := getRawConnection(NewConnection(c0ID, rw, &testutils.NoopRW{}, testutils.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil))
  161. c.Start()
  162. defer closeAndWait(c, rw)
  163. select {
  164. case c.outbox <- asyncMessage{&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 setup after c.Start
  168. }
  169. c.ClusterConfig(ClusterConfig{})
  170. done := make(chan struct{})
  171. if ok := c.send(context.Background(), &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 := testutils.NewBlockingRW()
  203. c := getRawConnection(NewConnection(c0ID, rw, rw, testutils.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil))
  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 TestMarshalIndexMessage(t *testing.T) {
  218. if testing.Short() {
  219. quickCfg.MaxCount = 10
  220. }
  221. f := func(m1 Index) bool {
  222. if len(m1.Files) == 0 {
  223. m1.Files = nil
  224. }
  225. for i, f := range m1.Files {
  226. if len(f.BlocksHash) == 0 {
  227. m1.Files[i].BlocksHash = nil
  228. }
  229. if len(f.VersionHash) == 0 {
  230. m1.Files[i].VersionHash = nil
  231. }
  232. if len(f.Blocks) == 0 {
  233. m1.Files[i].Blocks = nil
  234. } else {
  235. for j := range f.Blocks {
  236. f.Blocks[j].Offset = 0
  237. if len(f.Blocks[j].Hash) == 0 {
  238. f.Blocks[j].Hash = nil
  239. }
  240. }
  241. }
  242. if len(f.Version.Counters) == 0 {
  243. m1.Files[i].Version.Counters = nil
  244. }
  245. if len(f.Encrypted) == 0 {
  246. m1.Files[i].Encrypted = nil
  247. }
  248. }
  249. return testMarshal(t, "index", &m1, &Index{})
  250. }
  251. if err := quick.Check(f, quickCfg); err != nil {
  252. t.Error(err)
  253. }
  254. }
  255. func TestMarshalRequestMessage(t *testing.T) {
  256. if testing.Short() {
  257. quickCfg.MaxCount = 10
  258. }
  259. f := func(m1 Request) bool {
  260. if len(m1.Hash) == 0 {
  261. m1.Hash = nil
  262. }
  263. return testMarshal(t, "request", &m1, &Request{})
  264. }
  265. if err := quick.Check(f, quickCfg); err != nil {
  266. t.Error(err)
  267. }
  268. }
  269. func TestMarshalResponseMessage(t *testing.T) {
  270. if testing.Short() {
  271. quickCfg.MaxCount = 10
  272. }
  273. f := func(m1 Response) bool {
  274. if len(m1.Data) == 0 {
  275. m1.Data = nil
  276. }
  277. return testMarshal(t, "response", &m1, &Response{})
  278. }
  279. if err := quick.Check(f, quickCfg); err != nil {
  280. t.Error(err)
  281. }
  282. }
  283. func TestMarshalClusterConfigMessage(t *testing.T) {
  284. if testing.Short() {
  285. quickCfg.MaxCount = 10
  286. }
  287. f := func(m1 ClusterConfig) bool {
  288. if len(m1.Folders) == 0 {
  289. m1.Folders = nil
  290. }
  291. for i := range m1.Folders {
  292. if len(m1.Folders[i].Devices) == 0 {
  293. m1.Folders[i].Devices = nil
  294. }
  295. for j := range m1.Folders[i].Devices {
  296. if len(m1.Folders[i].Devices[j].Addresses) == 0 {
  297. m1.Folders[i].Devices[j].Addresses = nil
  298. }
  299. if len(m1.Folders[i].Devices[j].EncryptionPasswordToken) == 0 {
  300. m1.Folders[i].Devices[j].EncryptionPasswordToken = nil
  301. }
  302. }
  303. }
  304. return testMarshal(t, "clusterconfig", &m1, &ClusterConfig{})
  305. }
  306. if err := quick.Check(f, quickCfg); err != nil {
  307. t.Error(err)
  308. }
  309. }
  310. func TestMarshalCloseMessage(t *testing.T) {
  311. if testing.Short() {
  312. quickCfg.MaxCount = 10
  313. }
  314. f := func(m1 Close) bool {
  315. return testMarshal(t, "close", &m1, &Close{})
  316. }
  317. if err := quick.Check(f, quickCfg); err != nil {
  318. t.Error(err)
  319. }
  320. }
  321. func TestMarshalFDPU(t *testing.T) {
  322. if testing.Short() {
  323. quickCfg.MaxCount = 10
  324. }
  325. f := func(m1 FileDownloadProgressUpdate) bool {
  326. if len(m1.Version.Counters) == 0 {
  327. m1.Version.Counters = nil
  328. }
  329. if len(m1.BlockIndexes) == 0 {
  330. m1.BlockIndexes = nil
  331. }
  332. return testMarshal(t, "fdpu", &m1, &FileDownloadProgressUpdate{})
  333. }
  334. if err := quick.Check(f, quickCfg); err != nil {
  335. t.Error(err)
  336. }
  337. }
  338. func TestUnmarshalFDPUv16v17(t *testing.T) {
  339. var fdpu FileDownloadProgressUpdate
  340. m0, _ := hex.DecodeString("08cda1e2e3011278f3918787f3b89b8af2958887f0aa9389f3a08588f3aa8f96f39aa8a5f48b9188f19286a0f3848da4f3aba799f3beb489f0a285b9f487b684f2a3bda2f48598b4f2938a89f2a28badf187a0a2f2aebdbdf4849494f4808fbbf2b3a2adf2bb95bff0a6ada4f198ab9af29a9c8bf1abb793f3baabb2f188a6ba1a0020bb9390f60220f6d9e42220b0c7e2b2fdffffffff0120fdb2dfcdfbffffffff0120cedab1d50120bd8784c0feffffffff0120ace99591fdffffffff0120eed7d09af9ffffffff01")
  341. if err := fdpu.Unmarshal(m0); err != nil {
  342. t.Fatal("Unmarshalling message from v0.14.16:", err)
  343. }
  344. m1, _ := hex.DecodeString("0880f1969905128401f099b192f0abb1b9f3b280aff19e9aa2f3b89e84f484b39df1a7a6b0f1aea4b1f0adac94f3b39caaf1939281f1928a8af0abb1b0f0a8b3b3f3a88e94f2bd85acf29c97a9f2969da6f0b7a188f1908ea2f09a9c9bf19d86a6f29aada8f389bb95f0bf9d88f1a09d89f1b1a4b5f29b9eabf298a59df1b2a589f2979ebdf0b69880f18986b21a440a1508c7d8fb8897ca93d90910e8c4d8e8f2f8f0ccee010a1508afa8ffd8c085b393c50110e5bdedc3bddefe9b0b0a1408a1bedddba4cac5da3c10b8e5d9958ca7e3ec19225ae2f88cb2f8ffffffff018ceda99cfbffffffff01b9c298a407e295e8e9fcffffffff01f3b9ade5fcffffffff01c08bfea9fdffffffff01a2c2e5e1ffffffffff0186dcc5dafdffffffff01e9ffc7e507c9d89db8fdffffffff01")
  345. if err := fdpu.Unmarshal(m1); err != nil {
  346. t.Fatal("Unmarshalling message from v0.14.16:", err)
  347. }
  348. }
  349. func testMarshal(t *testing.T, prefix string, m1, m2 message) bool {
  350. buf, err := m1.Marshal()
  351. if err != nil {
  352. t.Fatal(err)
  353. }
  354. err = m2.Unmarshal(buf)
  355. if err != nil {
  356. t.Fatal(err)
  357. }
  358. bs1, _ := json.MarshalIndent(m1, "", " ")
  359. bs2, _ := json.MarshalIndent(m2, "", " ")
  360. if !bytes.Equal(bs1, bs2) {
  361. ioutil.WriteFile(prefix+"-1.txt", bs1, 0644)
  362. ioutil.WriteFile(prefix+"-2.txt", bs2, 0644)
  363. return false
  364. }
  365. return true
  366. }
  367. func TestWriteCompressed(t *testing.T) {
  368. for _, random := range []bool{false, true} {
  369. buf := new(bytes.Buffer)
  370. c := &rawConnection{
  371. cr: &countingReader{Reader: buf},
  372. cw: &countingWriter{Writer: buf},
  373. compression: CompressionAlways,
  374. }
  375. msg := &Response{Data: make([]byte, 10240)}
  376. if random {
  377. // This should make the message uncompressible.
  378. rand.Read(msg.Data)
  379. }
  380. if err := c.writeMessage(msg); err != nil {
  381. t.Fatal(err)
  382. }
  383. got, err := c.readMessage(make([]byte, 4))
  384. if err != nil {
  385. t.Fatal(err)
  386. }
  387. if !bytes.Equal(got.(*Response).Data, msg.Data) {
  388. t.Error("received the wrong message")
  389. }
  390. hdr := Header{Type: c.typeOf(msg)}
  391. size := int64(2 + hdr.ProtoSize() + 4 + msg.ProtoSize())
  392. if c.cr.tot > size {
  393. t.Errorf("compression enlarged message from %d to %d",
  394. size, c.cr.tot)
  395. }
  396. }
  397. }
  398. func TestLZ4Compression(t *testing.T) {
  399. for i := 0; i < 10; i++ {
  400. dataLen := 150 + rand.Intn(150)
  401. data := make([]byte, dataLen)
  402. _, err := io.ReadFull(rand.Reader, data[100:])
  403. if err != nil {
  404. t.Fatal(err)
  405. }
  406. comp := make([]byte, lz4.CompressBound(dataLen))
  407. compLen, err := lz4Compress(data, comp)
  408. if err != nil {
  409. t.Errorf("compressing %d bytes: %v", dataLen, err)
  410. continue
  411. }
  412. res, err := lz4Decompress(comp[:compLen])
  413. if err != nil {
  414. t.Errorf("decompressing %d bytes to %d: %v", len(comp), dataLen, err)
  415. continue
  416. }
  417. if len(res) != len(data) {
  418. t.Errorf("Incorrect len %d != expected %d", len(res), len(data))
  419. }
  420. if !bytes.Equal(data, res) {
  421. t.Error("Incorrect decompressed data")
  422. }
  423. t.Logf("OK #%d, %d -> %d -> %d", i, dataLen, len(comp), dataLen)
  424. }
  425. }
  426. func TestCheckFilename(t *testing.T) {
  427. cases := []struct {
  428. name string
  429. ok bool
  430. }{
  431. // Valid filenames
  432. {"foo", true},
  433. {"foo/bar/baz", true},
  434. {"foo/bar:baz", true}, // colon is ok in general, will be filtered on windows
  435. {`\`, true}, // path separator on the wire is forward slash, so as above
  436. {`\.`, true},
  437. {`\..`, true},
  438. {".foo", true},
  439. {"foo..", true},
  440. // Invalid filenames
  441. {"foo/..", false},
  442. {"foo/../bar", false},
  443. {"../foo/../bar", false},
  444. {"", false},
  445. {".", false},
  446. {"..", false},
  447. {"/", false},
  448. {"/.", false},
  449. {"/..", false},
  450. {"/foo", false},
  451. {"./foo", false},
  452. {"foo./", false},
  453. {"foo/.", false},
  454. {"foo/", false},
  455. }
  456. for _, tc := range cases {
  457. err := checkFilename(tc.name)
  458. if (err == nil) != tc.ok {
  459. t.Errorf("Unexpected result for checkFilename(%q): %v", tc.name, err)
  460. }
  461. }
  462. }
  463. func TestCheckConsistency(t *testing.T) {
  464. cases := []struct {
  465. fi FileInfo
  466. ok bool
  467. }{
  468. {
  469. // valid
  470. fi: FileInfo{
  471. Name: "foo",
  472. Type: FileInfoTypeFile,
  473. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  474. },
  475. ok: true,
  476. },
  477. {
  478. // deleted with blocks
  479. fi: FileInfo{
  480. Name: "foo",
  481. Deleted: true,
  482. Type: FileInfoTypeFile,
  483. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  484. },
  485. ok: false,
  486. },
  487. {
  488. // no blocks
  489. fi: FileInfo{
  490. Name: "foo",
  491. Type: FileInfoTypeFile,
  492. },
  493. ok: false,
  494. },
  495. {
  496. // directory with blocks
  497. fi: FileInfo{
  498. Name: "foo",
  499. Type: FileInfoTypeDirectory,
  500. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  501. },
  502. ok: false,
  503. },
  504. }
  505. for _, tc := range cases {
  506. err := checkFileInfoConsistency(tc.fi)
  507. if tc.ok && err != nil {
  508. t.Errorf("Unexpected error %v (want nil) for %v", err, tc.fi)
  509. }
  510. if !tc.ok && err == nil {
  511. t.Errorf("Unexpected nil error for %v", tc.fi)
  512. }
  513. }
  514. }
  515. func TestBlockSize(t *testing.T) {
  516. cases := []struct {
  517. fileSize int64
  518. blockSize int
  519. }{
  520. {1 << KiB, 128 << KiB},
  521. {1 << MiB, 128 << KiB},
  522. {499 << MiB, 256 << KiB},
  523. {500 << MiB, 512 << KiB},
  524. {501 << MiB, 512 << KiB},
  525. {1 << GiB, 1 << MiB},
  526. {2 << GiB, 2 << MiB},
  527. {3 << GiB, 2 << MiB},
  528. {500 << GiB, 16 << MiB},
  529. {50000 << GiB, 16 << MiB},
  530. }
  531. for _, tc := range cases {
  532. size := BlockSize(tc.fileSize)
  533. if size != tc.blockSize {
  534. t.Errorf("BlockSize(%d), size=%d, expected %d", tc.fileSize, size, tc.blockSize)
  535. }
  536. }
  537. }
  538. var blockSize int
  539. func BenchmarkBlockSize(b *testing.B) {
  540. for i := 0; i < b.N; i++ {
  541. blockSize = BlockSize(16 << 30)
  542. }
  543. }
  544. func TestLocalFlagBits(t *testing.T) {
  545. var f FileInfo
  546. if f.IsIgnored() || f.MustRescan() || f.IsInvalid() {
  547. t.Error("file should have no weird bits set by default")
  548. }
  549. f.SetIgnored()
  550. if !f.IsIgnored() || f.MustRescan() || !f.IsInvalid() {
  551. t.Error("file should be ignored and invalid")
  552. }
  553. f.SetMustRescan()
  554. if f.IsIgnored() || !f.MustRescan() || !f.IsInvalid() {
  555. t.Error("file should be must-rescan and invalid")
  556. }
  557. f.SetUnsupported()
  558. if f.IsIgnored() || f.MustRescan() || !f.IsInvalid() {
  559. t.Error("file should be invalid")
  560. }
  561. }
  562. func TestIsEquivalent(t *testing.T) {
  563. b := func(v bool) *bool {
  564. return &v
  565. }
  566. type testCase struct {
  567. a FileInfo
  568. b FileInfo
  569. ignPerms *bool // nil means should not matter, we'll test both variants
  570. ignBlocks *bool
  571. ignFlags uint32
  572. eq bool
  573. }
  574. cases := []testCase{
  575. // Empty FileInfos are equivalent
  576. {eq: true},
  577. // Various basic attributes, all of which cause ineqality when
  578. // they differ
  579. {
  580. a: FileInfo{Name: "foo"},
  581. b: FileInfo{Name: "bar"},
  582. eq: false,
  583. },
  584. {
  585. a: FileInfo{Type: FileInfoTypeFile},
  586. b: FileInfo{Type: FileInfoTypeDirectory},
  587. eq: false,
  588. },
  589. {
  590. a: FileInfo{Size: 1234},
  591. b: FileInfo{Size: 2345},
  592. eq: false,
  593. },
  594. {
  595. a: FileInfo{Deleted: false},
  596. b: FileInfo{Deleted: true},
  597. eq: false,
  598. },
  599. {
  600. a: FileInfo{RawInvalid: false},
  601. b: FileInfo{RawInvalid: true},
  602. eq: false,
  603. },
  604. {
  605. a: FileInfo{ModifiedS: 1234},
  606. b: FileInfo{ModifiedS: 2345},
  607. eq: false,
  608. },
  609. {
  610. a: FileInfo{ModifiedNs: 1234},
  611. b: FileInfo{ModifiedNs: 2345},
  612. eq: false,
  613. },
  614. // Special handling of local flags and invalidity. "MustRescan"
  615. // files are never equivalent to each other. Otherwise, equivalence
  616. // is based just on whether the file becomes IsInvalid() or not, not
  617. // the specific reason or flag bits.
  618. {
  619. a: FileInfo{LocalFlags: FlagLocalMustRescan},
  620. b: FileInfo{LocalFlags: FlagLocalMustRescan},
  621. eq: false,
  622. },
  623. {
  624. a: FileInfo{RawInvalid: true},
  625. b: FileInfo{RawInvalid: true},
  626. eq: true,
  627. },
  628. {
  629. a: FileInfo{LocalFlags: FlagLocalUnsupported},
  630. b: FileInfo{LocalFlags: FlagLocalUnsupported},
  631. eq: true,
  632. },
  633. {
  634. a: FileInfo{RawInvalid: true},
  635. b: FileInfo{LocalFlags: FlagLocalUnsupported},
  636. eq: true,
  637. },
  638. {
  639. a: FileInfo{LocalFlags: 0},
  640. b: FileInfo{LocalFlags: FlagLocalReceiveOnly},
  641. eq: false,
  642. },
  643. {
  644. a: FileInfo{LocalFlags: 0},
  645. b: FileInfo{LocalFlags: FlagLocalReceiveOnly},
  646. ignFlags: FlagLocalReceiveOnly,
  647. eq: true,
  648. },
  649. // Difference in blocks is not OK
  650. {
  651. a: FileInfo{Blocks: []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}},
  652. b: FileInfo{Blocks: []BlockInfo{{Hash: []byte{2, 3, 4, 5}}}},
  653. ignBlocks: b(false),
  654. eq: false,
  655. },
  656. // ... unless we say it is
  657. {
  658. a: FileInfo{Blocks: []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}},
  659. b: FileInfo{Blocks: []BlockInfo{{Hash: []byte{2, 3, 4, 5}}}},
  660. ignBlocks: b(true),
  661. eq: true,
  662. },
  663. // Difference in permissions is not OK.
  664. {
  665. a: FileInfo{Permissions: 0444},
  666. b: FileInfo{Permissions: 0666},
  667. ignPerms: b(false),
  668. eq: false,
  669. },
  670. // ... unless we say it is
  671. {
  672. a: FileInfo{Permissions: 0666},
  673. b: FileInfo{Permissions: 0444},
  674. ignPerms: b(true),
  675. eq: true,
  676. },
  677. // These attributes are not checked at all
  678. {
  679. a: FileInfo{NoPermissions: false},
  680. b: FileInfo{NoPermissions: true},
  681. eq: true,
  682. },
  683. {
  684. a: FileInfo{Version: Vector{Counters: []Counter{{ID: 1, Value: 42}}}},
  685. b: FileInfo{Version: Vector{Counters: []Counter{{ID: 42, Value: 1}}}},
  686. eq: true,
  687. },
  688. {
  689. a: FileInfo{Sequence: 1},
  690. b: FileInfo{Sequence: 2},
  691. eq: true,
  692. },
  693. // The block size is not checked (but this would fail the blocks
  694. // check in real world)
  695. {
  696. a: FileInfo{RawBlockSize: 1},
  697. b: FileInfo{RawBlockSize: 2},
  698. eq: true,
  699. },
  700. // The symlink target is checked for symlinks
  701. {
  702. a: FileInfo{Type: FileInfoTypeSymlink, SymlinkTarget: "a"},
  703. b: FileInfo{Type: FileInfoTypeSymlink, SymlinkTarget: "b"},
  704. eq: false,
  705. },
  706. // ... but not for non-symlinks
  707. {
  708. a: FileInfo{Type: FileInfoTypeFile, SymlinkTarget: "a"},
  709. b: FileInfo{Type: FileInfoTypeFile, SymlinkTarget: "b"},
  710. eq: true,
  711. },
  712. }
  713. if runtime.GOOS == "windows" {
  714. // On windows we only check the user writable bit of the permission
  715. // set, so these are equivalent.
  716. cases = append(cases, testCase{
  717. a: FileInfo{Permissions: 0777},
  718. b: FileInfo{Permissions: 0600},
  719. ignPerms: b(false),
  720. eq: true,
  721. })
  722. }
  723. for i, tc := range cases {
  724. // Check the standard attributes with all permutations of the
  725. // special ignore flags, unless the value of those flags are given
  726. // in the tests.
  727. for _, ignPerms := range []bool{true, false} {
  728. for _, ignBlocks := range []bool{true, false} {
  729. if tc.ignPerms != nil && *tc.ignPerms != ignPerms {
  730. continue
  731. }
  732. if tc.ignBlocks != nil && *tc.ignBlocks != ignBlocks {
  733. continue
  734. }
  735. if res := tc.a.isEquivalent(tc.b, 0, ignPerms, ignBlocks, tc.ignFlags); res != tc.eq {
  736. 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)
  737. }
  738. if res := tc.b.isEquivalent(tc.a, 0, ignPerms, ignBlocks, tc.ignFlags); res != tc.eq {
  739. 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)
  740. }
  741. }
  742. }
  743. }
  744. }
  745. func TestSha256OfEmptyBlock(t *testing.T) {
  746. // every block size should have a correct entry in sha256OfEmptyBlock
  747. for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
  748. expected := sha256.Sum256(make([]byte, blockSize))
  749. if sha256OfEmptyBlock[blockSize] != expected {
  750. t.Error("missing or wrong hash for block of size", blockSize)
  751. }
  752. }
  753. }
  754. // TestClusterConfigAfterClose checks that ClusterConfig does not deadlock when
  755. // ClusterConfig is called on a closed connection.
  756. func TestClusterConfigAfterClose(t *testing.T) {
  757. m := newTestModel()
  758. rw := testutils.NewBlockingRW()
  759. c := getRawConnection(NewConnection(c0ID, rw, rw, testutils.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil))
  760. c.Start()
  761. defer closeAndWait(c, rw)
  762. c.internalClose(errManual)
  763. done := make(chan struct{})
  764. go func() {
  765. c.ClusterConfig(ClusterConfig{})
  766. close(done)
  767. }()
  768. select {
  769. case <-done:
  770. case <-time.After(time.Second):
  771. t.Fatal("timed out before Cluster Config returned")
  772. }
  773. }
  774. func TestDispatcherToCloseDeadlock(t *testing.T) {
  775. // Verify that we don't deadlock when calling Close() from within one of
  776. // the model callbacks (ClusterConfig).
  777. m := newTestModel()
  778. rw := testutils.NewBlockingRW()
  779. c := getRawConnection(NewConnection(c0ID, rw, &testutils.NoopRW{}, testutils.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil))
  780. m.ccFn = func(devID DeviceID, cc ClusterConfig) {
  781. c.Close(errManual)
  782. }
  783. c.Start()
  784. defer closeAndWait(c, rw)
  785. c.inbox <- &ClusterConfig{}
  786. select {
  787. case <-c.dispatcherLoopStopped:
  788. case <-time.After(time.Second):
  789. t.Fatal("timed out before dispatcher loop terminated")
  790. }
  791. }
  792. func TestBlocksEqual(t *testing.T) {
  793. blocksOne := []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}
  794. blocksTwo := []BlockInfo{{Hash: []byte{5, 6, 7, 8}}}
  795. hashOne := []byte{42, 42, 42, 42}
  796. hashTwo := []byte{29, 29, 29, 29}
  797. cases := []struct {
  798. b1 []BlockInfo
  799. h1 []byte
  800. b2 []BlockInfo
  801. h2 []byte
  802. eq bool
  803. }{
  804. {blocksOne, hashOne, blocksOne, hashOne, true}, // everything equal
  805. {blocksOne, hashOne, blocksTwo, hashTwo, false}, // nothing equal
  806. {blocksOne, hashOne, blocksOne, nil, true}, // blocks compared
  807. {blocksOne, nil, blocksOne, nil, true}, // blocks compared
  808. {blocksOne, nil, blocksTwo, nil, false}, // blocks compared
  809. {blocksOne, hashOne, blocksTwo, hashOne, true}, // hashes equal, blocks not looked at
  810. {blocksOne, hashOne, blocksOne, hashTwo, true}, // hashes different, blocks compared
  811. {blocksOne, hashOne, blocksTwo, hashTwo, false}, // hashes different, blocks compared
  812. {blocksOne, hashOne, nil, nil, false}, // blocks is different from no blocks
  813. {blocksOne, nil, nil, nil, false}, // blocks is different from no blocks
  814. {nil, hashOne, nil, nil, true}, // nil blocks are equal, even of one side has a hash
  815. }
  816. for _, tc := range cases {
  817. f1 := FileInfo{Blocks: tc.b1, BlocksHash: tc.h1}
  818. f2 := FileInfo{Blocks: tc.b2, BlocksHash: tc.h2}
  819. if !f1.BlocksEqual(f1) {
  820. t.Error("f1 is always equal to itself", f1)
  821. }
  822. if !f2.BlocksEqual(f2) {
  823. t.Error("f2 is always equal to itself", f2)
  824. }
  825. if res := f1.BlocksEqual(f2); res != tc.eq {
  826. t.Log("f1", f1.BlocksHash, f1.Blocks)
  827. t.Log("f2", f2.BlocksHash, f2.Blocks)
  828. t.Errorf("f1.BlocksEqual(f2) == %v but should be %v", res, tc.eq)
  829. }
  830. if res := f2.BlocksEqual(f1); res != tc.eq {
  831. t.Log("f1", f1.BlocksHash, f1.Blocks)
  832. t.Log("f2", f2.BlocksHash, f2.Blocks)
  833. t.Errorf("f2.BlocksEqual(f1) == %v but should be %v", res, tc.eq)
  834. }
  835. }
  836. }
  837. func TestIndexIDString(t *testing.T) {
  838. // Index ID is a 64 bit, zero padded hex integer.
  839. var i IndexID = 42
  840. if i.String() != "0x000000000000002A" {
  841. t.Error(i.String())
  842. }
  843. }
  844. func closeAndWait(c interface{}, closers ...io.Closer) {
  845. for _, closer := range closers {
  846. closer.Close()
  847. }
  848. var raw *rawConnection
  849. switch i := c.(type) {
  850. case *rawConnection:
  851. raw = i
  852. default:
  853. raw = getRawConnection(c.(Connection))
  854. }
  855. raw.internalClose(ErrClosed)
  856. raw.loopWG.Wait()
  857. }
  858. func getRawConnection(c Connection) *rawConnection {
  859. var raw *rawConnection
  860. switch i := c.(type) {
  861. case wireFormatConnection:
  862. raw = i.Connection.(encryptedConnection).conn
  863. case encryptedConnection:
  864. raw = i.conn
  865. }
  866. return raw
  867. }