1
0

protocol_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. "os"
  12. "sync"
  13. "testing"
  14. "testing/quick"
  15. "time"
  16. lz4 "github.com/pierrec/lz4/v4"
  17. "github.com/syncthing/syncthing/lib/build"
  18. "github.com/syncthing/syncthing/lib/rand"
  19. "github.com/syncthing/syncthing/lib/testutil"
  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, testutil.NoopCloser{}, newTestModel(), new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen))
  30. c0.Start()
  31. defer closeAndWait(c0, ar, bw)
  32. c1 := getRawConnection(NewConnection(c1ID, br, aw, testutil.NoopCloser{}, newTestModel(), new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen))
  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, testutil.NoopCloser{}, m0, new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen))
  51. c0.Start()
  52. defer closeAndWait(c0, ar, bw)
  53. c1 := NewConnection(c1ID, br, aw, testutil.NoopCloser{}, m1, new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen)
  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 := testutil.NewBlockingRW()
  85. c := getRawConnection(NewConnection(c0ID, rw, rw, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen))
  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(string, []FileInfo) {
  121. close(indexReceived)
  122. <-unblockIndex
  123. }
  124. m1 := newTestModel()
  125. ar, aw := io.Pipe()
  126. br, bw := io.Pipe()
  127. c0 := getRawConnection(NewConnection(c0ID, ar, bw, testutil.NoopCloser{}, m0, new(mockedConnectionInfo), CompressionNever, nil, testKeyGen))
  128. c0.Start()
  129. defer closeAndWait(c0, ar, bw)
  130. c1 := NewConnection(c1ID, br, aw, testutil.NoopCloser{}, m1, new(mockedConnectionInfo), CompressionNever, nil, testKeyGen)
  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 := testutil.NewBlockingRW()
  160. c := getRawConnection(NewConnection(c0ID, rw, &testutil.NoopRW{}, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen))
  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 := testutil.NewBlockingRW()
  203. c := getRawConnection(NewConnection(c0ID, rw, rw, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen))
  204. c.Start()
  205. defer closeAndWait(c, rw)
  206. done := make(chan struct{})
  207. go func() {
  208. c.Close(errManual)
  209. close(done)
  210. }()
  211. select {
  212. case <-done:
  213. case <-time.After(5 * CloseTimeout):
  214. t.Fatal("timed out before Close returned")
  215. }
  216. }
  217. func 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. os.WriteFile(prefix+"-1.txt", bs1, 0o644)
  362. os.WriteFile(prefix+"-2.txt", bs2, 0o644)
  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: 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.CompressBlockBound(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 TestLZ4CompressionUpdate(t *testing.T) {
  427. uncompressed := []byte("this is some arbitrary yet fairly compressible data")
  428. // Compressed, as created by the LZ4 implementation in Syncthing 1.18.6 and earlier.
  429. oldCompressed, _ := hex.DecodeString("00000033f0247468697320697320736f6d65206172626974726172792079657420666169726c7920636f6d707265737369626c652064617461")
  430. // Verify that we can decompress
  431. res, err := lz4Decompress(oldCompressed)
  432. if err != nil {
  433. t.Fatal(err)
  434. }
  435. if !bytes.Equal(uncompressed, res) {
  436. t.Fatal("result does not match")
  437. }
  438. // Verify that our current compression is equivalent
  439. buf := make([]byte, 128)
  440. n, err := lz4Compress(uncompressed, buf)
  441. if err != nil {
  442. t.Fatal(err)
  443. }
  444. if !bytes.Equal(oldCompressed, buf[:n]) {
  445. t.Logf("%x", oldCompressed)
  446. t.Logf("%x", buf[:n])
  447. t.Fatal("compression does not match")
  448. }
  449. }
  450. func TestCheckFilename(t *testing.T) {
  451. cases := []struct {
  452. name string
  453. ok bool
  454. }{
  455. // Valid filenames
  456. {"foo", true},
  457. {"foo/bar/baz", true},
  458. {"foo/bar:baz", true}, // colon is ok in general, will be filtered on windows
  459. {`\`, true}, // path separator on the wire is forward slash, so as above
  460. {`\.`, true},
  461. {`\..`, true},
  462. {".foo", true},
  463. {"foo..", true},
  464. // Invalid filenames
  465. {"foo/..", false},
  466. {"foo/../bar", false},
  467. {"../foo/../bar", false},
  468. {"", false},
  469. {".", false},
  470. {"..", false},
  471. {"/", false},
  472. {"/.", false},
  473. {"/..", false},
  474. {"/foo", false},
  475. {"./foo", false},
  476. {"foo./", false},
  477. {"foo/.", false},
  478. {"foo/", false},
  479. }
  480. for _, tc := range cases {
  481. err := checkFilename(tc.name)
  482. if (err == nil) != tc.ok {
  483. t.Errorf("Unexpected result for checkFilename(%q): %v", tc.name, err)
  484. }
  485. }
  486. }
  487. func TestCheckConsistency(t *testing.T) {
  488. cases := []struct {
  489. fi FileInfo
  490. ok bool
  491. }{
  492. {
  493. // valid
  494. fi: FileInfo{
  495. Name: "foo",
  496. Type: FileInfoTypeFile,
  497. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  498. },
  499. ok: true,
  500. },
  501. {
  502. // deleted with blocks
  503. fi: FileInfo{
  504. Name: "foo",
  505. Deleted: true,
  506. Type: FileInfoTypeFile,
  507. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  508. },
  509. ok: false,
  510. },
  511. {
  512. // no blocks
  513. fi: FileInfo{
  514. Name: "foo",
  515. Type: FileInfoTypeFile,
  516. },
  517. ok: false,
  518. },
  519. {
  520. // directory with blocks
  521. fi: FileInfo{
  522. Name: "foo",
  523. Type: FileInfoTypeDirectory,
  524. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  525. },
  526. ok: false,
  527. },
  528. }
  529. for _, tc := range cases {
  530. err := checkFileInfoConsistency(tc.fi)
  531. if tc.ok && err != nil {
  532. t.Errorf("Unexpected error %v (want nil) for %v", err, tc.fi)
  533. }
  534. if !tc.ok && err == nil {
  535. t.Errorf("Unexpected nil error for %v", tc.fi)
  536. }
  537. }
  538. }
  539. func TestBlockSize(t *testing.T) {
  540. cases := []struct {
  541. fileSize int64
  542. blockSize int
  543. }{
  544. {1 << KiB, 128 << KiB},
  545. {1 << MiB, 128 << KiB},
  546. {499 << MiB, 256 << KiB},
  547. {500 << MiB, 512 << KiB},
  548. {501 << MiB, 512 << KiB},
  549. {1 << GiB, 1 << MiB},
  550. {2 << GiB, 2 << MiB},
  551. {3 << GiB, 2 << MiB},
  552. {500 << GiB, 16 << MiB},
  553. {50000 << GiB, 16 << MiB},
  554. }
  555. for _, tc := range cases {
  556. size := BlockSize(tc.fileSize)
  557. if size != tc.blockSize {
  558. t.Errorf("BlockSize(%d), size=%d, expected %d", tc.fileSize, size, tc.blockSize)
  559. }
  560. }
  561. }
  562. var blockSize int
  563. func BenchmarkBlockSize(b *testing.B) {
  564. for i := 0; i < b.N; i++ {
  565. blockSize = BlockSize(16 << 30)
  566. }
  567. }
  568. func TestLocalFlagBits(t *testing.T) {
  569. var f FileInfo
  570. if f.IsIgnored() || f.MustRescan() || f.IsInvalid() {
  571. t.Error("file should have no weird bits set by default")
  572. }
  573. f.SetIgnored()
  574. if !f.IsIgnored() || f.MustRescan() || !f.IsInvalid() {
  575. t.Error("file should be ignored and invalid")
  576. }
  577. f.SetMustRescan()
  578. if f.IsIgnored() || !f.MustRescan() || !f.IsInvalid() {
  579. t.Error("file should be must-rescan and invalid")
  580. }
  581. f.SetUnsupported()
  582. if f.IsIgnored() || f.MustRescan() || !f.IsInvalid() {
  583. t.Error("file should be invalid")
  584. }
  585. }
  586. func TestIsEquivalent(t *testing.T) {
  587. b := func(v bool) *bool {
  588. return &v
  589. }
  590. type testCase struct {
  591. a FileInfo
  592. b FileInfo
  593. ignPerms *bool // nil means should not matter, we'll test both variants
  594. ignBlocks *bool
  595. ignFlags uint32
  596. eq bool
  597. }
  598. cases := []testCase{
  599. // Empty FileInfos are equivalent
  600. {eq: true},
  601. // Various basic attributes, all of which cause inequality when
  602. // they differ
  603. {
  604. a: FileInfo{Name: "foo"},
  605. b: FileInfo{Name: "bar"},
  606. eq: false,
  607. },
  608. {
  609. a: FileInfo{Type: FileInfoTypeFile},
  610. b: FileInfo{Type: FileInfoTypeDirectory},
  611. eq: false,
  612. },
  613. {
  614. a: FileInfo{Size: 1234},
  615. b: FileInfo{Size: 2345},
  616. eq: false,
  617. },
  618. {
  619. a: FileInfo{Deleted: false},
  620. b: FileInfo{Deleted: true},
  621. eq: false,
  622. },
  623. {
  624. a: FileInfo{RawInvalid: false},
  625. b: FileInfo{RawInvalid: true},
  626. eq: false,
  627. },
  628. {
  629. a: FileInfo{ModifiedS: 1234},
  630. b: FileInfo{ModifiedS: 2345},
  631. eq: false,
  632. },
  633. {
  634. a: FileInfo{ModifiedNs: 1234},
  635. b: FileInfo{ModifiedNs: 2345},
  636. eq: false,
  637. },
  638. // Special handling of local flags and invalidity. "MustRescan"
  639. // files are never equivalent to each other. Otherwise, equivalence
  640. // is based just on whether the file becomes IsInvalid() or not, not
  641. // the specific reason or flag bits.
  642. {
  643. a: FileInfo{LocalFlags: FlagLocalMustRescan},
  644. b: FileInfo{LocalFlags: FlagLocalMustRescan},
  645. eq: false,
  646. },
  647. {
  648. a: FileInfo{RawInvalid: true},
  649. b: FileInfo{RawInvalid: true},
  650. eq: true,
  651. },
  652. {
  653. a: FileInfo{LocalFlags: FlagLocalUnsupported},
  654. b: FileInfo{LocalFlags: FlagLocalUnsupported},
  655. eq: true,
  656. },
  657. {
  658. a: FileInfo{RawInvalid: true},
  659. b: FileInfo{LocalFlags: FlagLocalUnsupported},
  660. eq: true,
  661. },
  662. {
  663. a: FileInfo{LocalFlags: 0},
  664. b: FileInfo{LocalFlags: FlagLocalReceiveOnly},
  665. eq: false,
  666. },
  667. {
  668. a: FileInfo{LocalFlags: 0},
  669. b: FileInfo{LocalFlags: FlagLocalReceiveOnly},
  670. ignFlags: FlagLocalReceiveOnly,
  671. eq: true,
  672. },
  673. // Difference in blocks is not OK
  674. {
  675. a: FileInfo{Blocks: []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}},
  676. b: FileInfo{Blocks: []BlockInfo{{Hash: []byte{2, 3, 4, 5}}}},
  677. ignBlocks: b(false),
  678. eq: false,
  679. },
  680. // ... unless we say it is
  681. {
  682. a: FileInfo{Blocks: []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}},
  683. b: FileInfo{Blocks: []BlockInfo{{Hash: []byte{2, 3, 4, 5}}}},
  684. ignBlocks: b(true),
  685. eq: true,
  686. },
  687. // Difference in permissions is not OK.
  688. {
  689. a: FileInfo{Permissions: 0o444},
  690. b: FileInfo{Permissions: 0o666},
  691. ignPerms: b(false),
  692. eq: false,
  693. },
  694. // ... unless we say it is
  695. {
  696. a: FileInfo{Permissions: 0o666},
  697. b: FileInfo{Permissions: 0o444},
  698. ignPerms: b(true),
  699. eq: true,
  700. },
  701. // These attributes are not checked at all
  702. {
  703. a: FileInfo{NoPermissions: false},
  704. b: FileInfo{NoPermissions: true},
  705. eq: true,
  706. },
  707. {
  708. a: FileInfo{Version: Vector{Counters: []Counter{{ID: 1, Value: 42}}}},
  709. b: FileInfo{Version: Vector{Counters: []Counter{{ID: 42, Value: 1}}}},
  710. eq: true,
  711. },
  712. {
  713. a: FileInfo{Sequence: 1},
  714. b: FileInfo{Sequence: 2},
  715. eq: true,
  716. },
  717. // The block size is not checked (but this would fail the blocks
  718. // check in real world)
  719. {
  720. a: FileInfo{RawBlockSize: 1},
  721. b: FileInfo{RawBlockSize: 2},
  722. eq: true,
  723. },
  724. // The symlink target is checked for symlinks
  725. {
  726. a: FileInfo{Type: FileInfoTypeSymlink, SymlinkTarget: "a"},
  727. b: FileInfo{Type: FileInfoTypeSymlink, SymlinkTarget: "b"},
  728. eq: false,
  729. },
  730. // ... but not for non-symlinks
  731. {
  732. a: FileInfo{Type: FileInfoTypeFile, SymlinkTarget: "a"},
  733. b: FileInfo{Type: FileInfoTypeFile, SymlinkTarget: "b"},
  734. eq: true,
  735. },
  736. }
  737. if build.IsWindows {
  738. // On windows we only check the user writable bit of the permission
  739. // set, so these are equivalent.
  740. cases = append(cases, testCase{
  741. a: FileInfo{Permissions: 0o777},
  742. b: FileInfo{Permissions: 0o600},
  743. ignPerms: b(false),
  744. eq: true,
  745. })
  746. }
  747. for i, tc := range cases {
  748. // Check the standard attributes with all permutations of the
  749. // special ignore flags, unless the value of those flags are given
  750. // in the tests.
  751. for _, ignPerms := range []bool{true, false} {
  752. for _, ignBlocks := range []bool{true, false} {
  753. if tc.ignPerms != nil && *tc.ignPerms != ignPerms {
  754. continue
  755. }
  756. if tc.ignBlocks != nil && *tc.ignBlocks != ignBlocks {
  757. continue
  758. }
  759. if res := tc.a.isEquivalent(tc.b, FileInfoComparison{IgnorePerms: ignPerms, IgnoreBlocks: ignBlocks, IgnoreFlags: tc.ignFlags}); res != tc.eq {
  760. 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)
  761. }
  762. if res := tc.b.isEquivalent(tc.a, FileInfoComparison{IgnorePerms: ignPerms, IgnoreBlocks: ignBlocks, IgnoreFlags: tc.ignFlags}); res != tc.eq {
  763. 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)
  764. }
  765. }
  766. }
  767. }
  768. }
  769. func TestSha256OfEmptyBlock(t *testing.T) {
  770. // every block size should have a correct entry in sha256OfEmptyBlock
  771. for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
  772. expected := sha256.Sum256(make([]byte, blockSize))
  773. if sha256OfEmptyBlock[blockSize] != expected {
  774. t.Error("missing or wrong hash for block of size", blockSize)
  775. }
  776. }
  777. }
  778. // TestClusterConfigAfterClose checks that ClusterConfig does not deadlock when
  779. // ClusterConfig is called on a closed connection.
  780. func TestClusterConfigAfterClose(t *testing.T) {
  781. m := newTestModel()
  782. rw := testutil.NewBlockingRW()
  783. c := getRawConnection(NewConnection(c0ID, rw, rw, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen))
  784. c.Start()
  785. defer closeAndWait(c, rw)
  786. c.internalClose(errManual)
  787. done := make(chan struct{})
  788. go func() {
  789. c.ClusterConfig(ClusterConfig{})
  790. close(done)
  791. }()
  792. select {
  793. case <-done:
  794. case <-time.After(time.Second):
  795. t.Fatal("timed out before Cluster Config returned")
  796. }
  797. }
  798. func TestDispatcherToCloseDeadlock(t *testing.T) {
  799. // Verify that we don't deadlock when calling Close() from within one of
  800. // the model callbacks (ClusterConfig).
  801. m := newTestModel()
  802. rw := testutil.NewBlockingRW()
  803. c := getRawConnection(NewConnection(c0ID, rw, &testutil.NoopRW{}, testutil.NoopCloser{}, m, new(mockedConnectionInfo), CompressionAlways, nil, testKeyGen))
  804. m.ccFn = func(ClusterConfig) {
  805. c.Close(errManual)
  806. }
  807. c.Start()
  808. defer closeAndWait(c, rw)
  809. c.inbox <- &ClusterConfig{}
  810. select {
  811. case <-c.dispatcherLoopStopped:
  812. case <-time.After(time.Second):
  813. t.Fatal("timed out before dispatcher loop terminated")
  814. }
  815. }
  816. func TestBlocksEqual(t *testing.T) {
  817. blocksOne := []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}
  818. blocksTwo := []BlockInfo{{Hash: []byte{5, 6, 7, 8}}}
  819. hashOne := []byte{42, 42, 42, 42}
  820. hashTwo := []byte{29, 29, 29, 29}
  821. cases := []struct {
  822. b1 []BlockInfo
  823. h1 []byte
  824. b2 []BlockInfo
  825. h2 []byte
  826. eq bool
  827. }{
  828. {blocksOne, hashOne, blocksOne, hashOne, true}, // everything equal
  829. {blocksOne, hashOne, blocksTwo, hashTwo, false}, // nothing equal
  830. {blocksOne, hashOne, blocksOne, nil, true}, // blocks compared
  831. {blocksOne, nil, blocksOne, nil, true}, // blocks compared
  832. {blocksOne, nil, blocksTwo, nil, false}, // blocks compared
  833. {blocksOne, hashOne, blocksTwo, hashOne, true}, // hashes equal, blocks not looked at
  834. {blocksOne, hashOne, blocksOne, hashTwo, true}, // hashes different, blocks compared
  835. {blocksOne, hashOne, blocksTwo, hashTwo, false}, // hashes different, blocks compared
  836. {blocksOne, hashOne, nil, nil, false}, // blocks is different from no blocks
  837. {blocksOne, nil, nil, nil, false}, // blocks is different from no blocks
  838. {nil, hashOne, nil, nil, true}, // nil blocks are equal, even of one side has a hash
  839. }
  840. for _, tc := range cases {
  841. f1 := FileInfo{Blocks: tc.b1, BlocksHash: tc.h1}
  842. f2 := FileInfo{Blocks: tc.b2, BlocksHash: tc.h2}
  843. if !f1.BlocksEqual(f1) {
  844. t.Error("f1 is always equal to itself", f1)
  845. }
  846. if !f2.BlocksEqual(f2) {
  847. t.Error("f2 is always equal to itself", f2)
  848. }
  849. if res := f1.BlocksEqual(f2); res != tc.eq {
  850. t.Log("f1", f1.BlocksHash, f1.Blocks)
  851. t.Log("f2", f2.BlocksHash, f2.Blocks)
  852. t.Errorf("f1.BlocksEqual(f2) == %v but should be %v", res, tc.eq)
  853. }
  854. if res := f2.BlocksEqual(f1); res != tc.eq {
  855. t.Log("f1", f1.BlocksHash, f1.Blocks)
  856. t.Log("f2", f2.BlocksHash, f2.Blocks)
  857. t.Errorf("f2.BlocksEqual(f1) == %v but should be %v", res, tc.eq)
  858. }
  859. }
  860. }
  861. func TestIndexIDString(t *testing.T) {
  862. // Index ID is a 64 bit, zero padded hex integer.
  863. var i IndexID = 42
  864. if i.String() != "0x000000000000002A" {
  865. t.Error(i.String())
  866. }
  867. }
  868. func closeAndWait(c interface{}, closers ...io.Closer) {
  869. for _, closer := range closers {
  870. closer.Close()
  871. }
  872. var raw *rawConnection
  873. switch i := c.(type) {
  874. case *rawConnection:
  875. raw = i
  876. default:
  877. raw = getRawConnection(c.(Connection))
  878. }
  879. raw.internalClose(ErrClosed)
  880. raw.loopWG.Wait()
  881. }
  882. func getRawConnection(c Connection) *rawConnection {
  883. var raw *rawConnection
  884. switch i := c.(type) {
  885. case wireFormatConnection:
  886. raw = i.Connection.(encryptedConnection).conn
  887. case encryptedConnection:
  888. raw = i.conn
  889. }
  890. return raw
  891. }