requests_test.go 26 KB

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