requests_test.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bytes"
  9. "context"
  10. "errors"
  11. "io/ioutil"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "testing"
  18. "time"
  19. "github.com/syncthing/syncthing/lib/config"
  20. "github.com/syncthing/syncthing/lib/events"
  21. "github.com/syncthing/syncthing/lib/fs"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. )
  24. func TestRequestSimple(t *testing.T) {
  25. // Verify that the model performs a request and creates a file based on
  26. // an incoming index update.
  27. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  28. defer wcfgCancel()
  29. tfs := fcfg.Filesystem()
  30. defer cleanupModelAndRemoveDir(m, tfs.URI())
  31. // We listen for incoming index updates and trigger when we see one for
  32. // the expected test file.
  33. done := make(chan struct{})
  34. fc.mut.Lock()
  35. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  36. select {
  37. case <-done:
  38. t.Error("More than one index update sent")
  39. default:
  40. }
  41. for _, f := range fs {
  42. if f.Name == "testfile" {
  43. close(done)
  44. return
  45. }
  46. }
  47. }
  48. fc.mut.Unlock()
  49. // Send an update for the test file, wait for it to sync and be reported back.
  50. contents := []byte("test file contents\n")
  51. fc.addFile("testfile", 0644, protocol.FileInfoTypeFile, contents)
  52. fc.sendIndexUpdate()
  53. <-done
  54. // Verify the contents
  55. if err := equalContents(filepath.Join(tfs.URI(), "testfile"), contents); err != nil {
  56. t.Error("File did not sync correctly:", err)
  57. }
  58. }
  59. func TestSymlinkTraversalRead(t *testing.T) {
  60. // Verify that a symlink can not be traversed for reading.
  61. if runtime.GOOS == "windows" {
  62. t.Skip("no symlink support on CI")
  63. return
  64. }
  65. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  66. defer wcfgCancel()
  67. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  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(_ context.Context, folder string, fs []protocol.FileInfo) {
  73. select {
  74. case <-done:
  75. t.Error("More than one index update sent")
  76. default:
  77. }
  78. for _, f := range fs {
  79. if f.Name == "symlink" {
  80. close(done)
  81. return
  82. }
  83. }
  84. }
  85. fc.mut.Unlock()
  86. // Send an update for the symlink, wait for it to sync and be reported back.
  87. contents := []byte("..")
  88. fc.addFile("symlink", 0644, protocol.FileInfoTypeSymlink, contents)
  89. fc.sendIndexUpdate()
  90. <-done
  91. // Request a file by traversing the symlink
  92. res, err := m.Request(device1, "default", "symlink/requests_test.go", 0, 10, 0, nil, 0, false)
  93. if err == nil || res != nil {
  94. t.Error("Managed to traverse symlink")
  95. }
  96. }
  97. func TestSymlinkTraversalWrite(t *testing.T) {
  98. // Verify that a symlink can not be traversed for writing.
  99. if runtime.GOOS == "windows" {
  100. t.Skip("no symlink support on CI")
  101. return
  102. }
  103. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  104. defer wcfgCancel()
  105. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  106. // We listen for incoming index updates and trigger when we see one for
  107. // the expected names.
  108. done := make(chan struct{}, 1)
  109. badReq := make(chan string, 1)
  110. badIdx := make(chan string, 1)
  111. fc.mut.Lock()
  112. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  113. for _, f := range fs {
  114. if f.Name == "symlink" {
  115. done <- struct{}{}
  116. return
  117. }
  118. if strings.HasPrefix(f.Name, "symlink") {
  119. badIdx <- f.Name
  120. return
  121. }
  122. }
  123. }
  124. fc.requestFn = func(_ context.Context, folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  125. if name != "symlink" && strings.HasPrefix(name, "symlink") {
  126. badReq <- name
  127. }
  128. return fc.fileData[name], nil
  129. }
  130. fc.mut.Unlock()
  131. // Send an update for the symlink, wait for it to sync and be reported back.
  132. contents := []byte("..")
  133. fc.addFile("symlink", 0644, protocol.FileInfoTypeSymlink, contents)
  134. fc.sendIndexUpdate()
  135. <-done
  136. // Send an update for things behind the symlink, wait for requests for
  137. // blocks for any of them to come back, or index entries. Hopefully none
  138. // of that should happen.
  139. contents = []byte("testdata testdata\n")
  140. fc.addFile("symlink/testfile", 0644, protocol.FileInfoTypeFile, contents)
  141. fc.addFile("symlink/testdir", 0644, protocol.FileInfoTypeDirectory, contents)
  142. fc.addFile("symlink/testsyml", 0644, protocol.FileInfoTypeSymlink, contents)
  143. fc.sendIndexUpdate()
  144. select {
  145. case name := <-badReq:
  146. t.Fatal("Should not have requested the data for", name)
  147. case name := <-badIdx:
  148. t.Fatal("Should not have sent the index entry for", name)
  149. case <-time.After(3 * time.Second):
  150. // Unfortunately not much else to trigger on here. The puller sleep
  151. // interval is 1s so if we didn't get any requests within two
  152. // iterations we should be fine.
  153. }
  154. }
  155. func TestRequestCreateTmpSymlink(t *testing.T) {
  156. // Test that an update for a temporary file is invalidated
  157. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  158. defer wcfgCancel()
  159. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  160. // We listen for incoming index updates and trigger when we see one for
  161. // the expected test file.
  162. goodIdx := make(chan struct{})
  163. name := fs.TempName("testlink")
  164. fc.mut.Lock()
  165. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  166. for _, f := range fs {
  167. if f.Name == name {
  168. if f.IsInvalid() {
  169. goodIdx <- struct{}{}
  170. } else {
  171. t.Error("Received index with non-invalid temporary file")
  172. close(goodIdx)
  173. }
  174. return
  175. }
  176. }
  177. }
  178. fc.mut.Unlock()
  179. // Send an update for the test file, wait for it to sync and be reported back.
  180. fc.addFile(name, 0644, protocol.FileInfoTypeSymlink, []byte(".."))
  181. fc.sendIndexUpdate()
  182. select {
  183. case <-goodIdx:
  184. case <-time.After(3 * time.Second):
  185. t.Fatal("Timed out without index entry being sent")
  186. }
  187. }
  188. func TestRequestVersioningSymlinkAttack(t *testing.T) {
  189. if runtime.GOOS == "windows" {
  190. t.Skip("no symlink support on Windows")
  191. }
  192. // Sets up a folder with trashcan versioning and tries to use a
  193. // deleted symlink to escape
  194. w, fcfg, wCancel := tmpDefaultWrapper()
  195. defer wCancel()
  196. defer func() {
  197. os.RemoveAll(fcfg.Filesystem().URI())
  198. os.Remove(w.ConfigPath())
  199. }()
  200. fcfg.Versioning = config.VersioningConfiguration{Type: "trashcan"}
  201. setFolder(t, w, fcfg)
  202. m, fc := setupModelWithConnectionFromWrapper(t, w)
  203. defer cleanupModel(m)
  204. // Create a temporary directory that we will use as target to see if
  205. // we can escape to it
  206. tmpdir, err := ioutil.TempDir("", "syncthing-test")
  207. if err != nil {
  208. t.Fatal(err)
  209. }
  210. defer os.RemoveAll(tmpdir)
  211. // We listen for incoming index updates and trigger when we see one for
  212. // the expected test file.
  213. idx := make(chan int)
  214. fc.mut.Lock()
  215. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  216. idx <- len(fs)
  217. }
  218. fc.mut.Unlock()
  219. waitForIdx := func() {
  220. select {
  221. case c := <-idx:
  222. if c == 0 {
  223. t.Fatal("Got empty index update")
  224. }
  225. case <-time.After(5 * time.Second):
  226. t.Fatal("timed out before receiving index update")
  227. }
  228. }
  229. // Send an update for the test file, wait for it to sync and be reported back.
  230. fc.addFile("foo", 0644, protocol.FileInfoTypeSymlink, []byte(tmpdir))
  231. fc.sendIndexUpdate()
  232. waitForIdx()
  233. // Delete the symlink, hoping for it to get versioned
  234. fc.deleteFile("foo")
  235. fc.sendIndexUpdate()
  236. waitForIdx()
  237. // Recreate foo and a file in it with some data
  238. fc.updateFile("foo", 0755, protocol.FileInfoTypeDirectory, nil)
  239. fc.addFile("foo/test", 0644, protocol.FileInfoTypeFile, []byte("testtesttest"))
  240. fc.sendIndexUpdate()
  241. waitForIdx()
  242. // Remove the test file and see if it escaped
  243. fc.deleteFile("foo/test")
  244. fc.sendIndexUpdate()
  245. waitForIdx()
  246. path := filepath.Join(tmpdir, "test")
  247. if _, err := os.Lstat(path); !os.IsNotExist(err) {
  248. t.Fatal("File escaped to", path)
  249. }
  250. }
  251. func TestPullInvalidIgnoredSO(t *testing.T) {
  252. pullInvalidIgnored(t, config.FolderTypeSendOnly)
  253. }
  254. func TestPullInvalidIgnoredSR(t *testing.T) {
  255. pullInvalidIgnored(t, config.FolderTypeSendReceive)
  256. }
  257. // This test checks that (un-)ignored/invalid/deleted files are treated as expected.
  258. func pullInvalidIgnored(t *testing.T, ft config.FolderType) {
  259. w, wCancel := createTmpWrapper(defaultCfgWrapper.RawCopy())
  260. defer wCancel()
  261. fcfg := testFolderConfigTmp()
  262. fss := fcfg.Filesystem()
  263. fcfg.Type = ft
  264. setFolder(t, w, fcfg)
  265. m := setupModel(t, w)
  266. defer cleanupModelAndRemoveDir(m, fss.URI())
  267. folderIgnoresAlwaysReload(t, m, fcfg)
  268. fc := addFakeConn(m, device1)
  269. fc.folder = "default"
  270. if err := m.SetIgnores("default", []string{"*ignored*"}); err != nil {
  271. panic(err)
  272. }
  273. contents := []byte("test file contents\n")
  274. otherContents := []byte("other test file contents\n")
  275. invIgn := "invalid:ignored"
  276. invDel := "invalid:deleted"
  277. ign := "ignoredNonExisting"
  278. ignExisting := "ignoredExisting"
  279. fc.addFile(invIgn, 0644, protocol.FileInfoTypeFile, contents)
  280. fc.addFile(invDel, 0644, protocol.FileInfoTypeFile, contents)
  281. fc.deleteFile(invDel)
  282. fc.addFile(ign, 0644, protocol.FileInfoTypeFile, contents)
  283. fc.addFile(ignExisting, 0644, protocol.FileInfoTypeFile, contents)
  284. if err := writeFile(fss, ignExisting, otherContents, 0644); err != nil {
  285. panic(err)
  286. }
  287. done := make(chan struct{})
  288. fc.mut.Lock()
  289. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  290. expected := map[string]struct{}{invIgn: {}, ign: {}, ignExisting: {}}
  291. for _, f := range fs {
  292. if _, ok := expected[f.Name]; !ok {
  293. t.Errorf("Unexpected file %v was added to index", f.Name)
  294. }
  295. if !f.IsInvalid() {
  296. t.Errorf("File %v wasn't marked as invalid", f.Name)
  297. }
  298. delete(expected, f.Name)
  299. }
  300. for name := range expected {
  301. t.Errorf("File %v wasn't added to index", name)
  302. }
  303. close(done)
  304. }
  305. fc.mut.Unlock()
  306. sub := m.evLogger.Subscribe(events.FolderErrors)
  307. defer sub.Unsubscribe()
  308. fc.sendIndexUpdate()
  309. select {
  310. case ev := <-sub.C():
  311. t.Fatalf("Errors while scanning/pulling: %v", ev)
  312. case <-time.After(5 * time.Second):
  313. t.Fatalf("timed out before index was received")
  314. case <-done:
  315. }
  316. done = make(chan struct{})
  317. expected := map[string]struct{}{ign: {}, ignExisting: {}}
  318. // The indexes will normally arrive in one update, but it is possible
  319. // that they arrive in separate ones.
  320. fc.mut.Lock()
  321. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  322. for _, f := range fs {
  323. if _, ok := expected[f.Name]; !ok {
  324. t.Errorf("Unexpected file %v was updated in index", f.Name)
  325. continue
  326. }
  327. if f.IsInvalid() {
  328. t.Errorf("File %v is still marked as invalid", f.Name)
  329. }
  330. if f.Name == ign {
  331. // The unignored deleted file should have an
  332. // empty version, to make it not override
  333. // existing global files.
  334. if !f.Deleted {
  335. t.Errorf("File %v was not marked as deleted", f.Name)
  336. }
  337. if len(f.Version.Counters) != 0 {
  338. t.Errorf("File %v has version %v, expected empty", f.Name, f.Version)
  339. }
  340. } else {
  341. // The unignored existing file should have a
  342. // version with only a local counter, to make
  343. // it conflict changed global files.
  344. if f.Deleted {
  345. t.Errorf("File %v is marked as deleted", f.Name)
  346. }
  347. if len(f.Version.Counters) != 1 || f.Version.Counter(myID.Short()) == 0 {
  348. t.Errorf("File %v has version %v, expected one entry for ourselves", f.Name, f.Version)
  349. }
  350. }
  351. delete(expected, f.Name)
  352. }
  353. if len(expected) == 0 {
  354. close(done)
  355. }
  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(_ context.Context, 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.Fatal("timed out before receiving index updates for all existing files, missing", expected)
  369. case <-done:
  370. }
  371. }
  372. func TestIssue4841(t *testing.T) {
  373. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  374. defer wcfgCancel()
  375. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  376. received := make(chan []protocol.FileInfo)
  377. fc.mut.Lock()
  378. fc.indexFn = func(_ context.Context, _ string, fs []protocol.FileInfo) {
  379. received <- fs
  380. }
  381. fc.mut.Unlock()
  382. checkReceived := func(fs []protocol.FileInfo) protocol.FileInfo {
  383. t.Helper()
  384. if len(fs) != 1 {
  385. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  386. }
  387. if fs[0].Name != "foo" {
  388. t.Fatalf(`Sent index with file %v, should be "foo"`, fs[0].Name)
  389. }
  390. return fs[0]
  391. }
  392. // Setup file from remote that was ignored locally
  393. folder := m.folderRunners[defaultFolderConfig.ID].(*sendReceiveFolder)
  394. folder.updateLocals([]protocol.FileInfo{{
  395. Name: "foo",
  396. Type: protocol.FileInfoTypeFile,
  397. LocalFlags: protocol.FlagLocalIgnored,
  398. Version: protocol.Vector{}.Update(device1.Short()),
  399. }})
  400. checkReceived(<-received)
  401. // Scan without ignore patterns with "foo" not existing locally
  402. if err := m.ScanFolder("default"); err != nil {
  403. t.Fatal("Failed scanning:", err)
  404. }
  405. f := checkReceived(<-received)
  406. if !f.Version.Equal(protocol.Vector{}) {
  407. t.Errorf("Got Version == %v, expected empty version", f.Version)
  408. }
  409. }
  410. func TestRescanIfHaveInvalidContent(t *testing.T) {
  411. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  412. defer wcfgCancel()
  413. tfs := fcfg.Filesystem()
  414. defer cleanupModelAndRemoveDir(m, tfs.URI())
  415. payload := []byte("hello")
  416. must(t, writeFile(tfs, "foo", payload, 0777))
  417. received := make(chan []protocol.FileInfo)
  418. fc.mut.Lock()
  419. fc.indexFn = func(_ context.Context, _ string, fs []protocol.FileInfo) {
  420. received <- fs
  421. }
  422. fc.mut.Unlock()
  423. checkReceived := func(fs []protocol.FileInfo) protocol.FileInfo {
  424. t.Helper()
  425. if len(fs) != 1 {
  426. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  427. }
  428. if fs[0].Name != "foo" {
  429. t.Fatalf(`Sent index with file %v, should be "foo"`, fs[0].Name)
  430. }
  431. return fs[0]
  432. }
  433. // Scan without ignore patterns with "foo" not existing locally
  434. if err := m.ScanFolder("default"); err != nil {
  435. t.Fatal("Failed scanning:", err)
  436. }
  437. f := checkReceived(<-received)
  438. if f.Blocks[0].WeakHash != 103547413 {
  439. t.Fatalf("unexpected weak hash: %d != 103547413", f.Blocks[0].WeakHash)
  440. }
  441. res, err := m.Request(device1, "default", "foo", 0, int32(len(payload)), 0, f.Blocks[0].Hash, f.Blocks[0].WeakHash, false)
  442. if err != nil {
  443. t.Fatal(err)
  444. }
  445. buf := res.Data()
  446. if !bytes.Equal(buf, payload) {
  447. t.Errorf("%s != %s", buf, payload)
  448. }
  449. payload = []byte("bye")
  450. buf = make([]byte, len(payload))
  451. must(t, writeFile(tfs, "foo", payload, 0777))
  452. _, err = m.Request(device1, "default", "foo", 0, int32(len(payload)), 0, f.Blocks[0].Hash, f.Blocks[0].WeakHash, false)
  453. if err == nil {
  454. t.Fatalf("expected failure")
  455. }
  456. select {
  457. case fs := <-received:
  458. f := checkReceived(fs)
  459. if f.Blocks[0].WeakHash != 41943361 {
  460. t.Fatalf("unexpected weak hash: %d != 41943361", f.Blocks[0].WeakHash)
  461. }
  462. case <-time.After(time.Second):
  463. t.Fatalf("timed out")
  464. }
  465. }
  466. func TestParentDeletion(t *testing.T) {
  467. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  468. defer wcfgCancel()
  469. testFs := fcfg.Filesystem()
  470. defer cleanupModelAndRemoveDir(m, testFs.URI())
  471. parent := "foo"
  472. child := filepath.Join(parent, "bar")
  473. received := make(chan []protocol.FileInfo)
  474. fc.addFile(parent, 0777, protocol.FileInfoTypeDirectory, nil)
  475. fc.addFile(child, 0777, protocol.FileInfoTypeDirectory, nil)
  476. fc.mut.Lock()
  477. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  478. received <- fs
  479. }
  480. fc.mut.Unlock()
  481. fc.sendIndexUpdate()
  482. // Get back index from initial setup
  483. select {
  484. case fs := <-received:
  485. if len(fs) != 2 {
  486. t.Fatalf("Sent index with %d files, should be 2", len(fs))
  487. }
  488. case <-time.After(time.Second):
  489. t.Fatalf("timed out")
  490. }
  491. // Delete parent dir
  492. must(t, testFs.RemoveAll(parent))
  493. // Scan only the child dir (not the parent)
  494. if err := m.ScanFolderSubdirs("default", []string{child}); err != nil {
  495. t.Fatal("Failed scanning:", err)
  496. }
  497. select {
  498. case fs := <-received:
  499. if len(fs) != 1 {
  500. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  501. }
  502. if fs[0].Name != child {
  503. t.Fatalf(`Sent index with file "%v", should be "%v"`, fs[0].Name, child)
  504. }
  505. case <-time.After(time.Second):
  506. t.Fatalf("timed out")
  507. }
  508. // Recreate the child dir on the remote
  509. fc.updateFile(child, 0777, protocol.FileInfoTypeDirectory, nil)
  510. fc.sendIndexUpdate()
  511. // Wait for the child dir to be recreated and sent to the remote
  512. select {
  513. case fs := <-received:
  514. l.Debugln("sent:", fs)
  515. found := false
  516. for _, f := range fs {
  517. if f.Name == child {
  518. if f.Deleted {
  519. t.Fatalf(`File "%v" is still deleted`, child)
  520. }
  521. found = true
  522. }
  523. }
  524. if !found {
  525. t.Fatalf(`File "%v" is missing in index`, child)
  526. }
  527. case <-time.After(5 * time.Second):
  528. t.Fatalf("timed out")
  529. }
  530. }
  531. // TestRequestSymlinkWindows checks that symlinks aren't marked as deleted on windows
  532. // Issue: https://github.com/syncthing/syncthing/issues/5125
  533. func TestRequestSymlinkWindows(t *testing.T) {
  534. if runtime.GOOS != "windows" {
  535. t.Skip("windows specific test")
  536. }
  537. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  538. defer wcfgCancel()
  539. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem().URI())
  540. received := make(chan []protocol.FileInfo)
  541. fc.mut.Lock()
  542. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  543. select {
  544. case <-received:
  545. t.Error("More than one index update sent")
  546. default:
  547. }
  548. received <- fs
  549. }
  550. fc.mut.Unlock()
  551. fc.addFile("link", 0644, protocol.FileInfoTypeSymlink, nil)
  552. fc.sendIndexUpdate()
  553. select {
  554. case fs := <-received:
  555. close(received)
  556. // expected first index
  557. if len(fs) != 1 {
  558. t.Fatalf("Expected just one file in index, got %v", fs)
  559. }
  560. f := fs[0]
  561. if f.Name != "link" {
  562. t.Fatalf(`Got file info with path "%v", expected "link"`, f.Name)
  563. }
  564. if !f.IsInvalid() {
  565. t.Errorf(`File info was not marked as invalid`)
  566. }
  567. case <-time.After(time.Second):
  568. t.Fatalf("timed out before pull was finished")
  569. }
  570. sub := m.evLogger.Subscribe(events.StateChanged | events.LocalIndexUpdated)
  571. defer sub.Unsubscribe()
  572. m.ScanFolder("default")
  573. for {
  574. select {
  575. case ev := <-sub.C():
  576. switch data := ev.Data.(map[string]interface{}); {
  577. case ev.Type == events.LocalIndexUpdated:
  578. t.Fatalf("Local index was updated unexpectedly: %v", data)
  579. case ev.Type == events.StateChanged:
  580. if data["from"] == "scanning" {
  581. return
  582. }
  583. }
  584. case <-time.After(5 * time.Second):
  585. t.Fatalf("Timed out before scan finished")
  586. }
  587. }
  588. }
  589. func equalContents(path string, contents []byte) error {
  590. if bs, err := ioutil.ReadFile(path); err != nil {
  591. return err
  592. } else if !bytes.Equal(bs, contents) {
  593. return errors.New("incorrect data")
  594. }
  595. return nil
  596. }
  597. func TestRequestRemoteRenameChanged(t *testing.T) {
  598. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  599. defer wcfgCancel()
  600. tfs := fcfg.Filesystem()
  601. tmpDir := tfs.URI()
  602. defer cleanupModelAndRemoveDir(m, tfs.URI())
  603. received := make(chan []protocol.FileInfo)
  604. fc.mut.Lock()
  605. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  606. select {
  607. case <-received:
  608. t.Error("More than one index update sent")
  609. default:
  610. }
  611. received <- fs
  612. }
  613. fc.mut.Unlock()
  614. // setup
  615. a := "a"
  616. b := "b"
  617. data := map[string][]byte{
  618. a: []byte("aData"),
  619. b: []byte("bData"),
  620. }
  621. for _, n := range [2]string{a, b} {
  622. fc.addFile(n, 0644, protocol.FileInfoTypeFile, data[n])
  623. }
  624. fc.sendIndexUpdate()
  625. select {
  626. case fs := <-received:
  627. close(received)
  628. if len(fs) != 2 {
  629. t.Fatalf("Received index with %v indexes instead of 2", len(fs))
  630. }
  631. case <-time.After(10 * time.Second):
  632. t.Fatal("timed out")
  633. }
  634. for _, n := range [2]string{a, b} {
  635. must(t, equalContents(filepath.Join(tmpDir, n), data[n]))
  636. }
  637. var gotA, gotB, gotConfl bool
  638. done := make(chan struct{})
  639. fc.mut.Lock()
  640. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  641. select {
  642. case <-done:
  643. t.Error("Received more index updates than expected")
  644. return
  645. default:
  646. }
  647. for _, f := range fs {
  648. switch {
  649. case f.Name == a:
  650. if gotA {
  651. t.Error("Got more than one index update for", f.Name)
  652. }
  653. gotA = true
  654. case f.Name == b:
  655. if gotB {
  656. t.Error("Got more than one index update for", f.Name)
  657. }
  658. if f.Version.Counter(fc.id.Short()) == 0 {
  659. // This index entry might be superseeded
  660. // by the final one or sent before it separately.
  661. break
  662. }
  663. gotB = true
  664. case strings.HasPrefix(f.Name, "b.sync-conflict-"):
  665. if gotConfl {
  666. t.Error("Got more than one index update for conflicts of", f.Name)
  667. }
  668. gotConfl = true
  669. default:
  670. t.Error("Got unexpected file in index update", f.Name)
  671. }
  672. }
  673. if gotA && gotB && gotConfl {
  674. close(done)
  675. }
  676. }
  677. fc.mut.Unlock()
  678. fd, err := tfs.OpenFile(b, fs.OptReadWrite, 0644)
  679. if err != nil {
  680. t.Fatal(err)
  681. }
  682. otherData := []byte("otherData")
  683. if _, err = fd.Write(otherData); err != nil {
  684. t.Fatal(err)
  685. }
  686. fd.Close()
  687. // rename
  688. fc.deleteFile(a)
  689. fc.updateFile(b, 0644, protocol.FileInfoTypeFile, data[a])
  690. // Make sure the remote file for b is newer and thus stays global -> local conflict
  691. fc.mut.Lock()
  692. for i := range fc.files {
  693. if fc.files[i].Name == b {
  694. fc.files[i].ModifiedS += 100
  695. break
  696. }
  697. }
  698. fc.mut.Unlock()
  699. fc.sendIndexUpdate()
  700. select {
  701. case <-done:
  702. case <-time.After(10 * time.Second):
  703. t.Errorf("timed out without receiving all expected index updates")
  704. }
  705. // Check outcome
  706. tfs.Walk(".", func(path string, info fs.FileInfo, err error) error {
  707. switch {
  708. case path == a:
  709. t.Errorf(`File "a" was not removed`)
  710. case path == b:
  711. if err := equalContents(filepath.Join(tmpDir, b), data[a]); err != nil {
  712. t.Error(`File "b" has unexpected content (renamed from a on remote)`)
  713. }
  714. case strings.HasPrefix(path, b+".sync-conflict-"):
  715. if err := equalContents(filepath.Join(tmpDir, path), otherData); err != nil {
  716. t.Error(`Sync conflict of "b" has unexptected content`)
  717. }
  718. case path == "." || strings.HasPrefix(path, ".stfolder"):
  719. default:
  720. t.Error("Found unexpected file", path)
  721. }
  722. return nil
  723. })
  724. }
  725. func TestRequestRemoteRenameConflict(t *testing.T) {
  726. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  727. defer wcfgCancel()
  728. tfs := fcfg.Filesystem()
  729. tmpDir := tfs.URI()
  730. defer cleanupModelAndRemoveDir(m, tmpDir)
  731. recv := make(chan int)
  732. fc.mut.Lock()
  733. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  734. recv <- len(fs)
  735. }
  736. fc.mut.Unlock()
  737. // setup
  738. a := "a"
  739. b := "b"
  740. data := map[string][]byte{
  741. a: []byte("aData"),
  742. b: []byte("bData"),
  743. }
  744. for _, n := range [2]string{a, b} {
  745. fc.addFile(n, 0644, protocol.FileInfoTypeFile, data[n])
  746. }
  747. fc.sendIndexUpdate()
  748. select {
  749. case i := <-recv:
  750. if i != 2 {
  751. t.Fatalf("received %v items in index, expected 1", i)
  752. }
  753. case <-time.After(10 * time.Second):
  754. t.Fatal("timed out")
  755. }
  756. for _, n := range [2]string{a, b} {
  757. must(t, equalContents(filepath.Join(tmpDir, n), data[n]))
  758. }
  759. fd, err := tfs.OpenFile(b, fs.OptReadWrite, 0644)
  760. if err != nil {
  761. t.Fatal(err)
  762. }
  763. otherData := []byte("otherData")
  764. if _, err = fd.Write(otherData); err != nil {
  765. t.Fatal(err)
  766. }
  767. fd.Close()
  768. m.ScanFolders()
  769. select {
  770. case i := <-recv:
  771. if i != 1 {
  772. t.Fatalf("received %v items in index, expected 1", i)
  773. }
  774. case <-time.After(10 * time.Second):
  775. t.Fatal("timed out")
  776. }
  777. // make sure the following rename is more recent (not concurrent)
  778. time.Sleep(2 * time.Second)
  779. // rename
  780. fc.deleteFile(a)
  781. fc.updateFile(b, 0644, protocol.FileInfoTypeFile, data[a])
  782. fc.sendIndexUpdate()
  783. select {
  784. case <-recv:
  785. case <-time.After(10 * time.Second):
  786. t.Fatal("timed out")
  787. }
  788. // Check outcome
  789. foundB := false
  790. foundBConfl := false
  791. tfs.Walk(".", func(path string, info fs.FileInfo, err error) error {
  792. switch {
  793. case path == a:
  794. t.Errorf(`File "a" was not removed`)
  795. case path == b:
  796. foundB = true
  797. case strings.HasPrefix(path, b) && strings.Contains(path, ".sync-conflict-"):
  798. foundBConfl = true
  799. }
  800. return nil
  801. })
  802. if !foundB {
  803. t.Errorf(`File "b" was removed`)
  804. }
  805. if !foundBConfl {
  806. t.Errorf(`No conflict file for "b" was created`)
  807. }
  808. }
  809. func TestRequestDeleteChanged(t *testing.T) {
  810. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  811. defer wcfgCancel()
  812. tfs := fcfg.Filesystem()
  813. defer cleanupModelAndRemoveDir(m, tfs.URI())
  814. done := make(chan struct{})
  815. fc.mut.Lock()
  816. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  817. select {
  818. case <-done:
  819. t.Error("More than one index update sent")
  820. default:
  821. }
  822. close(done)
  823. }
  824. fc.mut.Unlock()
  825. // setup
  826. a := "a"
  827. data := []byte("aData")
  828. fc.addFile(a, 0644, protocol.FileInfoTypeFile, data)
  829. fc.sendIndexUpdate()
  830. select {
  831. case <-done:
  832. done = make(chan struct{})
  833. case <-time.After(10 * time.Second):
  834. t.Fatal("timed out")
  835. }
  836. fc.mut.Lock()
  837. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  838. select {
  839. case <-done:
  840. t.Error("More than one index update sent")
  841. default:
  842. }
  843. close(done)
  844. }
  845. fc.mut.Unlock()
  846. fd, err := tfs.OpenFile(a, fs.OptReadWrite, 0644)
  847. if err != nil {
  848. t.Fatal(err)
  849. }
  850. otherData := []byte("otherData")
  851. if _, err = fd.Write(otherData); err != nil {
  852. t.Fatal(err)
  853. }
  854. fd.Close()
  855. // rename
  856. fc.deleteFile(a)
  857. fc.sendIndexUpdate()
  858. select {
  859. case <-done:
  860. case <-time.After(10 * time.Second):
  861. t.Fatal("timed out")
  862. }
  863. // Check outcome
  864. if _, err := tfs.Lstat(a); err != nil {
  865. if fs.IsNotExist(err) {
  866. t.Error(`Modified file "a" was removed`)
  867. } else {
  868. t.Error(`Error stating file "a":`, err)
  869. }
  870. }
  871. }
  872. func TestNeedFolderFiles(t *testing.T) {
  873. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  874. defer wcfgCancel()
  875. tfs := fcfg.Filesystem()
  876. tmpDir := tfs.URI()
  877. defer cleanupModelAndRemoveDir(m, tmpDir)
  878. sub := m.evLogger.Subscribe(events.RemoteIndexUpdated)
  879. defer sub.Unsubscribe()
  880. errPreventSync := errors.New("you aren't getting any of this")
  881. fc.mut.Lock()
  882. fc.requestFn = func(context.Context, string, string, int64, int, []byte, bool) ([]byte, error) {
  883. return nil, errPreventSync
  884. }
  885. fc.mut.Unlock()
  886. data := []byte("foo")
  887. num := 20
  888. for i := 0; i < num; i++ {
  889. fc.addFile(strconv.Itoa(i), 0644, protocol.FileInfoTypeFile, data)
  890. }
  891. fc.sendIndexUpdate()
  892. select {
  893. case <-sub.C():
  894. case <-time.After(5 * time.Second):
  895. t.Fatal("Timed out before receiving index")
  896. }
  897. progress, queued, rest, err := m.NeedFolderFiles(fcfg.ID, 1, 100)
  898. must(t, err)
  899. if got := len(progress) + len(queued) + len(rest); got != num {
  900. t.Errorf("Got %v needed items, expected %v", got, num)
  901. }
  902. exp := 10
  903. for page := 1; page < 3; page++ {
  904. progress, queued, rest, err := m.NeedFolderFiles(fcfg.ID, page, exp)
  905. must(t, err)
  906. if got := len(progress) + len(queued) + len(rest); got != exp {
  907. t.Errorf("Got %v needed items on page %v, expected %v", got, page, exp)
  908. }
  909. }
  910. }
  911. // TestIgnoreDeleteUnignore checks that the deletion of an ignored file is not
  912. // propagated upon un-ignoring.
  913. // https://github.com/syncthing/syncthing/issues/6038
  914. func TestIgnoreDeleteUnignore(t *testing.T) {
  915. w, fcfg, wCancel := tmpDefaultWrapper()
  916. defer wCancel()
  917. m := setupModel(t, w)
  918. fss := fcfg.Filesystem()
  919. tmpDir := fss.URI()
  920. defer cleanupModelAndRemoveDir(m, tmpDir)
  921. folderIgnoresAlwaysReload(t, m, fcfg)
  922. m.ScanFolders()
  923. fc := addFakeConn(m, device1)
  924. fc.folder = "default"
  925. fc.mut.Lock()
  926. fc.mut.Unlock()
  927. file := "foobar"
  928. contents := []byte("test file contents\n")
  929. basicCheck := func(fs []protocol.FileInfo) {
  930. t.Helper()
  931. if len(fs) != 1 {
  932. t.Fatal("expected a single index entry, got", len(fs))
  933. } else if fs[0].Name != file {
  934. t.Fatalf("expected a index entry for %v, got one for %v", file, fs[0].Name)
  935. }
  936. }
  937. done := make(chan struct{})
  938. fc.mut.Lock()
  939. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  940. basicCheck(fs)
  941. close(done)
  942. }
  943. fc.mut.Unlock()
  944. if err := writeFile(fss, file, contents, 0644); err != nil {
  945. panic(err)
  946. }
  947. m.ScanFolders()
  948. select {
  949. case <-time.After(5 * time.Second):
  950. t.Fatalf("timed out before index was received")
  951. case <-done:
  952. }
  953. done = make(chan struct{})
  954. fc.mut.Lock()
  955. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  956. basicCheck(fs)
  957. f := fs[0]
  958. if !f.IsInvalid() {
  959. t.Errorf("Received non-invalid index update")
  960. }
  961. close(done)
  962. }
  963. fc.mut.Unlock()
  964. if err := m.SetIgnores("default", []string{"foobar"}); err != nil {
  965. panic(err)
  966. }
  967. select {
  968. case <-time.After(5 * time.Second):
  969. t.Fatal("timed out before receiving index update")
  970. case <-done:
  971. }
  972. done = make(chan struct{})
  973. fc.mut.Lock()
  974. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  975. basicCheck(fs)
  976. f := fs[0]
  977. if f.IsInvalid() {
  978. t.Errorf("Received invalid index update")
  979. }
  980. if !f.Version.Equal(protocol.Vector{}) && f.Deleted {
  981. t.Error("Received deleted index entry with non-empty version")
  982. }
  983. l.Infoln(f)
  984. close(done)
  985. }
  986. fc.mut.Unlock()
  987. if err := fss.Remove(file); err != nil {
  988. t.Fatal(err)
  989. }
  990. if err := m.SetIgnores("default", []string{}); err != nil {
  991. panic(err)
  992. }
  993. select {
  994. case <-time.After(5 * time.Second):
  995. t.Fatalf("timed out before index was received")
  996. case <-done:
  997. }
  998. }
  999. // TestRequestLastFileProgress checks that the last pulled file (here only) is registered
  1000. // as in progress.
  1001. func TestRequestLastFileProgress(t *testing.T) {
  1002. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  1003. defer wcfgCancel()
  1004. tfs := fcfg.Filesystem()
  1005. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1006. done := make(chan struct{})
  1007. fc.mut.Lock()
  1008. fc.requestFn = func(_ context.Context, folder, name string, _ int64, _ int, _ []byte, _ bool) ([]byte, error) {
  1009. defer close(done)
  1010. progress, queued, rest, err := m.NeedFolderFiles(folder, 1, 10)
  1011. must(t, err)
  1012. if len(queued)+len(rest) != 0 {
  1013. t.Error(`There should not be any queued or "rest" items`)
  1014. }
  1015. if len(progress) != 1 {
  1016. t.Error("Expected exactly one item in progress.")
  1017. }
  1018. return fc.fileData[name], nil
  1019. }
  1020. fc.mut.Unlock()
  1021. contents := []byte("test file contents\n")
  1022. fc.addFile("testfile", 0644, protocol.FileInfoTypeFile, contents)
  1023. fc.sendIndexUpdate()
  1024. select {
  1025. case <-done:
  1026. case <-time.After(5 * time.Second):
  1027. t.Fatal("Timed out before file was requested")
  1028. }
  1029. }
  1030. func TestRequestIndexSenderPause(t *testing.T) {
  1031. done := make(chan struct{})
  1032. defer close(done)
  1033. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  1034. defer wcfgCancel()
  1035. tfs := fcfg.Filesystem()
  1036. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1037. indexChan := make(chan []protocol.FileInfo)
  1038. fc.mut.Lock()
  1039. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  1040. select {
  1041. case indexChan <- fs:
  1042. case <-done:
  1043. }
  1044. }
  1045. fc.mut.Unlock()
  1046. var seq int64 = 1
  1047. files := []protocol.FileInfo{{Name: "foo", Size: 10, Version: protocol.Vector{}.Update(myID.Short()), Sequence: seq}}
  1048. // Both devices connected, noone paused
  1049. localIndexUpdate(m, fcfg.ID, files)
  1050. select {
  1051. case <-time.After(5 * time.Second):
  1052. t.Fatal("timed out before receiving index")
  1053. case <-indexChan:
  1054. }
  1055. // Remote paused
  1056. cc := basicClusterConfig(device1, myID, fcfg.ID)
  1057. cc.Folders[0].Paused = true
  1058. m.ClusterConfig(device1, cc)
  1059. seq++
  1060. files[0].Sequence = seq
  1061. files[0].Version = files[0].Version.Update(myID.Short())
  1062. localIndexUpdate(m, fcfg.ID, files)
  1063. // I don't see what to hook into to ensure an index update is not sent.
  1064. dur := 50 * time.Millisecond
  1065. if !testing.Short() {
  1066. dur = 2 * time.Second
  1067. }
  1068. select {
  1069. case <-time.After(dur):
  1070. case <-indexChan:
  1071. t.Error("Received index despite remote being paused")
  1072. }
  1073. // Remote unpaused
  1074. cc.Folders[0].Paused = false
  1075. m.ClusterConfig(device1, cc)
  1076. select {
  1077. case <-time.After(5 * time.Second):
  1078. t.Fatal("timed out before receiving index")
  1079. case <-indexChan:
  1080. }
  1081. // Local paused and resume
  1082. pauseFolder(t, m.cfg, fcfg.ID, true)
  1083. pauseFolder(t, m.cfg, fcfg.ID, false)
  1084. seq++
  1085. files[0].Sequence = seq
  1086. files[0].Version = files[0].Version.Update(myID.Short())
  1087. localIndexUpdate(m, fcfg.ID, files)
  1088. select {
  1089. case <-time.After(5 * time.Second):
  1090. t.Fatal("timed out before receiving index")
  1091. case <-indexChan:
  1092. }
  1093. // Local and remote paused, then first resume remote, then local
  1094. cc.Folders[0].Paused = true
  1095. m.ClusterConfig(device1, cc)
  1096. pauseFolder(t, m.cfg, fcfg.ID, true)
  1097. cc.Folders[0].Paused = false
  1098. m.ClusterConfig(device1, cc)
  1099. pauseFolder(t, m.cfg, fcfg.ID, false)
  1100. seq++
  1101. files[0].Sequence = seq
  1102. files[0].Version = files[0].Version.Update(myID.Short())
  1103. localIndexUpdate(m, fcfg.ID, files)
  1104. select {
  1105. case <-time.After(5 * time.Second):
  1106. t.Fatal("timed out before receiving index")
  1107. case <-indexChan:
  1108. }
  1109. // Folder removed on remote
  1110. cc = protocol.ClusterConfig{}
  1111. m.ClusterConfig(device1, cc)
  1112. seq++
  1113. files[0].Sequence = seq
  1114. files[0].Version = files[0].Version.Update(myID.Short())
  1115. localIndexUpdate(m, fcfg.ID, files)
  1116. select {
  1117. case <-time.After(dur):
  1118. case <-indexChan:
  1119. t.Error("Received index despite remote not having the folder")
  1120. }
  1121. }
  1122. func TestRequestIndexSenderClusterConfigBeforeStart(t *testing.T) {
  1123. w, fcfg, wCancel := tmpDefaultWrapper()
  1124. defer wCancel()
  1125. tfs := fcfg.Filesystem()
  1126. dir1 := "foo"
  1127. dir2 := "bar"
  1128. // Initialise db with an entry and then stop everything again
  1129. must(t, tfs.Mkdir(dir1, 0777))
  1130. m := newModel(t, w, myID, "syncthing", "dev", nil)
  1131. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1132. m.ServeBackground()
  1133. m.ScanFolders()
  1134. m.cancel()
  1135. <-m.stopped
  1136. // Add connection (sends incoming cluster config) before starting the new model
  1137. m = &testModel{
  1138. model: NewModel(m.cfg, m.id, m.clientName, m.clientVersion, m.db, m.protectedFiles, m.evLogger).(*model),
  1139. evCancel: m.evCancel,
  1140. stopped: make(chan struct{}),
  1141. }
  1142. defer cleanupModel(m)
  1143. fc := addFakeConn(m, device1)
  1144. done := make(chan struct{})
  1145. defer close(done) // Must be the last thing to be deferred, thus first to run.
  1146. indexChan := make(chan []protocol.FileInfo, 1)
  1147. ccChan := make(chan protocol.ClusterConfig, 1)
  1148. fc.mut.Lock()
  1149. fc.indexFn = func(_ context.Context, folder string, fs []protocol.FileInfo) {
  1150. select {
  1151. case indexChan <- fs:
  1152. case <-done:
  1153. }
  1154. }
  1155. fc.clusterConfigFn = func(cc protocol.ClusterConfig) {
  1156. select {
  1157. case ccChan <- cc:
  1158. case <-done:
  1159. }
  1160. }
  1161. fc.mut.Unlock()
  1162. m.ServeBackground()
  1163. timeout := time.After(5 * time.Second)
  1164. // Check that cluster-config is resent after adding folders when starting model
  1165. select {
  1166. case <-timeout:
  1167. t.Fatal("timed out before receiving cluster-config")
  1168. case <-ccChan:
  1169. }
  1170. // Check that an index is sent for the newly added item
  1171. must(t, tfs.Mkdir(dir2, 0777))
  1172. m.ScanFolders()
  1173. select {
  1174. case <-timeout:
  1175. t.Fatal("timed out before receiving index")
  1176. case <-indexChan:
  1177. }
  1178. }
  1179. func TestRequestReceiveEncryptedLocalNoSend(t *testing.T) {
  1180. w, fcfg, wCancel := tmpDefaultWrapper()
  1181. defer wCancel()
  1182. tfs := fcfg.Filesystem()
  1183. fcfg.Type = config.FolderTypeReceiveEncrypted
  1184. setFolder(t, w, fcfg)
  1185. encToken := protocol.PasswordToken(fcfg.ID, "pw")
  1186. must(t, tfs.Mkdir(config.DefaultMarkerName, 0777))
  1187. must(t, writeEncryptionToken(encToken, fcfg))
  1188. m := setupModel(t, w)
  1189. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1190. files := genFiles(2)
  1191. files[1].LocalFlags = protocol.FlagLocalReceiveOnly
  1192. m.fmut.RLock()
  1193. fset := m.folderFiles[fcfg.ID]
  1194. m.fmut.RUnlock()
  1195. fset.Update(protocol.LocalDeviceID, files)
  1196. indexChan := make(chan []protocol.FileInfo, 1)
  1197. done := make(chan struct{})
  1198. defer close(done)
  1199. fc := &fakeConnection{
  1200. id: device1,
  1201. model: m,
  1202. indexFn: func(_ context.Context, _ string, fs []protocol.FileInfo) {
  1203. select {
  1204. case indexChan <- fs:
  1205. case <-done:
  1206. }
  1207. },
  1208. }
  1209. m.AddConnection(fc, protocol.Hello{})
  1210. m.ClusterConfig(device1, protocol.ClusterConfig{
  1211. Folders: []protocol.Folder{
  1212. {
  1213. ID: "default",
  1214. Devices: []protocol.Device{
  1215. {
  1216. ID: myID,
  1217. EncryptionPasswordToken: encToken,
  1218. },
  1219. {ID: device1},
  1220. },
  1221. },
  1222. },
  1223. })
  1224. select {
  1225. case fs := <-indexChan:
  1226. if len(fs) != 1 {
  1227. t.Error("Expected index with one file, got", fs)
  1228. }
  1229. if got := fs[0].Name; got != files[0].Name {
  1230. t.Errorf("Expected file %v, got %v", got, files[0].Name)
  1231. }
  1232. case <-time.After(5 * time.Second):
  1233. t.Fatal("timed out before receiving index")
  1234. }
  1235. }