requests_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bytes"
  9. "errors"
  10. "io/ioutil"
  11. "os"
  12. "path/filepath"
  13. "runtime"
  14. "strings"
  15. "testing"
  16. "time"
  17. "github.com/syncthing/syncthing/lib/config"
  18. "github.com/syncthing/syncthing/lib/db"
  19. "github.com/syncthing/syncthing/lib/events"
  20. "github.com/syncthing/syncthing/lib/fs"
  21. "github.com/syncthing/syncthing/lib/ignore"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. )
  24. func TestRequestSimple(t *testing.T) {
  25. testOs := &fatalOs{t}
  26. // Verify that the model performs a request and creates a file based on
  27. // an incoming index update.
  28. m, fc, tmpDir, w := setupModelWithConnection()
  29. defer func() {
  30. m.Stop()
  31. testOs.RemoveAll(tmpDir)
  32. testOs.Remove(w.ConfigPath())
  33. }()
  34. // We listen for incoming index updates and trigger when we see one for
  35. // the expected test file.
  36. done := make(chan struct{})
  37. fc.mut.Lock()
  38. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  39. select {
  40. case <-done:
  41. t.Fatalf("More than one index update sent")
  42. default:
  43. }
  44. for _, f := range fs {
  45. if f.Name == "testfile" {
  46. close(done)
  47. return
  48. }
  49. }
  50. }
  51. fc.mut.Unlock()
  52. // Send an update for the test file, wait for it to sync and be reported back.
  53. contents := []byte("test file contents\n")
  54. fc.addFile("testfile", 0644, protocol.FileInfoTypeFile, contents)
  55. fc.sendIndexUpdate()
  56. <-done
  57. // Verify the contents
  58. if err := equalContents(filepath.Join(tmpDir, "testfile"), contents); err != nil {
  59. t.Error("File did not sync correctly:", err)
  60. }
  61. }
  62. func TestSymlinkTraversalRead(t *testing.T) {
  63. testOs := &fatalOs{t}
  64. // Verify that a symlink can not be traversed for reading.
  65. if runtime.GOOS == "windows" {
  66. t.Skip("no symlink support on CI")
  67. return
  68. }
  69. m, fc, tmpDir, w := setupModelWithConnection()
  70. defer func() {
  71. m.Stop()
  72. testOs.RemoveAll(tmpDir)
  73. testOs.Remove(w.ConfigPath())
  74. }()
  75. // We listen for incoming index updates and trigger when we see one for
  76. // the expected test file.
  77. done := make(chan struct{})
  78. fc.mut.Lock()
  79. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  80. select {
  81. case <-done:
  82. t.Fatalf("More than one index update sent")
  83. default:
  84. }
  85. for _, f := range fs {
  86. if f.Name == "symlink" {
  87. close(done)
  88. return
  89. }
  90. }
  91. }
  92. fc.mut.Unlock()
  93. // Send an update for the symlink, wait for it to sync and be reported back.
  94. contents := []byte("..")
  95. fc.addFile("symlink", 0644, protocol.FileInfoTypeSymlink, contents)
  96. fc.sendIndexUpdate()
  97. <-done
  98. // Request a file by traversing the symlink
  99. res, err := m.Request(device1, "default", "symlink/requests_test.go", 10, 0, nil, 0, false)
  100. if err == nil || res != nil {
  101. t.Error("Managed to traverse symlink")
  102. }
  103. }
  104. func TestSymlinkTraversalWrite(t *testing.T) {
  105. testOs := &fatalOs{t}
  106. // Verify that a symlink can not be traversed for writing.
  107. if runtime.GOOS == "windows" {
  108. t.Skip("no symlink support on CI")
  109. return
  110. }
  111. m, fc, tmpDir, w := setupModelWithConnection()
  112. defer func() {
  113. m.Stop()
  114. testOs.RemoveAll(tmpDir)
  115. testOs.Remove(w.ConfigPath())
  116. }()
  117. // We listen for incoming index updates and trigger when we see one for
  118. // the expected names.
  119. done := make(chan struct{}, 1)
  120. badReq := make(chan string, 1)
  121. badIdx := make(chan string, 1)
  122. fc.mut.Lock()
  123. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  124. for _, f := range fs {
  125. if f.Name == "symlink" {
  126. done <- struct{}{}
  127. return
  128. }
  129. if strings.HasPrefix(f.Name, "symlink") {
  130. badIdx <- f.Name
  131. return
  132. }
  133. }
  134. }
  135. fc.requestFn = func(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  136. if name != "symlink" && strings.HasPrefix(name, "symlink") {
  137. badReq <- name
  138. }
  139. return fc.fileData[name], nil
  140. }
  141. fc.mut.Unlock()
  142. // Send an update for the symlink, wait for it to sync and be reported back.
  143. contents := []byte("..")
  144. fc.addFile("symlink", 0644, protocol.FileInfoTypeSymlink, contents)
  145. fc.sendIndexUpdate()
  146. <-done
  147. // Send an update for things behind the symlink, wait for requests for
  148. // blocks for any of them to come back, or index entries. Hopefully none
  149. // of that should happen.
  150. contents = []byte("testdata testdata\n")
  151. fc.addFile("symlink/testfile", 0644, protocol.FileInfoTypeFile, contents)
  152. fc.addFile("symlink/testdir", 0644, protocol.FileInfoTypeDirectory, contents)
  153. fc.addFile("symlink/testsyml", 0644, protocol.FileInfoTypeSymlink, contents)
  154. fc.sendIndexUpdate()
  155. select {
  156. case name := <-badReq:
  157. t.Fatal("Should not have requested the data for", name)
  158. case name := <-badIdx:
  159. t.Fatal("Should not have sent the index entry for", name)
  160. case <-time.After(3 * time.Second):
  161. // Unfortunately not much else to trigger on here. The puller sleep
  162. // interval is 1s so if we didn't get any requests within two
  163. // iterations we should be fine.
  164. }
  165. }
  166. func TestRequestCreateTmpSymlink(t *testing.T) {
  167. testOs := &fatalOs{t}
  168. // Test that an update for a temporary file is invalidated
  169. m, fc, tmpDir, w := setupModelWithConnection()
  170. defer func() {
  171. m.Stop()
  172. testOs.RemoveAll(tmpDir)
  173. testOs.Remove(w.ConfigPath())
  174. }()
  175. // We listen for incoming index updates and trigger when we see one for
  176. // the expected test file.
  177. goodIdx := make(chan struct{})
  178. name := fs.TempName("testlink")
  179. fc.mut.Lock()
  180. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  181. for _, f := range fs {
  182. if f.Name == name {
  183. if f.IsInvalid() {
  184. goodIdx <- struct{}{}
  185. } else {
  186. t.Fatal("Received index with non-invalid temporary file")
  187. }
  188. return
  189. }
  190. }
  191. }
  192. fc.mut.Unlock()
  193. // Send an update for the test file, wait for it to sync and be reported back.
  194. fc.addFile(name, 0644, protocol.FileInfoTypeSymlink, []byte(".."))
  195. fc.sendIndexUpdate()
  196. select {
  197. case <-goodIdx:
  198. case <-time.After(3 * time.Second):
  199. t.Fatal("Timed out without index entry being sent")
  200. }
  201. }
  202. func TestRequestVersioningSymlinkAttack(t *testing.T) {
  203. testOs := &fatalOs{t}
  204. if runtime.GOOS == "windows" {
  205. t.Skip("no symlink support on Windows")
  206. }
  207. // Sets up a folder with trashcan versioning and tries to use a
  208. // deleted symlink to escape
  209. tmpDir := createTmpDir()
  210. defer testOs.RemoveAll(tmpDir)
  211. cfg := defaultCfgWrapper.RawCopy()
  212. cfg.Devices = append(cfg.Devices, config.NewDeviceConfiguration(device2, "device2"))
  213. cfg.Folders[0] = config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, tmpDir)
  214. cfg.Folders[0].Devices = []config.FolderDeviceConfiguration{
  215. {DeviceID: device1},
  216. {DeviceID: device2},
  217. }
  218. cfg.Folders[0].Versioning = config.VersioningConfiguration{
  219. Type: "trashcan",
  220. }
  221. w := createTmpWrapper(cfg)
  222. defer testOs.Remove(w.ConfigPath())
  223. db := db.OpenMemory()
  224. m := NewModel(w, device1, "syncthing", "dev", db, nil)
  225. m.AddFolder(cfg.Folders[0])
  226. m.ServeBackground()
  227. m.StartFolder("default")
  228. defer m.Stop()
  229. defer testOs.RemoveAll(tmpDir)
  230. fc := addFakeConn(m, device2)
  231. fc.folder = "default"
  232. // Create a temporary directory that we will use as target to see if
  233. // we can escape to it
  234. tmpdir, err := ioutil.TempDir("", "syncthing-test")
  235. if err != nil {
  236. t.Fatal(err)
  237. }
  238. // We listen for incoming index updates and trigger when we see one for
  239. // the expected test file.
  240. idx := make(chan int)
  241. fc.mut.Lock()
  242. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  243. idx <- len(fs)
  244. }
  245. fc.mut.Unlock()
  246. // Send an update for the test file, wait for it to sync and be reported back.
  247. fc.addFile("foo", 0644, protocol.FileInfoTypeSymlink, []byte(tmpdir))
  248. fc.sendIndexUpdate()
  249. for updates := 0; updates < 1; updates += <-idx {
  250. }
  251. // Delete the symlink, hoping for it to get versioned
  252. fc.deleteFile("foo")
  253. fc.sendIndexUpdate()
  254. for updates := 0; updates < 1; updates += <-idx {
  255. }
  256. // Recreate foo and a file in it with some data
  257. fc.updateFile("foo", 0755, protocol.FileInfoTypeDirectory, nil)
  258. fc.addFile("foo/test", 0644, protocol.FileInfoTypeFile, []byte("testtesttest"))
  259. fc.sendIndexUpdate()
  260. for updates := 0; updates < 1; updates += <-idx {
  261. }
  262. // Remove the test file and see if it escaped
  263. fc.deleteFile("foo/test")
  264. fc.sendIndexUpdate()
  265. for updates := 0; updates < 1; updates += <-idx {
  266. }
  267. path := filepath.Join(tmpdir, "test")
  268. if _, err := os.Lstat(path); !os.IsNotExist(err) {
  269. t.Fatal("File escaped to", path)
  270. }
  271. }
  272. func TestPullInvalidIgnoredSO(t *testing.T) {
  273. pullInvalidIgnored(t, config.FolderTypeSendOnly)
  274. }
  275. func TestPullInvalidIgnoredSR(t *testing.T) {
  276. pullInvalidIgnored(t, config.FolderTypeSendReceive)
  277. }
  278. // This test checks that (un-)ignored/invalid/deleted files are treated as expected.
  279. func pullInvalidIgnored(t *testing.T, ft config.FolderType) {
  280. t.Helper()
  281. testOs := &fatalOs{t}
  282. tmpDir := createTmpDir()
  283. cfg := defaultCfgWrapper.RawCopy()
  284. cfg.Devices = append(cfg.Devices, config.NewDeviceConfiguration(device2, "device2"))
  285. cfg.Folders[0] = config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, tmpDir)
  286. cfg.Folders[0].Devices = []config.FolderDeviceConfiguration{
  287. {DeviceID: device1},
  288. {DeviceID: device2},
  289. }
  290. cfg.Folders[0].Type = ft
  291. m, fc, w := setupModelWithConnectionManual(cfg)
  292. defer func() {
  293. m.Stop()
  294. testOs.RemoveAll(tmpDir)
  295. testOs.Remove(w.ConfigPath())
  296. }()
  297. // Reach in and update the ignore matcher to one that always does
  298. // reloads when asked to, instead of checking file mtimes. This is
  299. // because we might be changing the files on disk often enough that the
  300. // mtimes will be unreliable to determine change status.
  301. m.fmut.Lock()
  302. m.folderIgnores["default"] = ignore.New(cfg.Folders[0].Filesystem(), ignore.WithChangeDetector(newAlwaysChanged()))
  303. m.fmut.Unlock()
  304. if err := m.SetIgnores("default", []string{"*ignored*"}); err != nil {
  305. panic(err)
  306. }
  307. contents := []byte("test file contents\n")
  308. otherContents := []byte("other test file contents\n")
  309. invIgn := "invalid:ignored"
  310. invDel := "invalid:deleted"
  311. ign := "ignoredNonExisting"
  312. ignExisting := "ignoredExisting"
  313. fc.addFile(invIgn, 0644, protocol.FileInfoTypeFile, contents)
  314. fc.addFile(invDel, 0644, protocol.FileInfoTypeFile, contents)
  315. fc.deleteFile(invDel)
  316. fc.addFile(ign, 0644, protocol.FileInfoTypeFile, contents)
  317. fc.addFile(ignExisting, 0644, protocol.FileInfoTypeFile, contents)
  318. if err := ioutil.WriteFile(filepath.Join(tmpDir, ignExisting), otherContents, 0644); err != nil {
  319. panic(err)
  320. }
  321. done := make(chan struct{})
  322. fc.mut.Lock()
  323. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  324. expected := map[string]struct{}{invIgn: {}, ign: {}, ignExisting: {}}
  325. for _, f := range fs {
  326. if _, ok := expected[f.Name]; !ok {
  327. t.Errorf("Unexpected file %v was added to index", f.Name)
  328. }
  329. if !f.IsInvalid() {
  330. t.Errorf("File %v wasn't marked as invalid", f.Name)
  331. }
  332. delete(expected, f.Name)
  333. }
  334. for name := range expected {
  335. t.Errorf("File %v wasn't added to index", name)
  336. }
  337. done <- struct{}{}
  338. }
  339. fc.mut.Unlock()
  340. sub := events.Default.Subscribe(events.FolderErrors)
  341. defer events.Default.Unsubscribe(sub)
  342. fc.sendIndexUpdate()
  343. timeout := time.NewTimer(5 * time.Second)
  344. select {
  345. case ev := <-sub.C():
  346. t.Fatalf("Errors while pulling: %v", ev)
  347. case <-timeout.C:
  348. t.Fatalf("timed out before index was received")
  349. case <-done:
  350. return
  351. }
  352. fc.mut.Lock()
  353. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  354. expected := map[string]struct{}{ign: {}, ignExisting: {}}
  355. for _, f := range fs {
  356. if _, ok := expected[f.Name]; !ok {
  357. t.Fatalf("Unexpected file %v was updated in index", f.Name)
  358. }
  359. if f.IsInvalid() {
  360. t.Errorf("File %v is still marked as invalid", f.Name)
  361. }
  362. // The unignored files should only have a local version,
  363. // to mark them as in conflict with any other existing versions.
  364. ev := protocol.Vector{}.Update(device1.Short())
  365. if v := f.Version; !v.Equal(ev) {
  366. t.Errorf("File %v has version %v, expected %v", f.Name, v, ev)
  367. }
  368. if f.Name == ign {
  369. if !f.Deleted {
  370. t.Errorf("File %v was not marked as deleted", f.Name)
  371. }
  372. } else if f.Deleted {
  373. t.Errorf("File %v is marked as deleted", f.Name)
  374. }
  375. delete(expected, f.Name)
  376. }
  377. for name := range expected {
  378. t.Errorf("File %v wasn't updated in index", name)
  379. }
  380. done <- struct{}{}
  381. }
  382. // Make sure pulling doesn't interfere, as index updates are racy and
  383. // thus we cannot distinguish between scan and pull results.
  384. fc.requestFn = func(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  385. return nil, nil
  386. }
  387. fc.mut.Unlock()
  388. if err := m.SetIgnores("default", []string{"*:ignored*"}); err != nil {
  389. panic(err)
  390. }
  391. timeout = time.NewTimer(5 * time.Second)
  392. select {
  393. case <-timeout.C:
  394. t.Fatalf("timed out before index was received")
  395. case <-done:
  396. return
  397. }
  398. }
  399. func TestIssue4841(t *testing.T) {
  400. testOs := &fatalOs{t}
  401. m, fc, tmpDir, w := setupModelWithConnection()
  402. defer func() {
  403. m.Stop()
  404. testOs.RemoveAll(tmpDir)
  405. testOs.Remove(w.ConfigPath())
  406. }()
  407. received := make(chan protocol.FileInfo)
  408. fc.mut.Lock()
  409. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  410. if len(fs) != 1 {
  411. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  412. }
  413. if fs[0].Name != "foo" {
  414. t.Fatalf(`Sent index with file %v, should be "foo"`, fs[0].Name)
  415. }
  416. received <- fs[0]
  417. }
  418. fc.mut.Unlock()
  419. // Setup file from remote that was ignored locally
  420. m.updateLocals(defaultFolderConfig.ID, []protocol.FileInfo{{
  421. Name: "foo",
  422. Type: protocol.FileInfoTypeFile,
  423. LocalFlags: protocol.FlagLocalIgnored,
  424. Version: protocol.Vector{}.Update(device2.Short()),
  425. }})
  426. <-received
  427. // Scan without ignore patterns with "foo" not existing locally
  428. if err := m.ScanFolder("default"); err != nil {
  429. t.Fatal("Failed scanning:", err)
  430. }
  431. f := <-received
  432. if expected := (protocol.Vector{}.Update(device1.Short())); !f.Version.Equal(expected) {
  433. t.Errorf("Got Version == %v, expected %v", f.Version, expected)
  434. }
  435. }
  436. func TestRescanIfHaveInvalidContent(t *testing.T) {
  437. testOs := &fatalOs{t}
  438. m, fc, tmpDir, w := setupModelWithConnection()
  439. defer func() {
  440. m.Stop()
  441. testOs.RemoveAll(tmpDir)
  442. testOs.Remove(w.ConfigPath())
  443. }()
  444. payload := []byte("hello")
  445. if err := ioutil.WriteFile(filepath.Join(tmpDir, "foo"), payload, 0777); err != nil {
  446. t.Fatal(err)
  447. }
  448. received := make(chan protocol.FileInfo)
  449. fc.mut.Lock()
  450. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  451. if len(fs) != 1 {
  452. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  453. }
  454. if fs[0].Name != "foo" {
  455. t.Fatalf(`Sent index with file %v, should be "foo"`, fs[0].Name)
  456. }
  457. received <- fs[0]
  458. }
  459. fc.mut.Unlock()
  460. // Scan without ignore patterns with "foo" not existing locally
  461. if err := m.ScanFolder("default"); err != nil {
  462. t.Fatal("Failed scanning:", err)
  463. }
  464. f := <-received
  465. if f.Blocks[0].WeakHash != 103547413 {
  466. t.Fatalf("unexpected weak hash: %d != 103547413", f.Blocks[0].WeakHash)
  467. }
  468. res, err := m.Request(device2, "default", "foo", int32(len(payload)), 0, f.Blocks[0].Hash, f.Blocks[0].WeakHash, false)
  469. if err != nil {
  470. t.Fatal(err)
  471. }
  472. buf := res.Data()
  473. if !bytes.Equal(buf, payload) {
  474. t.Errorf("%s != %s", buf, payload)
  475. }
  476. payload = []byte("bye")
  477. buf = make([]byte, len(payload))
  478. if err := ioutil.WriteFile(filepath.Join(tmpDir, "foo"), payload, 0777); err != nil {
  479. t.Fatal(err)
  480. }
  481. _, err = m.Request(device2, "default", "foo", int32(len(payload)), 0, f.Blocks[0].Hash, f.Blocks[0].WeakHash, false)
  482. if err == nil {
  483. t.Fatalf("expected failure")
  484. }
  485. select {
  486. case f := <-received:
  487. if f.Blocks[0].WeakHash != 41943361 {
  488. t.Fatalf("unexpected weak hash: %d != 41943361", f.Blocks[0].WeakHash)
  489. }
  490. case <-time.After(time.Second):
  491. t.Fatalf("timed out")
  492. }
  493. }
  494. func TestParentDeletion(t *testing.T) {
  495. testOs := &fatalOs{t}
  496. m, fc, tmpDir, w := setupModelWithConnection()
  497. defer func() {
  498. m.Stop()
  499. testOs.RemoveAll(tmpDir)
  500. testOs.Remove(w.ConfigPath())
  501. }()
  502. parent := "foo"
  503. child := filepath.Join(parent, "bar")
  504. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmpDir)
  505. received := make(chan []protocol.FileInfo)
  506. fc.addFile(parent, 0777, protocol.FileInfoTypeDirectory, nil)
  507. fc.addFile(child, 0777, protocol.FileInfoTypeDirectory, nil)
  508. fc.mut.Lock()
  509. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  510. received <- fs
  511. }
  512. fc.mut.Unlock()
  513. fc.sendIndexUpdate()
  514. // Get back index from initial setup
  515. select {
  516. case fs := <-received:
  517. if len(fs) != 2 {
  518. t.Fatalf("Sent index with %d files, should be 2", len(fs))
  519. }
  520. case <-time.After(time.Second):
  521. t.Fatalf("timed out")
  522. }
  523. // Delete parent dir
  524. if err := testFs.RemoveAll(parent); err != nil {
  525. t.Fatal(err)
  526. }
  527. // Scan only the child dir (not the parent)
  528. if err := m.ScanFolderSubdirs("default", []string{child}); err != nil {
  529. t.Fatal("Failed scanning:", err)
  530. }
  531. select {
  532. case fs := <-received:
  533. if len(fs) != 1 {
  534. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  535. }
  536. if fs[0].Name != child {
  537. t.Fatalf(`Sent index with file "%v", should be "%v"`, fs[0].Name, child)
  538. }
  539. case <-time.After(time.Second):
  540. t.Fatalf("timed out")
  541. }
  542. // Recreate the child dir on the remote
  543. fc.updateFile(child, 0777, protocol.FileInfoTypeDirectory, nil)
  544. fc.sendIndexUpdate()
  545. // Wait for the child dir to be recreated and sent to the remote
  546. select {
  547. case fs := <-received:
  548. l.Debugln("sent:", fs)
  549. found := false
  550. for _, f := range fs {
  551. if f.Name == child {
  552. if f.Deleted {
  553. t.Fatalf(`File "%v" is still deleted`, child)
  554. }
  555. found = true
  556. }
  557. }
  558. if !found {
  559. t.Fatalf(`File "%v" is missing in index`, child)
  560. }
  561. case <-time.After(5 * time.Second):
  562. t.Fatalf("timed out")
  563. }
  564. }
  565. // TestRequestSymlinkWindows checks that symlinks aren't marked as deleted on windows
  566. // Issue: https://github.com/syncthing/syncthing/issues/5125
  567. func TestRequestSymlinkWindows(t *testing.T) {
  568. if runtime.GOOS != "windows" {
  569. t.Skip("windows specific test")
  570. }
  571. testOs := &fatalOs{t}
  572. m, fc, tmpDir, w := setupModelWithConnection()
  573. defer func() {
  574. m.Stop()
  575. testOs.RemoveAll(tmpDir)
  576. testOs.Remove(w.ConfigPath())
  577. }()
  578. done := make(chan struct{})
  579. fc.mut.Lock()
  580. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  581. select {
  582. case <-done:
  583. t.Fatalf("More than one index update sent")
  584. default:
  585. }
  586. // expected first index
  587. if len(fs) != 1 {
  588. t.Fatalf("Expected just one file in index, got %v", fs)
  589. }
  590. f := fs[0]
  591. if f.Name != "link" {
  592. t.Fatalf(`Got file info with path "%v", expected "link"`, f.Name)
  593. }
  594. if !f.IsInvalid() {
  595. t.Errorf(`File info was not marked as invalid`)
  596. }
  597. close(done)
  598. }
  599. fc.mut.Unlock()
  600. fc.addFile("link", 0644, protocol.FileInfoTypeSymlink, nil)
  601. fc.sendIndexUpdate()
  602. select {
  603. case <-done:
  604. case <-time.After(time.Second):
  605. t.Fatalf("timed out before pull was finished")
  606. }
  607. sub := events.Default.Subscribe(events.StateChanged | events.LocalIndexUpdated)
  608. defer events.Default.Unsubscribe(sub)
  609. m.ScanFolder("default")
  610. for {
  611. select {
  612. case ev := <-sub.C():
  613. switch data := ev.Data.(map[string]interface{}); {
  614. case ev.Type == events.LocalIndexUpdated:
  615. t.Fatalf("Local index was updated unexpectedly: %v", data)
  616. case ev.Type == events.StateChanged:
  617. if data["from"] == "scanning" {
  618. return
  619. }
  620. }
  621. case <-time.After(5 * time.Second):
  622. t.Fatalf("Timed out before scan finished")
  623. }
  624. }
  625. }
  626. func setupModelWithConnection() (*Model, *fakeConnection, string, *config.Wrapper) {
  627. tmpDir := createTmpDir()
  628. cfg := defaultCfgWrapper.RawCopy()
  629. cfg.Devices = append(cfg.Devices, config.NewDeviceConfiguration(device2, "device2"))
  630. cfg.Folders[0] = config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, tmpDir)
  631. cfg.Folders[0].FSWatcherEnabled = false
  632. cfg.Folders[0].Devices = []config.FolderDeviceConfiguration{
  633. {DeviceID: device1},
  634. {DeviceID: device2},
  635. }
  636. m, fc, w := setupModelWithConnectionManual(cfg)
  637. return m, fc, tmpDir, w
  638. }
  639. func setupModelWithConnectionManual(cfg config.Configuration) (*Model, *fakeConnection, *config.Wrapper) {
  640. w := createTmpWrapper(cfg)
  641. db := db.OpenMemory()
  642. m := NewModel(w, device1, "syncthing", "dev", db, nil)
  643. m.AddFolder(cfg.Folders[0])
  644. m.ServeBackground()
  645. m.StartFolder("default")
  646. fc := addFakeConn(m, device2)
  647. fc.folder = "default"
  648. m.ScanFolder("default")
  649. return m, fc, w
  650. }
  651. func createTmpDir() string {
  652. tmpDir, err := ioutil.TempDir("", "_request-")
  653. if err != nil {
  654. panic("Failed to create temporary testing dir")
  655. }
  656. return tmpDir
  657. }
  658. func equalContents(path string, contents []byte) error {
  659. if bs, err := ioutil.ReadFile(path); err != nil {
  660. return err
  661. } else if !bytes.Equal(bs, contents) {
  662. return errors.New("incorrect data")
  663. }
  664. return nil
  665. }
  666. func TestRequestRemoteRenameChanged(t *testing.T) {
  667. testOs := &fatalOs{t}
  668. m, fc, tmpDir, w := setupModelWithConnection()
  669. defer func() {
  670. m.Stop()
  671. testOs.RemoveAll(tmpDir)
  672. testOs.Remove(w.ConfigPath())
  673. }()
  674. tfs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmpDir)
  675. done := make(chan struct{})
  676. fc.mut.Lock()
  677. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  678. select {
  679. case <-done:
  680. t.Fatalf("More than one index update sent")
  681. default:
  682. }
  683. if len(fs) != 2 {
  684. t.Fatalf("Received index with %v indexes instead of 2", len(fs))
  685. }
  686. close(done)
  687. }
  688. fc.mut.Unlock()
  689. // setup
  690. a := "a"
  691. b := "b"
  692. data := map[string][]byte{
  693. a: []byte("aData"),
  694. b: []byte("bData"),
  695. }
  696. for _, n := range [2]string{a, b} {
  697. fc.addFile(n, 0644, protocol.FileInfoTypeFile, data[n])
  698. }
  699. fc.sendIndexUpdate()
  700. select {
  701. case <-done:
  702. done = make(chan struct{})
  703. fc.mut.Lock()
  704. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  705. select {
  706. case <-done:
  707. t.Fatalf("More than one index update sent")
  708. default:
  709. }
  710. close(done)
  711. }
  712. fc.mut.Unlock()
  713. case <-time.After(10 * time.Second):
  714. t.Fatal("timed out")
  715. }
  716. for _, n := range [2]string{a, b} {
  717. if err := equalContents(filepath.Join(tmpDir, n), data[n]); err != nil {
  718. t.Fatal(err)
  719. }
  720. }
  721. fd, err := tfs.OpenFile(b, fs.OptReadWrite, 0644)
  722. if err != nil {
  723. t.Fatal(err)
  724. }
  725. otherData := []byte("otherData")
  726. if _, err = fd.Write(otherData); err != nil {
  727. t.Fatal(err)
  728. }
  729. fd.Close()
  730. // rename
  731. fc.deleteFile(a)
  732. fc.updateFile(b, 0644, protocol.FileInfoTypeFile, data[a])
  733. fc.sendIndexUpdate()
  734. select {
  735. case <-done:
  736. case <-time.After(10 * time.Second):
  737. t.Fatal("timed out")
  738. }
  739. // Check outcome
  740. tfs.Walk(".", func(path string, info fs.FileInfo, err error) error {
  741. switch {
  742. case path == a:
  743. t.Errorf(`File "a" was not removed`)
  744. case path == b:
  745. if err := equalContents(filepath.Join(tmpDir, b), otherData); err != nil {
  746. t.Errorf(`Modified file "b" was overwritten`)
  747. }
  748. }
  749. return nil
  750. })
  751. }
  752. func TestRequestRemoteRenameConflict(t *testing.T) {
  753. testOs := &fatalOs{t}
  754. m, fc, tmpDir, w := setupModelWithConnection()
  755. defer func() {
  756. m.Stop()
  757. testOs.RemoveAll(tmpDir)
  758. testOs.Remove(w.ConfigPath())
  759. }()
  760. tfs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmpDir)
  761. recv := make(chan int)
  762. fc.mut.Lock()
  763. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  764. recv <- len(fs)
  765. }
  766. fc.mut.Unlock()
  767. // setup
  768. a := "a"
  769. b := "b"
  770. data := map[string][]byte{
  771. a: []byte("aData"),
  772. b: []byte("bData"),
  773. }
  774. for _, n := range [2]string{a, b} {
  775. fc.addFile(n, 0644, protocol.FileInfoTypeFile, data[n])
  776. }
  777. fc.sendIndexUpdate()
  778. select {
  779. case i := <-recv:
  780. if i != 2 {
  781. t.Fatalf("received %v items in index, expected 1", i)
  782. }
  783. case <-time.After(10 * time.Second):
  784. t.Fatal("timed out")
  785. }
  786. for _, n := range [2]string{a, b} {
  787. if err := equalContents(filepath.Join(tmpDir, n), data[n]); err != nil {
  788. t.Fatal(err)
  789. }
  790. }
  791. fd, err := tfs.OpenFile(b, fs.OptReadWrite, 0644)
  792. if err != nil {
  793. t.Fatal(err)
  794. }
  795. otherData := []byte("otherData")
  796. if _, err = fd.Write(otherData); err != nil {
  797. t.Fatal(err)
  798. }
  799. fd.Close()
  800. m.ScanFolders()
  801. select {
  802. case i := <-recv:
  803. if i != 1 {
  804. t.Fatalf("received %v items in index, expected 1", i)
  805. }
  806. case <-time.After(10 * time.Second):
  807. t.Fatal("timed out")
  808. }
  809. // make sure the following rename is more recent (not concurrent)
  810. time.Sleep(2 * time.Second)
  811. // rename
  812. fc.deleteFile(a)
  813. fc.updateFile(b, 0644, protocol.FileInfoTypeFile, data[a])
  814. fc.sendIndexUpdate()
  815. select {
  816. case <-recv:
  817. case <-time.After(10 * time.Second):
  818. t.Fatal("timed out")
  819. }
  820. // Check outcome
  821. foundB := false
  822. foundBConfl := false
  823. tfs.Walk(".", func(path string, info fs.FileInfo, err error) error {
  824. switch {
  825. case path == a:
  826. t.Errorf(`File "a" was not removed`)
  827. case path == b:
  828. foundB = true
  829. case strings.HasPrefix(path, b) && strings.Contains(path, ".sync-conflict-"):
  830. foundBConfl = true
  831. }
  832. return nil
  833. })
  834. if !foundB {
  835. t.Errorf(`File "b" was removed`)
  836. }
  837. if !foundBConfl {
  838. t.Errorf(`No conflict file for "b" was created`)
  839. }
  840. }
  841. func TestRequestDeleteChanged(t *testing.T) {
  842. testOs := &fatalOs{t}
  843. m, fc, tmpDir, w := setupModelWithConnection()
  844. defer func() {
  845. m.Stop()
  846. testOs.RemoveAll(tmpDir)
  847. testOs.Remove(w.ConfigPath())
  848. }()
  849. tfs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmpDir)
  850. done := make(chan struct{})
  851. fc.mut.Lock()
  852. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  853. select {
  854. case <-done:
  855. t.Fatalf("More than one index update sent")
  856. default:
  857. }
  858. close(done)
  859. }
  860. fc.mut.Unlock()
  861. // setup
  862. a := "a"
  863. data := []byte("aData")
  864. fc.addFile(a, 0644, protocol.FileInfoTypeFile, data)
  865. fc.sendIndexUpdate()
  866. select {
  867. case <-done:
  868. done = make(chan struct{})
  869. case <-time.After(10 * time.Second):
  870. t.Fatal("timed out")
  871. }
  872. fc.mut.Lock()
  873. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  874. select {
  875. case <-done:
  876. t.Fatalf("More than one index update sent")
  877. default:
  878. }
  879. close(done)
  880. }
  881. fc.mut.Unlock()
  882. fd, err := tfs.OpenFile(a, fs.OptReadWrite, 0644)
  883. if err != nil {
  884. t.Fatal(err)
  885. }
  886. otherData := []byte("otherData")
  887. if _, err = fd.Write(otherData); err != nil {
  888. t.Fatal(err)
  889. }
  890. fd.Close()
  891. // rename
  892. fc.deleteFile(a)
  893. fc.sendIndexUpdate()
  894. select {
  895. case <-done:
  896. case <-time.After(10 * time.Second):
  897. t.Fatal("timed out")
  898. }
  899. // Check outcome
  900. if _, err := tfs.Lstat(a); err != nil {
  901. if fs.IsNotExist(err) {
  902. t.Error(`Modified file "a" was removed`)
  903. } else {
  904. t.Error(`Error stating file "a":`, err)
  905. }
  906. }
  907. }