requests_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bytes"
  9. "errors"
  10. "io/ioutil"
  11. "os"
  12. "path/filepath"
  13. "runtime"
  14. "strings"
  15. "testing"
  16. "time"
  17. "github.com/syncthing/syncthing/lib/config"
  18. "github.com/syncthing/syncthing/lib/db"
  19. "github.com/syncthing/syncthing/lib/events"
  20. "github.com/syncthing/syncthing/lib/fs"
  21. "github.com/syncthing/syncthing/lib/ignore"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. )
  24. func TestRequestSimple(t *testing.T) {
  25. // 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. os.RemoveAll(tmpDir)
  31. os.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. for _, f := range fs {
  39. if f.Name == "testfile" {
  40. close(done)
  41. return
  42. }
  43. }
  44. }
  45. fc.mut.Unlock()
  46. // Send an update for the test file, wait for it to sync and be reported back.
  47. contents := []byte("test file contents\n")
  48. fc.addFile("testfile", 0644, protocol.FileInfoTypeFile, contents)
  49. fc.sendIndexUpdate()
  50. <-done
  51. // Verify the contents
  52. if err := equalContents(filepath.Join(tmpDir, "testfile"), contents); err != nil {
  53. t.Error("File did not sync correctly:", err)
  54. }
  55. }
  56. func TestSymlinkTraversalRead(t *testing.T) {
  57. // Verify that a symlink can not be traversed for reading.
  58. if runtime.GOOS == "windows" {
  59. t.Skip("no symlink support on CI")
  60. return
  61. }
  62. m, fc, tmpDir, w := setupModelWithConnection()
  63. defer func() {
  64. m.Stop()
  65. os.RemoveAll(tmpDir)
  66. os.Remove(w.ConfigPath())
  67. }()
  68. // We listen for incoming index updates and trigger when we see one for
  69. // the expected test file.
  70. done := make(chan struct{})
  71. fc.mut.Lock()
  72. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  73. for _, f := range fs {
  74. if f.Name == "symlink" {
  75. close(done)
  76. return
  77. }
  78. }
  79. }
  80. fc.mut.Unlock()
  81. // Send an update for the symlink, wait for it to sync and be reported back.
  82. contents := []byte("..")
  83. fc.addFile("symlink", 0644, protocol.FileInfoTypeSymlink, contents)
  84. fc.sendIndexUpdate()
  85. <-done
  86. // Request a file by traversing the symlink
  87. buf := make([]byte, 10)
  88. err := m.Request(device1, "default", "symlink/requests_test.go", 0, nil, 0, false, buf)
  89. if err == nil || !bytes.Equal(buf, make([]byte, 10)) {
  90. t.Error("Managed to traverse symlink")
  91. }
  92. }
  93. func TestSymlinkTraversalWrite(t *testing.T) {
  94. // Verify that a symlink can not be traversed for writing.
  95. if runtime.GOOS == "windows" {
  96. t.Skip("no symlink support on CI")
  97. return
  98. }
  99. m, fc, tmpDir, w := setupModelWithConnection()
  100. defer func() {
  101. m.Stop()
  102. os.RemoveAll(tmpDir)
  103. os.Remove(w.ConfigPath())
  104. }()
  105. // We listen for incoming index updates and trigger when we see one for
  106. // the expected names.
  107. done := make(chan struct{}, 1)
  108. badReq := make(chan string, 1)
  109. badIdx := make(chan string, 1)
  110. fc.mut.Lock()
  111. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  112. for _, f := range fs {
  113. if f.Name == "symlink" {
  114. done <- struct{}{}
  115. return
  116. }
  117. if strings.HasPrefix(f.Name, "symlink") {
  118. badIdx <- f.Name
  119. return
  120. }
  121. }
  122. }
  123. fc.requestFn = func(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  124. if name != "symlink" && strings.HasPrefix(name, "symlink") {
  125. badReq <- name
  126. }
  127. return fc.fileData[name], nil
  128. }
  129. fc.mut.Unlock()
  130. // Send an update for the symlink, wait for it to sync and be reported back.
  131. contents := []byte("..")
  132. fc.addFile("symlink", 0644, protocol.FileInfoTypeSymlink, contents)
  133. fc.sendIndexUpdate()
  134. <-done
  135. // Send an update for things behind the symlink, wait for requests for
  136. // blocks for any of them to come back, or index entries. Hopefully none
  137. // of that should happen.
  138. contents = []byte("testdata testdata\n")
  139. fc.addFile("symlink/testfile", 0644, protocol.FileInfoTypeFile, contents)
  140. fc.addFile("symlink/testdir", 0644, protocol.FileInfoTypeDirectory, contents)
  141. fc.addFile("symlink/testsyml", 0644, protocol.FileInfoTypeSymlink, contents)
  142. fc.sendIndexUpdate()
  143. select {
  144. case name := <-badReq:
  145. t.Fatal("Should not have requested the data for", name)
  146. case name := <-badIdx:
  147. t.Fatal("Should not have sent the index entry for", name)
  148. case <-time.After(3 * time.Second):
  149. // Unfortunately not much else to trigger on here. The puller sleep
  150. // interval is 1s so if we didn't get any requests within two
  151. // iterations we should be fine.
  152. }
  153. }
  154. func TestRequestCreateTmpSymlink(t *testing.T) {
  155. // Test that an update for a temporary file is invalidated
  156. m, fc, tmpDir, w := setupModelWithConnection()
  157. defer func() {
  158. m.Stop()
  159. os.RemoveAll(tmpDir)
  160. os.Remove(w.ConfigPath())
  161. }()
  162. // We listen for incoming index updates and trigger when we see one for
  163. // the expected test file.
  164. goodIdx := make(chan struct{})
  165. name := fs.TempName("testlink")
  166. fc.mut.Lock()
  167. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  168. for _, f := range fs {
  169. if f.Name == name {
  170. if f.IsInvalid() {
  171. goodIdx <- struct{}{}
  172. } else {
  173. t.Fatal("Received index with non-invalid temporary file")
  174. }
  175. return
  176. }
  177. }
  178. }
  179. fc.mut.Unlock()
  180. // Send an update for the test file, wait for it to sync and be reported back.
  181. fc.addFile(name, 0644, protocol.FileInfoTypeSymlink, []byte(".."))
  182. fc.sendIndexUpdate()
  183. select {
  184. case <-goodIdx:
  185. case <-time.After(3 * time.Second):
  186. t.Fatal("Timed out without index entry being sent")
  187. }
  188. }
  189. func TestRequestVersioningSymlinkAttack(t *testing.T) {
  190. if runtime.GOOS == "windows" {
  191. t.Skip("no symlink support on Windows")
  192. }
  193. // Sets up a folder with trashcan versioning and tries to use a
  194. // deleted symlink to escape
  195. tmpDir := createTmpDir()
  196. defer os.RemoveAll(tmpDir)
  197. cfg := defaultCfgWrapper.RawCopy()
  198. cfg.Folders[0] = config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, tmpDir)
  199. cfg.Folders[0].Devices = []config.FolderDeviceConfiguration{
  200. {DeviceID: device1},
  201. {DeviceID: device2},
  202. }
  203. cfg.Folders[0].Versioning = config.VersioningConfiguration{
  204. Type: "trashcan",
  205. }
  206. w := createTmpWrapper(cfg)
  207. defer os.Remove(w.ConfigPath())
  208. db := db.OpenMemory()
  209. m := NewModel(w, device1, "syncthing", "dev", db, nil)
  210. m.AddFolder(cfg.Folders[0])
  211. m.ServeBackground()
  212. m.StartFolder("default")
  213. defer m.Stop()
  214. defer os.RemoveAll(tmpDir)
  215. fc := addFakeConn(m, device2)
  216. fc.folder = "default"
  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. tmpDir := createTmpDir()
  267. cfg := defaultCfgWrapper.RawCopy()
  268. cfg.Devices = append(cfg.Devices, config.NewDeviceConfiguration(device2, "device2"))
  269. cfg.Folders[0] = config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, tmpDir)
  270. cfg.Folders[0].Devices = []config.FolderDeviceConfiguration{
  271. {DeviceID: device1},
  272. {DeviceID: device2},
  273. }
  274. cfg.Folders[0].Type = ft
  275. m, fc, w := setupModelWithConnectionManual(cfg)
  276. defer func() {
  277. m.Stop()
  278. os.RemoveAll(tmpDir)
  279. os.Remove(w.ConfigPath())
  280. }()
  281. // Reach in and update the ignore matcher to one that always does
  282. // reloads when asked to, instead of checking file mtimes. This is
  283. // because we might be changing the files on disk often enough that the
  284. // mtimes will be unreliable to determine change status.
  285. m.fmut.Lock()
  286. m.folderIgnores["default"] = ignore.New(cfg.Folders[0].Filesystem(), ignore.WithChangeDetector(newAlwaysChanged()))
  287. m.fmut.Unlock()
  288. if err := m.SetIgnores("default", []string{"*ignored*"}); err != nil {
  289. panic(err)
  290. }
  291. contents := []byte("test file contents\n")
  292. otherContents := []byte("other test file contents\n")
  293. invIgn := "invalid:ignored"
  294. invDel := "invalid:deleted"
  295. ign := "ignoredNonExisting"
  296. ignExisting := "ignoredExisting"
  297. fc.addFile(invIgn, 0644, protocol.FileInfoTypeFile, contents)
  298. fc.addFile(invDel, 0644, protocol.FileInfoTypeFile, contents)
  299. fc.deleteFile(invDel)
  300. fc.addFile(ign, 0644, protocol.FileInfoTypeFile, contents)
  301. fc.addFile(ignExisting, 0644, protocol.FileInfoTypeFile, contents)
  302. if err := ioutil.WriteFile(filepath.Join(tmpDir, ignExisting), otherContents, 0644); err != nil {
  303. panic(err)
  304. }
  305. done := make(chan struct{})
  306. fc.mut.Lock()
  307. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  308. expected := map[string]struct{}{invIgn: {}, ign: {}, ignExisting: {}}
  309. for _, f := range fs {
  310. if _, ok := expected[f.Name]; !ok {
  311. t.Errorf("Unexpected file %v was added to index", f.Name)
  312. }
  313. if !f.IsInvalid() {
  314. t.Errorf("File %v wasn't marked as invalid", f.Name)
  315. }
  316. delete(expected, f.Name)
  317. }
  318. for name := range expected {
  319. t.Errorf("File %v wasn't added to index", name)
  320. }
  321. done <- struct{}{}
  322. }
  323. fc.mut.Unlock()
  324. sub := events.Default.Subscribe(events.FolderErrors)
  325. defer events.Default.Unsubscribe(sub)
  326. fc.sendIndexUpdate()
  327. timeout := time.NewTimer(5 * time.Second)
  328. select {
  329. case ev := <-sub.C():
  330. t.Fatalf("Errors while pulling: %v", ev)
  331. case <-timeout.C:
  332. t.Fatalf("timed out before index was received")
  333. case <-done:
  334. return
  335. }
  336. fc.mut.Lock()
  337. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  338. expected := map[string]struct{}{ign: {}, ignExisting: {}}
  339. for _, f := range fs {
  340. if _, ok := expected[f.Name]; !ok {
  341. t.Fatalf("Unexpected file %v was updated in index", f.Name)
  342. }
  343. if f.IsInvalid() {
  344. t.Errorf("File %v is still marked as invalid", f.Name)
  345. }
  346. // The unignored files should only have a local version,
  347. // to mark them as in conflict with any other existing versions.
  348. ev := protocol.Vector{}.Update(device1.Short())
  349. if v := f.Version; !v.Equal(ev) {
  350. t.Errorf("File %v has version %v, expected %v", f.Name, v, ev)
  351. }
  352. if f.Name == ign {
  353. if !f.Deleted {
  354. t.Errorf("File %v was not marked as deleted", f.Name)
  355. }
  356. } else if f.Deleted {
  357. t.Errorf("File %v is marked as deleted", f.Name)
  358. }
  359. delete(expected, f.Name)
  360. }
  361. for name := range expected {
  362. t.Errorf("File %v wasn't updated in index", name)
  363. }
  364. done <- struct{}{}
  365. }
  366. // Make sure pulling doesn't interfere, as index updates are racy and
  367. // thus we cannot distinguish between scan and pull results.
  368. fc.requestFn = func(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  369. return nil, nil
  370. }
  371. fc.mut.Unlock()
  372. if err := m.SetIgnores("default", []string{"*:ignored*"}); err != nil {
  373. panic(err)
  374. }
  375. timeout = time.NewTimer(5 * time.Second)
  376. select {
  377. case <-timeout.C:
  378. t.Fatalf("timed out before index was received")
  379. case <-done:
  380. return
  381. }
  382. }
  383. func TestIssue4841(t *testing.T) {
  384. m, fc, tmpDir, w := setupModelWithConnection()
  385. defer func() {
  386. m.Stop()
  387. os.RemoveAll(tmpDir)
  388. os.Remove(w.ConfigPath())
  389. }()
  390. received := make(chan protocol.FileInfo)
  391. fc.mut.Lock()
  392. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  393. if len(fs) != 1 {
  394. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  395. }
  396. if fs[0].Name != "foo" {
  397. t.Fatalf(`Sent index with file %v, should be "foo"`, fs[0].Name)
  398. }
  399. received <- fs[0]
  400. return
  401. }
  402. fc.mut.Unlock()
  403. // Setup file from remote that was ignored locally
  404. m.updateLocals(defaultFolderConfig.ID, []protocol.FileInfo{{
  405. Name: "foo",
  406. Type: protocol.FileInfoTypeFile,
  407. LocalFlags: protocol.FlagLocalIgnored,
  408. Version: protocol.Vector{}.Update(device2.Short()),
  409. }})
  410. <-received
  411. // Scan without ignore patterns with "foo" not existing locally
  412. if err := m.ScanFolder("default"); err != nil {
  413. t.Fatal("Failed scanning:", err)
  414. }
  415. f := <-received
  416. if expected := (protocol.Vector{}.Update(device1.Short())); !f.Version.Equal(expected) {
  417. t.Errorf("Got Version == %v, expected %v", f.Version, expected)
  418. }
  419. }
  420. func TestRescanIfHaveInvalidContent(t *testing.T) {
  421. m, fc, tmpDir, w := setupModelWithConnection()
  422. defer func() {
  423. m.Stop()
  424. os.RemoveAll(tmpDir)
  425. os.Remove(w.ConfigPath())
  426. }()
  427. payload := []byte("hello")
  428. if err := ioutil.WriteFile(filepath.Join(tmpDir, "foo"), payload, 0777); err != nil {
  429. t.Fatal(err)
  430. }
  431. received := make(chan protocol.FileInfo)
  432. fc.mut.Lock()
  433. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  434. if len(fs) != 1 {
  435. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  436. }
  437. if fs[0].Name != "foo" {
  438. t.Fatalf(`Sent index with file %v, should be "foo"`, fs[0].Name)
  439. }
  440. received <- fs[0]
  441. return
  442. }
  443. fc.mut.Unlock()
  444. // Scan without ignore patterns with "foo" not existing locally
  445. if err := m.ScanFolder("default"); err != nil {
  446. t.Fatal("Failed scanning:", err)
  447. }
  448. f := <-received
  449. if f.Blocks[0].WeakHash != 103547413 {
  450. t.Fatalf("unexpected weak hash: %d != 103547413", f.Blocks[0].WeakHash)
  451. }
  452. buf := make([]byte, len(payload))
  453. err := m.Request(device2, "default", "foo", 0, f.Blocks[0].Hash, f.Blocks[0].WeakHash, false, buf)
  454. if err != nil {
  455. t.Fatal(err)
  456. }
  457. if !bytes.Equal(buf, payload) {
  458. t.Errorf("%s != %s", buf, payload)
  459. }
  460. payload = []byte("bye")
  461. buf = make([]byte, len(payload))
  462. if err := ioutil.WriteFile(filepath.Join(tmpDir, "foo"), payload, 0777); err != nil {
  463. t.Fatal(err)
  464. }
  465. err = m.Request(device2, "default", "foo", 0, f.Blocks[0].Hash, f.Blocks[0].WeakHash, false, buf)
  466. if err == nil {
  467. t.Fatalf("expected failure")
  468. }
  469. select {
  470. case f := <-received:
  471. if f.Blocks[0].WeakHash != 41943361 {
  472. t.Fatalf("unexpected weak hash: %d != 41943361", f.Blocks[0].WeakHash)
  473. }
  474. case <-time.After(time.Second):
  475. t.Fatalf("timed out")
  476. }
  477. }
  478. func TestParentDeletion(t *testing.T) {
  479. m, fc, tmpDir, w := setupModelWithConnection()
  480. defer func() {
  481. m.Stop()
  482. os.RemoveAll(tmpDir)
  483. os.Remove(w.ConfigPath())
  484. }()
  485. parent := "foo"
  486. child := filepath.Join(parent, "bar")
  487. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmpDir)
  488. received := make(chan []protocol.FileInfo)
  489. fc.addFile(parent, 0777, protocol.FileInfoTypeDirectory, nil)
  490. fc.addFile(child, 0777, protocol.FileInfoTypeDirectory, nil)
  491. fc.mut.Lock()
  492. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  493. received <- fs
  494. return
  495. }
  496. fc.mut.Unlock()
  497. fc.sendIndexUpdate()
  498. // Get back index from initial setup
  499. select {
  500. case fs := <-received:
  501. if len(fs) != 2 {
  502. t.Fatalf("Sent index with %d files, should be 2", len(fs))
  503. }
  504. case <-time.After(time.Second):
  505. t.Fatalf("timed out")
  506. }
  507. // Delete parent dir
  508. if err := testFs.RemoveAll(parent); err != nil {
  509. t.Fatal(err)
  510. }
  511. // Scan only the child dir (not the parent)
  512. if err := m.ScanFolderSubdirs("default", []string{child}); err != nil {
  513. t.Fatal("Failed scanning:", err)
  514. }
  515. select {
  516. case fs := <-received:
  517. if len(fs) != 1 {
  518. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  519. }
  520. if fs[0].Name != child {
  521. t.Fatalf(`Sent index with file "%v", should be "%v"`, fs[0].Name, child)
  522. }
  523. case <-time.After(time.Second):
  524. t.Fatalf("timed out")
  525. }
  526. // Recreate the child dir on the remote
  527. fc.updateFile(child, 0777, protocol.FileInfoTypeDirectory, nil)
  528. fc.sendIndexUpdate()
  529. // Wait for the child dir to be recreated and sent to the remote
  530. select {
  531. case fs := <-received:
  532. l.Debugln("sent:", fs)
  533. found := false
  534. for _, f := range fs {
  535. if f.Name == child {
  536. if f.Deleted {
  537. t.Fatalf(`File "%v" is still deleted`, child)
  538. }
  539. found = true
  540. }
  541. }
  542. if !found {
  543. t.Fatalf(`File "%v" is missing in index`, child)
  544. }
  545. case <-time.After(5 * time.Second):
  546. t.Fatalf("timed out")
  547. }
  548. }
  549. // TestRequestSymlinkWindows checks that symlinks aren't marked as deleted on windows
  550. // Issue: https://github.com/syncthing/syncthing/issues/5125
  551. func TestRequestSymlinkWindows(t *testing.T) {
  552. if runtime.GOOS != "windows" {
  553. t.Skip("windows specific test")
  554. }
  555. m, fc, tmpDir, w := setupModelWithConnection()
  556. defer func() {
  557. m.Stop()
  558. os.RemoveAll(tmpDir)
  559. os.Remove(w.ConfigPath())
  560. }()
  561. first := make(chan struct{})
  562. fc.mut.Lock()
  563. fc.indexFn = func(folder string, fs []protocol.FileInfo) {
  564. // expected first index
  565. if len(fs) != 1 {
  566. t.Fatalf("Expected just one file in index, got %v", fs)
  567. }
  568. f := fs[0]
  569. if f.Name != "link" {
  570. t.Fatalf(`Got file info with path "%v", expected "link"`, f.Name)
  571. }
  572. if !f.IsInvalid() {
  573. t.Errorf(`File info was not marked as invalid`)
  574. }
  575. close(first)
  576. }
  577. fc.mut.Unlock()
  578. fc.addFile("link", 0644, protocol.FileInfoTypeSymlink, nil)
  579. fc.sendIndexUpdate()
  580. select {
  581. case <-first:
  582. case <-time.After(time.Second):
  583. t.Fatalf("timed out before pull was finished")
  584. }
  585. sub := events.Default.Subscribe(events.StateChanged | events.LocalIndexUpdated)
  586. defer events.Default.Unsubscribe(sub)
  587. m.ScanFolder("default")
  588. for {
  589. select {
  590. case ev := <-sub.C():
  591. switch data := ev.Data.(map[string]interface{}); {
  592. case ev.Type == events.LocalIndexUpdated:
  593. t.Fatalf("Local index was updated unexpectedly: %v", data)
  594. case ev.Type == events.StateChanged:
  595. if data["from"] == "scanning" {
  596. return
  597. }
  598. }
  599. case <-time.After(5 * time.Second):
  600. t.Fatalf("Timed out before scan finished")
  601. }
  602. }
  603. }
  604. func setupModelWithConnection() (*Model, *fakeConnection, string, *config.Wrapper) {
  605. tmpDir := createTmpDir()
  606. cfg := defaultCfgWrapper.RawCopy()
  607. cfg.Devices = append(cfg.Devices, config.NewDeviceConfiguration(device2, "device2"))
  608. cfg.Folders[0] = config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, tmpDir)
  609. cfg.Folders[0].Devices = []config.FolderDeviceConfiguration{
  610. {DeviceID: device1},
  611. {DeviceID: device2},
  612. }
  613. m, fc, w := setupModelWithConnectionManual(cfg)
  614. return m, fc, tmpDir, w
  615. }
  616. func setupModelWithConnectionManual(cfg config.Configuration) (*Model, *fakeConnection, *config.Wrapper) {
  617. w := createTmpWrapper(cfg)
  618. db := db.OpenMemory()
  619. m := NewModel(w, device1, "syncthing", "dev", db, nil)
  620. m.AddFolder(cfg.Folders[0])
  621. m.ServeBackground()
  622. m.StartFolder("default")
  623. fc := addFakeConn(m, device2)
  624. fc.folder = "default"
  625. m.ScanFolder("default")
  626. return m, fc, w
  627. }
  628. func createTmpDir() string {
  629. tmpDir, err := ioutil.TempDir("testdata", "_request-")
  630. if err != nil {
  631. panic("Failed to create temporary testing dir")
  632. }
  633. return tmpDir
  634. }
  635. func equalContents(path string, contents []byte) error {
  636. if bs, err := ioutil.ReadFile(path); err != nil {
  637. return err
  638. } else if !bytes.Equal(bs, contents) {
  639. return errors.New("incorrect data")
  640. }
  641. return nil
  642. }