requests_test.go 35 KB

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