protocol_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "bytes"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "io"
  9. "io/ioutil"
  10. "runtime"
  11. "strings"
  12. "testing"
  13. "testing/quick"
  14. "github.com/syncthing/syncthing/lib/rand"
  15. )
  16. var (
  17. c0ID = NewDeviceID([]byte{1})
  18. c1ID = NewDeviceID([]byte{2})
  19. quickCfg = &quick.Config{}
  20. )
  21. func TestPing(t *testing.T) {
  22. ar, aw := io.Pipe()
  23. br, bw := io.Pipe()
  24. c0 := NewConnection(c0ID, ar, bw, newTestModel(), "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  25. c0.Start()
  26. c1 := NewConnection(c1ID, br, aw, newTestModel(), "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  27. c1.Start()
  28. c0.ClusterConfig(ClusterConfig{})
  29. c1.ClusterConfig(ClusterConfig{})
  30. if ok := c0.ping(); !ok {
  31. t.Error("c0 ping failed")
  32. }
  33. if ok := c1.ping(); !ok {
  34. t.Error("c1 ping failed")
  35. }
  36. }
  37. func TestClose(t *testing.T) {
  38. m0 := newTestModel()
  39. m1 := newTestModel()
  40. ar, aw := io.Pipe()
  41. br, bw := io.Pipe()
  42. c0 := NewConnection(c0ID, ar, bw, m0, "name", CompressAlways).(wireFormatConnection).Connection.(*rawConnection)
  43. c0.Start()
  44. c1 := NewConnection(c1ID, br, aw, m1, "name", CompressAlways)
  45. c1.Start()
  46. c0.ClusterConfig(ClusterConfig{})
  47. c1.ClusterConfig(ClusterConfig{})
  48. c0.internalClose(errors.New("manual close"))
  49. <-c0.closed
  50. if err := m0.closedError(); err == nil || !strings.Contains(err.Error(), "manual close") {
  51. t.Fatal("Connection should be closed")
  52. }
  53. // None of these should panic, some should return an error
  54. if c0.ping() {
  55. t.Error("Ping should not return true")
  56. }
  57. c0.Index("default", nil)
  58. c0.Index("default", nil)
  59. if _, err := c0.Request("default", "foo", 0, 0, nil, 0, false); err == nil {
  60. t.Error("Request should return an error")
  61. }
  62. }
  63. func TestMarshalIndexMessage(t *testing.T) {
  64. if testing.Short() {
  65. quickCfg.MaxCount = 10
  66. }
  67. f := func(m1 Index) bool {
  68. if len(m1.Files) == 0 {
  69. m1.Files = nil
  70. }
  71. for i, f := range m1.Files {
  72. if len(f.Blocks) == 0 {
  73. m1.Files[i].Blocks = nil
  74. } else {
  75. for j := range f.Blocks {
  76. f.Blocks[j].Offset = 0
  77. if len(f.Blocks[j].Hash) == 0 {
  78. f.Blocks[j].Hash = nil
  79. }
  80. }
  81. }
  82. if len(f.Version.Counters) == 0 {
  83. m1.Files[i].Version.Counters = nil
  84. }
  85. }
  86. return testMarshal(t, "index", &m1, &Index{})
  87. }
  88. if err := quick.Check(f, quickCfg); err != nil {
  89. t.Error(err)
  90. }
  91. }
  92. func TestMarshalRequestMessage(t *testing.T) {
  93. if testing.Short() {
  94. quickCfg.MaxCount = 10
  95. }
  96. f := func(m1 Request) bool {
  97. if len(m1.Hash) == 0 {
  98. m1.Hash = nil
  99. }
  100. return testMarshal(t, "request", &m1, &Request{})
  101. }
  102. if err := quick.Check(f, quickCfg); err != nil {
  103. t.Error(err)
  104. }
  105. }
  106. func TestMarshalResponseMessage(t *testing.T) {
  107. if testing.Short() {
  108. quickCfg.MaxCount = 10
  109. }
  110. f := func(m1 Response) bool {
  111. if len(m1.Data) == 0 {
  112. m1.Data = nil
  113. }
  114. return testMarshal(t, "response", &m1, &Response{})
  115. }
  116. if err := quick.Check(f, quickCfg); err != nil {
  117. t.Error(err)
  118. }
  119. }
  120. func TestMarshalClusterConfigMessage(t *testing.T) {
  121. if testing.Short() {
  122. quickCfg.MaxCount = 10
  123. }
  124. f := func(m1 ClusterConfig) bool {
  125. if len(m1.Folders) == 0 {
  126. m1.Folders = nil
  127. }
  128. for i := range m1.Folders {
  129. if len(m1.Folders[i].Devices) == 0 {
  130. m1.Folders[i].Devices = nil
  131. }
  132. }
  133. return testMarshal(t, "clusterconfig", &m1, &ClusterConfig{})
  134. }
  135. if err := quick.Check(f, quickCfg); err != nil {
  136. t.Error(err)
  137. }
  138. }
  139. func TestMarshalCloseMessage(t *testing.T) {
  140. if testing.Short() {
  141. quickCfg.MaxCount = 10
  142. }
  143. f := func(m1 Close) bool {
  144. return testMarshal(t, "close", &m1, &Close{})
  145. }
  146. if err := quick.Check(f, quickCfg); err != nil {
  147. t.Error(err)
  148. }
  149. }
  150. func TestMarshalFDPU(t *testing.T) {
  151. if testing.Short() {
  152. quickCfg.MaxCount = 10
  153. }
  154. f := func(m1 FileDownloadProgressUpdate) bool {
  155. if len(m1.Version.Counters) == 0 {
  156. m1.Version.Counters = nil
  157. }
  158. return testMarshal(t, "close", &m1, &FileDownloadProgressUpdate{})
  159. }
  160. if err := quick.Check(f, quickCfg); err != nil {
  161. t.Error(err)
  162. }
  163. }
  164. func TestUnmarshalFDPUv16v17(t *testing.T) {
  165. var fdpu FileDownloadProgressUpdate
  166. m0, _ := hex.DecodeString("08cda1e2e3011278f3918787f3b89b8af2958887f0aa9389f3a08588f3aa8f96f39aa8a5f48b9188f19286a0f3848da4f3aba799f3beb489f0a285b9f487b684f2a3bda2f48598b4f2938a89f2a28badf187a0a2f2aebdbdf4849494f4808fbbf2b3a2adf2bb95bff0a6ada4f198ab9af29a9c8bf1abb793f3baabb2f188a6ba1a0020bb9390f60220f6d9e42220b0c7e2b2fdffffffff0120fdb2dfcdfbffffffff0120cedab1d50120bd8784c0feffffffff0120ace99591fdffffffff0120eed7d09af9ffffffff01")
  167. if err := fdpu.Unmarshal(m0); err != nil {
  168. t.Fatal("Unmarshalling message from v0.14.16:", err)
  169. }
  170. m1, _ := hex.DecodeString("0880f1969905128401f099b192f0abb1b9f3b280aff19e9aa2f3b89e84f484b39df1a7a6b0f1aea4b1f0adac94f3b39caaf1939281f1928a8af0abb1b0f0a8b3b3f3a88e94f2bd85acf29c97a9f2969da6f0b7a188f1908ea2f09a9c9bf19d86a6f29aada8f389bb95f0bf9d88f1a09d89f1b1a4b5f29b9eabf298a59df1b2a589f2979ebdf0b69880f18986b21a440a1508c7d8fb8897ca93d90910e8c4d8e8f2f8f0ccee010a1508afa8ffd8c085b393c50110e5bdedc3bddefe9b0b0a1408a1bedddba4cac5da3c10b8e5d9958ca7e3ec19225ae2f88cb2f8ffffffff018ceda99cfbffffffff01b9c298a407e295e8e9fcffffffff01f3b9ade5fcffffffff01c08bfea9fdffffffff01a2c2e5e1ffffffffff0186dcc5dafdffffffff01e9ffc7e507c9d89db8fdffffffff01")
  171. if err := fdpu.Unmarshal(m1); err != nil {
  172. t.Fatal("Unmarshalling message from v0.14.16:", err)
  173. }
  174. }
  175. func testMarshal(t *testing.T, prefix string, m1, m2 message) bool {
  176. buf, err := m1.Marshal()
  177. if err != nil {
  178. t.Fatal(err)
  179. }
  180. err = m2.Unmarshal(buf)
  181. if err != nil {
  182. t.Fatal(err)
  183. }
  184. bs1, _ := json.MarshalIndent(m1, "", " ")
  185. bs2, _ := json.MarshalIndent(m2, "", " ")
  186. if !bytes.Equal(bs1, bs2) {
  187. ioutil.WriteFile(prefix+"-1.txt", bs1, 0644)
  188. ioutil.WriteFile(prefix+"-2.txt", bs2, 0644)
  189. return false
  190. }
  191. return true
  192. }
  193. func TestLZ4Compression(t *testing.T) {
  194. c := new(rawConnection)
  195. for i := 0; i < 10; i++ {
  196. dataLen := 150 + rand.Intn(150)
  197. data := make([]byte, dataLen)
  198. _, err := io.ReadFull(rand.Reader, data[100:])
  199. if err != nil {
  200. t.Fatal(err)
  201. }
  202. comp, err := c.lz4Compress(data)
  203. if err != nil {
  204. t.Errorf("compressing %d bytes: %v", dataLen, err)
  205. continue
  206. }
  207. res, err := c.lz4Decompress(comp)
  208. if err != nil {
  209. t.Errorf("decompressing %d bytes to %d: %v", len(comp), dataLen, err)
  210. continue
  211. }
  212. if len(res) != len(data) {
  213. t.Errorf("Incorrect len %d != expected %d", len(res), len(data))
  214. }
  215. if !bytes.Equal(data, res) {
  216. t.Error("Incorrect decompressed data")
  217. }
  218. t.Logf("OK #%d, %d -> %d -> %d", i, dataLen, len(comp), dataLen)
  219. }
  220. }
  221. func TestCheckFilename(t *testing.T) {
  222. cases := []struct {
  223. name string
  224. ok bool
  225. }{
  226. // Valid filenames
  227. {"foo", true},
  228. {"foo/bar/baz", true},
  229. {"foo/bar:baz", true}, // colon is ok in general, will be filtered on windows
  230. {`\`, true}, // path separator on the wire is forward slash, so as above
  231. {`\.`, true},
  232. {`\..`, true},
  233. {".foo", true},
  234. {"foo..", true},
  235. // Invalid filenames
  236. {"foo/..", false},
  237. {"foo/../bar", false},
  238. {"../foo/../bar", false},
  239. {"", false},
  240. {".", false},
  241. {"..", false},
  242. {"/", false},
  243. {"/.", false},
  244. {"/..", false},
  245. {"/foo", false},
  246. {"./foo", false},
  247. {"foo./", false},
  248. {"foo/.", false},
  249. {"foo/", false},
  250. }
  251. for _, tc := range cases {
  252. err := checkFilename(tc.name)
  253. if (err == nil) != tc.ok {
  254. t.Errorf("Unexpected result for checkFilename(%q): %v", tc.name, err)
  255. }
  256. }
  257. }
  258. func TestCheckConsistency(t *testing.T) {
  259. cases := []struct {
  260. fi FileInfo
  261. ok bool
  262. }{
  263. {
  264. // valid
  265. fi: FileInfo{
  266. Name: "foo",
  267. Type: FileInfoTypeFile,
  268. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  269. },
  270. ok: true,
  271. },
  272. {
  273. // deleted with blocks
  274. fi: FileInfo{
  275. Name: "foo",
  276. Deleted: true,
  277. Type: FileInfoTypeFile,
  278. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  279. },
  280. ok: false,
  281. },
  282. {
  283. // no blocks
  284. fi: FileInfo{
  285. Name: "foo",
  286. Type: FileInfoTypeFile,
  287. },
  288. ok: false,
  289. },
  290. {
  291. // directory with blocks
  292. fi: FileInfo{
  293. Name: "foo",
  294. Type: FileInfoTypeDirectory,
  295. Blocks: []BlockInfo{{Size: 1234, Offset: 0, Hash: []byte{1, 2, 3, 4}}},
  296. },
  297. ok: false,
  298. },
  299. }
  300. for _, tc := range cases {
  301. err := checkFileInfoConsistency(tc.fi)
  302. if tc.ok && err != nil {
  303. t.Errorf("Unexpected error %v (want nil) for %v", err, tc.fi)
  304. }
  305. if !tc.ok && err == nil {
  306. t.Errorf("Unexpected nil error for %v", tc.fi)
  307. }
  308. }
  309. }
  310. func TestBlockSize(t *testing.T) {
  311. cases := []struct {
  312. fileSize int64
  313. blockSize int
  314. }{
  315. {1 << KiB, 128 << KiB},
  316. {1 << MiB, 128 << KiB},
  317. {499 << MiB, 256 << KiB},
  318. {500 << MiB, 512 << KiB},
  319. {501 << MiB, 512 << KiB},
  320. {1 << GiB, 1 << MiB},
  321. {2 << GiB, 2 << MiB},
  322. {3 << GiB, 2 << MiB},
  323. {500 << GiB, 16 << MiB},
  324. {50000 << GiB, 16 << MiB},
  325. }
  326. for _, tc := range cases {
  327. size := BlockSize(tc.fileSize)
  328. if size != tc.blockSize {
  329. t.Errorf("BlockSize(%d), size=%d, expected %d", tc.fileSize, size, tc.blockSize)
  330. }
  331. }
  332. }
  333. var blockSize int
  334. func BenchmarkBlockSize(b *testing.B) {
  335. for i := 0; i < b.N; i++ {
  336. blockSize = BlockSize(16 << 30)
  337. }
  338. }
  339. func TestLocalFlagBits(t *testing.T) {
  340. var f FileInfo
  341. if f.IsIgnored() || f.MustRescan() || f.IsInvalid() {
  342. t.Error("file should have no weird bits set by default")
  343. }
  344. f.SetIgnored(42)
  345. if !f.IsIgnored() || f.MustRescan() || !f.IsInvalid() {
  346. t.Error("file should be ignored and invalid")
  347. }
  348. f.SetMustRescan(42)
  349. if f.IsIgnored() || !f.MustRescan() || !f.IsInvalid() {
  350. t.Error("file should be must-rescan and invalid")
  351. }
  352. f.SetUnsupported(42)
  353. if f.IsIgnored() || f.MustRescan() || !f.IsInvalid() {
  354. t.Error("file should be invalid")
  355. }
  356. }
  357. func TestIsEquivalent(t *testing.T) {
  358. b := func(v bool) *bool {
  359. return &v
  360. }
  361. type testCase struct {
  362. a FileInfo
  363. b FileInfo
  364. ignPerms *bool // nil means should not matter, we'll test both variants
  365. ignBlocks *bool
  366. ignFlags uint32
  367. eq bool
  368. }
  369. cases := []testCase{
  370. // Empty FileInfos are equivalent
  371. {eq: true},
  372. // Various basic attributes, all of which cause ineqality when
  373. // they differ
  374. {
  375. a: FileInfo{Name: "foo"},
  376. b: FileInfo{Name: "bar"},
  377. eq: false,
  378. },
  379. {
  380. a: FileInfo{Type: FileInfoTypeFile},
  381. b: FileInfo{Type: FileInfoTypeDirectory},
  382. eq: false,
  383. },
  384. {
  385. a: FileInfo{Size: 1234},
  386. b: FileInfo{Size: 2345},
  387. eq: false,
  388. },
  389. {
  390. a: FileInfo{Deleted: false},
  391. b: FileInfo{Deleted: true},
  392. eq: false,
  393. },
  394. {
  395. a: FileInfo{RawInvalid: false},
  396. b: FileInfo{RawInvalid: true},
  397. eq: false,
  398. },
  399. {
  400. a: FileInfo{ModifiedS: 1234},
  401. b: FileInfo{ModifiedS: 2345},
  402. eq: false,
  403. },
  404. {
  405. a: FileInfo{ModifiedNs: 1234},
  406. b: FileInfo{ModifiedNs: 2345},
  407. eq: false,
  408. },
  409. // Special handling of local flags and invalidity. "MustRescan"
  410. // files are never equivalent to each other. Otherwise, equivalence
  411. // is based just on whether the file becomes IsInvalid() or not, not
  412. // the specific reason or flag bits.
  413. {
  414. a: FileInfo{LocalFlags: FlagLocalMustRescan},
  415. b: FileInfo{LocalFlags: FlagLocalMustRescan},
  416. eq: false,
  417. },
  418. {
  419. a: FileInfo{RawInvalid: true},
  420. b: FileInfo{RawInvalid: true},
  421. eq: true,
  422. },
  423. {
  424. a: FileInfo{LocalFlags: FlagLocalUnsupported},
  425. b: FileInfo{LocalFlags: FlagLocalUnsupported},
  426. eq: true,
  427. },
  428. {
  429. a: FileInfo{RawInvalid: true},
  430. b: FileInfo{LocalFlags: FlagLocalUnsupported},
  431. eq: true,
  432. },
  433. {
  434. a: FileInfo{LocalFlags: 0},
  435. b: FileInfo{LocalFlags: FlagLocalReceiveOnly},
  436. eq: false,
  437. },
  438. {
  439. a: FileInfo{LocalFlags: 0},
  440. b: FileInfo{LocalFlags: FlagLocalReceiveOnly},
  441. ignFlags: FlagLocalReceiveOnly,
  442. eq: true,
  443. },
  444. // Difference in blocks is not OK
  445. {
  446. a: FileInfo{Blocks: []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}},
  447. b: FileInfo{Blocks: []BlockInfo{{Hash: []byte{2, 3, 4, 5}}}},
  448. ignBlocks: b(false),
  449. eq: false,
  450. },
  451. // ... unless we say it is
  452. {
  453. a: FileInfo{Blocks: []BlockInfo{{Hash: []byte{1, 2, 3, 4}}}},
  454. b: FileInfo{Blocks: []BlockInfo{{Hash: []byte{2, 3, 4, 5}}}},
  455. ignBlocks: b(true),
  456. eq: true,
  457. },
  458. // Difference in permissions is not OK.
  459. {
  460. a: FileInfo{Permissions: 0444},
  461. b: FileInfo{Permissions: 0666},
  462. ignPerms: b(false),
  463. eq: false,
  464. },
  465. // ... unless we say it is
  466. {
  467. a: FileInfo{Permissions: 0666},
  468. b: FileInfo{Permissions: 0444},
  469. ignPerms: b(true),
  470. eq: true,
  471. },
  472. // These attributes are not checked at all
  473. {
  474. a: FileInfo{NoPermissions: false},
  475. b: FileInfo{NoPermissions: true},
  476. eq: true,
  477. },
  478. {
  479. a: FileInfo{Version: Vector{Counters: []Counter{{ID: 1, Value: 42}}}},
  480. b: FileInfo{Version: Vector{Counters: []Counter{{ID: 42, Value: 1}}}},
  481. eq: true,
  482. },
  483. {
  484. a: FileInfo{Sequence: 1},
  485. b: FileInfo{Sequence: 2},
  486. eq: true,
  487. },
  488. // The block size is not checked (but this would fail the blocks
  489. // check in real world)
  490. {
  491. a: FileInfo{RawBlockSize: 1},
  492. b: FileInfo{RawBlockSize: 2},
  493. eq: true,
  494. },
  495. // The symlink target is checked for symlinks
  496. {
  497. a: FileInfo{Type: FileInfoTypeSymlink, SymlinkTarget: "a"},
  498. b: FileInfo{Type: FileInfoTypeSymlink, SymlinkTarget: "b"},
  499. eq: false,
  500. },
  501. // ... but not for non-symlinks
  502. {
  503. a: FileInfo{Type: FileInfoTypeFile, SymlinkTarget: "a"},
  504. b: FileInfo{Type: FileInfoTypeFile, SymlinkTarget: "b"},
  505. eq: true,
  506. },
  507. }
  508. if runtime.GOOS == "windows" {
  509. // On windows we only check the user writable bit of the permission
  510. // set, so these are equivalent.
  511. cases = append(cases, testCase{
  512. a: FileInfo{Permissions: 0777},
  513. b: FileInfo{Permissions: 0600},
  514. ignPerms: b(false),
  515. eq: true,
  516. })
  517. }
  518. for i, tc := range cases {
  519. // Check the standard attributes with all permutations of the
  520. // special ignore flags, unless the value of those flags are given
  521. // in the tests.
  522. for _, ignPerms := range []bool{true, false} {
  523. for _, ignBlocks := range []bool{true, false} {
  524. if tc.ignPerms != nil && *tc.ignPerms != ignPerms {
  525. continue
  526. }
  527. if tc.ignBlocks != nil && *tc.ignBlocks != ignBlocks {
  528. continue
  529. }
  530. if res := tc.a.isEquivalent(tc.b, ignPerms, ignBlocks, tc.ignFlags); res != tc.eq {
  531. 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)
  532. }
  533. if res := tc.b.isEquivalent(tc.a, ignPerms, ignBlocks, tc.ignFlags); res != tc.eq {
  534. 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)
  535. }
  536. }
  537. }
  538. }
  539. }