requests_test.go 26 KB

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