requests_test.go 29 KB

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