requests_test.go 29 KB

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