requests_test.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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. "os"
  12. "path/filepath"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "sync"
  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. "github.com/syncthing/syncthing/lib/rand"
  24. )
  25. func TestRequestSimple(t *testing.T) {
  26. // Verify that the model performs a request and creates a file based on
  27. // an incoming index update.
  28. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  29. defer wcfgCancel()
  30. tfs := fcfg.Filesystem(nil)
  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.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  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 nil
  45. }
  46. }
  47. return nil
  48. })
  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. select {
  54. case <-done:
  55. case <-time.After(10 * time.Second):
  56. t.Fatal("timed out")
  57. }
  58. // Verify the contents
  59. if err := equalContents(filepath.Join(tfs.URI(), "testfile"), contents); err != nil {
  60. t.Error("File did not sync correctly:", err)
  61. }
  62. }
  63. func TestSymlinkTraversalRead(t *testing.T) {
  64. // Verify that a symlink can not be traversed for reading.
  65. if runtime.GOOS == "windows" {
  66. t.Skip("no symlink support on CI")
  67. return
  68. }
  69. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  70. defer wcfgCancel()
  71. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  72. // We listen for incoming index updates and trigger when we see one for
  73. // the expected test file.
  74. done := make(chan struct{})
  75. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  76. select {
  77. case <-done:
  78. t.Error("More than one index update sent")
  79. default:
  80. }
  81. for _, f := range fs {
  82. if f.Name == "symlink" {
  83. close(done)
  84. return nil
  85. }
  86. }
  87. return nil
  88. })
  89. // Send an update for the symlink, wait for it to sync and be reported back.
  90. contents := []byte("..")
  91. fc.addFile("symlink", 0644, protocol.FileInfoTypeSymlink, contents)
  92. fc.sendIndexUpdate()
  93. <-done
  94. // Request a file by traversing the symlink
  95. res, err := m.Request(device1, "default", "symlink/requests_test.go", 0, 10, 0, nil, 0, false)
  96. if err == nil || res != nil {
  97. t.Error("Managed to traverse symlink")
  98. }
  99. }
  100. func TestSymlinkTraversalWrite(t *testing.T) {
  101. // Verify that a symlink can not be traversed for writing.
  102. if runtime.GOOS == "windows" {
  103. t.Skip("no symlink support on CI")
  104. return
  105. }
  106. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  107. defer wcfgCancel()
  108. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  109. // We listen for incoming index updates and trigger when we see one for
  110. // the expected names.
  111. done := make(chan struct{}, 1)
  112. badReq := make(chan string, 1)
  113. badIdx := make(chan string, 1)
  114. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  115. for _, f := range fs {
  116. if f.Name == "symlink" {
  117. done <- struct{}{}
  118. return nil
  119. }
  120. if strings.HasPrefix(f.Name, "symlink") {
  121. badIdx <- f.Name
  122. return nil
  123. }
  124. }
  125. return nil
  126. })
  127. fc.RequestCalls(func(ctx context.Context, folder, name string, blockNo int, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  128. if name != "symlink" && strings.HasPrefix(name, "symlink") {
  129. badReq <- name
  130. }
  131. return fc.fileData[name], nil
  132. })
  133. // Send an update for the symlink, wait for it to sync and be reported back.
  134. contents := []byte("..")
  135. fc.addFile("symlink", 0644, protocol.FileInfoTypeSymlink, contents)
  136. fc.sendIndexUpdate()
  137. <-done
  138. // Send an update for things behind the symlink, wait for requests for
  139. // blocks for any of them to come back, or index entries. Hopefully none
  140. // of that should happen.
  141. contents = []byte("testdata testdata\n")
  142. fc.addFile("symlink/testfile", 0644, protocol.FileInfoTypeFile, contents)
  143. fc.addFile("symlink/testdir", 0644, protocol.FileInfoTypeDirectory, contents)
  144. fc.addFile("symlink/testsyml", 0644, protocol.FileInfoTypeSymlink, contents)
  145. fc.sendIndexUpdate()
  146. select {
  147. case name := <-badReq:
  148. t.Fatal("Should not have requested the data for", name)
  149. case name := <-badIdx:
  150. t.Fatal("Should not have sent the index entry for", name)
  151. case <-time.After(3 * time.Second):
  152. // Unfortunately not much else to trigger on here. The puller sleep
  153. // interval is 1s so if we didn't get any requests within two
  154. // iterations we should be fine.
  155. }
  156. }
  157. func TestRequestCreateTmpSymlink(t *testing.T) {
  158. // Test that an update for a temporary file is invalidated
  159. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  160. defer wcfgCancel()
  161. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  162. // We listen for incoming index updates and trigger when we see one for
  163. // the expected test file.
  164. goodIdx := make(chan struct{})
  165. name := fs.TempName("testlink")
  166. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  167. for _, f := range fs {
  168. if f.Name == name {
  169. if f.IsInvalid() {
  170. goodIdx <- struct{}{}
  171. } else {
  172. t.Error("Received index with non-invalid temporary file")
  173. close(goodIdx)
  174. }
  175. return nil
  176. }
  177. }
  178. return nil
  179. })
  180. // Send an update for the test file, wait for it to sync and be reported back.
  181. fc.addFile(name, 0644, protocol.FileInfoTypeSymlink, []byte(".."))
  182. fc.sendIndexUpdate()
  183. select {
  184. case <-goodIdx:
  185. case <-time.After(3 * time.Second):
  186. t.Fatal("Timed out without index entry being sent")
  187. }
  188. }
  189. func TestRequestVersioningSymlinkAttack(t *testing.T) {
  190. if runtime.GOOS == "windows" {
  191. t.Skip("no symlink support on Windows")
  192. }
  193. // Sets up a folder with trashcan versioning and tries to use a
  194. // deleted symlink to escape
  195. w, fcfg, wCancel := tmpDefaultWrapper()
  196. defer wCancel()
  197. defer func() {
  198. os.RemoveAll(fcfg.Filesystem(nil).URI())
  199. os.Remove(w.ConfigPath())
  200. }()
  201. fcfg.Versioning = config.VersioningConfiguration{Type: "trashcan"}
  202. setFolder(t, w, fcfg)
  203. m, fc := setupModelWithConnectionFromWrapper(t, w)
  204. defer cleanupModel(m)
  205. // Create a temporary directory that we will use as target to see if
  206. // we can escape to it
  207. tmpdir, err := os.MkdirTemp("", "syncthing-test")
  208. if err != nil {
  209. t.Fatal(err)
  210. }
  211. defer os.RemoveAll(tmpdir)
  212. // We listen for incoming index updates and trigger when we see one for
  213. // the expected test file.
  214. idx := make(chan int)
  215. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  216. idx <- len(fs)
  217. return nil
  218. })
  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(nil)
  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, fcfg.ID)
  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. writeFile(t, fss, ignExisting, otherContents)
  285. done := make(chan struct{})
  286. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  287. expected := map[string]struct{}{invIgn: {}, ign: {}, ignExisting: {}}
  288. for _, f := range fs {
  289. if _, ok := expected[f.Name]; !ok {
  290. t.Errorf("Unexpected file %v was added to index", f.Name)
  291. }
  292. if !f.IsInvalid() {
  293. t.Errorf("File %v wasn't marked as invalid", f.Name)
  294. }
  295. delete(expected, f.Name)
  296. }
  297. for name := range expected {
  298. t.Errorf("File %v wasn't added to index", name)
  299. }
  300. close(done)
  301. return nil
  302. })
  303. sub := m.evLogger.Subscribe(events.FolderErrors)
  304. defer sub.Unsubscribe()
  305. fc.sendIndexUpdate()
  306. select {
  307. case ev := <-sub.C():
  308. t.Fatalf("Errors while scanning/pulling: %v", ev)
  309. case <-time.After(5 * time.Second):
  310. t.Fatalf("timed out before index was received")
  311. case <-done:
  312. }
  313. done = make(chan struct{})
  314. expected := map[string]struct{}{ign: {}, ignExisting: {}}
  315. var expectedMut sync.Mutex
  316. // The indexes will normally arrive in one update, but it is possible
  317. // that they arrive in separate ones.
  318. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  319. expectedMut.Lock()
  320. for _, f := range fs {
  321. _, ok := expected[f.Name]
  322. if !ok {
  323. t.Errorf("Unexpected file %v was updated in index", f.Name)
  324. continue
  325. }
  326. if f.IsInvalid() {
  327. t.Errorf("File %v is still marked as invalid", f.Name)
  328. }
  329. if f.Name == ign {
  330. // The unignored deleted file should have an
  331. // empty version, to make it not override
  332. // existing global files.
  333. if !f.Deleted {
  334. t.Errorf("File %v was not marked as deleted", f.Name)
  335. }
  336. if len(f.Version.Counters) != 0 {
  337. t.Errorf("File %v has version %v, expected empty", f.Name, f.Version)
  338. }
  339. } else {
  340. // The unignored existing file should have a
  341. // version with only a local counter, to make
  342. // it conflict changed global files.
  343. if f.Deleted {
  344. t.Errorf("File %v is marked as deleted", f.Name)
  345. }
  346. if len(f.Version.Counters) != 1 || f.Version.Counter(myID.Short()) == 0 {
  347. t.Errorf("File %v has version %v, expected one entry for ourselves", f.Name, f.Version)
  348. }
  349. }
  350. delete(expected, f.Name)
  351. }
  352. if len(expected) == 0 {
  353. close(done)
  354. }
  355. expectedMut.Unlock()
  356. return nil
  357. })
  358. // Make sure pulling doesn't interfere, as index updates are racy and
  359. // thus we cannot distinguish between scan and pull results.
  360. fc.RequestCalls(func(ctx context.Context, folder, name string, blockNo int, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  361. return nil, nil
  362. })
  363. if err := m.SetIgnores("default", []string{"*:ignored*"}); err != nil {
  364. panic(err)
  365. }
  366. select {
  367. case <-time.After(5 * time.Second):
  368. expectedMut.Lock()
  369. t.Fatal("timed out before receiving index updates for all existing files, missing", expected)
  370. expectedMut.Unlock()
  371. case <-done:
  372. }
  373. }
  374. func TestIssue4841(t *testing.T) {
  375. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  376. defer wcfgCancel()
  377. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  378. received := make(chan []protocol.FileInfo)
  379. fc.setIndexFn(func(_ context.Context, _ string, fs []protocol.FileInfo) error {
  380. received <- fs
  381. return nil
  382. })
  383. checkReceived := func(fs []protocol.FileInfo) protocol.FileInfo {
  384. t.Helper()
  385. if len(fs) != 1 {
  386. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  387. }
  388. if fs[0].Name != "foo" {
  389. t.Fatalf(`Sent index with file %v, should be "foo"`, fs[0].Name)
  390. }
  391. return fs[0]
  392. }
  393. // Setup file from remote that was ignored locally
  394. folder := m.folderRunners[defaultFolderConfig.ID].(*sendReceiveFolder)
  395. folder.updateLocals([]protocol.FileInfo{{
  396. Name: "foo",
  397. Type: protocol.FileInfoTypeFile,
  398. LocalFlags: protocol.FlagLocalIgnored,
  399. Version: protocol.Vector{}.Update(device1.Short()),
  400. }})
  401. checkReceived(<-received)
  402. // Scan without ignore patterns with "foo" not existing locally
  403. if err := m.ScanFolder("default"); err != nil {
  404. t.Fatal("Failed scanning:", err)
  405. }
  406. select {
  407. case <-time.After(10 * time.Second):
  408. t.Fatal("timed out")
  409. case r := <-received:
  410. f := checkReceived(r)
  411. if !f.Version.Equal(protocol.Vector{}) {
  412. t.Errorf("Got Version == %v, expected empty version", f.Version)
  413. }
  414. }
  415. }
  416. func TestRescanIfHaveInvalidContent(t *testing.T) {
  417. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  418. defer wcfgCancel()
  419. tfs := fcfg.Filesystem(nil)
  420. defer cleanupModelAndRemoveDir(m, tfs.URI())
  421. payload := []byte("hello")
  422. writeFile(t, tfs, "foo", payload)
  423. received := make(chan []protocol.FileInfo)
  424. fc.setIndexFn(func(_ context.Context, _ string, fs []protocol.FileInfo) error {
  425. received <- fs
  426. return nil
  427. })
  428. checkReceived := func(fs []protocol.FileInfo) protocol.FileInfo {
  429. t.Helper()
  430. if len(fs) != 1 {
  431. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  432. }
  433. if fs[0].Name != "foo" {
  434. t.Fatalf(`Sent index with file %v, should be "foo"`, fs[0].Name)
  435. }
  436. return fs[0]
  437. }
  438. // Scan without ignore patterns with "foo" not existing locally
  439. if err := m.ScanFolder("default"); err != nil {
  440. t.Fatal("Failed scanning:", err)
  441. }
  442. f := checkReceived(<-received)
  443. if f.Blocks[0].WeakHash != 103547413 {
  444. t.Fatalf("unexpected weak hash: %d != 103547413", f.Blocks[0].WeakHash)
  445. }
  446. res, 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.Fatal(err)
  449. }
  450. buf := res.Data()
  451. if !bytes.Equal(buf, payload) {
  452. t.Errorf("%s != %s", buf, payload)
  453. }
  454. payload = []byte("bye")
  455. buf = make([]byte, len(payload))
  456. writeFile(t, tfs, "foo", payload)
  457. _, err = m.Request(device1, "default", "foo", 0, int32(len(payload)), 0, f.Blocks[0].Hash, f.Blocks[0].WeakHash, false)
  458. if err == nil {
  459. t.Fatalf("expected failure")
  460. }
  461. select {
  462. case fs := <-received:
  463. f := checkReceived(fs)
  464. if f.Blocks[0].WeakHash != 41943361 {
  465. t.Fatalf("unexpected weak hash: %d != 41943361", f.Blocks[0].WeakHash)
  466. }
  467. case <-time.After(time.Second):
  468. t.Fatalf("timed out")
  469. }
  470. }
  471. func TestParentDeletion(t *testing.T) {
  472. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  473. defer wcfgCancel()
  474. testFs := fcfg.Filesystem(nil)
  475. defer cleanupModelAndRemoveDir(m, testFs.URI())
  476. parent := "foo"
  477. child := filepath.Join(parent, "bar")
  478. received := make(chan []protocol.FileInfo)
  479. fc.addFile(parent, 0777, protocol.FileInfoTypeDirectory, nil)
  480. fc.addFile(child, 0777, protocol.FileInfoTypeDirectory, nil)
  481. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  482. received <- fs
  483. return nil
  484. })
  485. fc.sendIndexUpdate()
  486. // Get back index from initial setup
  487. select {
  488. case fs := <-received:
  489. if len(fs) != 2 {
  490. t.Fatalf("Sent index with %d files, should be 2", len(fs))
  491. }
  492. case <-time.After(time.Second):
  493. t.Fatalf("timed out")
  494. }
  495. // Delete parent dir
  496. must(t, testFs.RemoveAll(parent))
  497. // Scan only the child dir (not the parent)
  498. if err := m.ScanFolderSubdirs("default", []string{child}); err != nil {
  499. t.Fatal("Failed scanning:", err)
  500. }
  501. select {
  502. case fs := <-received:
  503. if len(fs) != 1 {
  504. t.Fatalf("Sent index with %d files, should be 1", len(fs))
  505. }
  506. if fs[0].Name != child {
  507. t.Fatalf(`Sent index with file "%v", should be "%v"`, fs[0].Name, child)
  508. }
  509. case <-time.After(time.Second):
  510. t.Fatalf("timed out")
  511. }
  512. // Recreate the child dir on the remote
  513. fc.updateFile(child, 0777, protocol.FileInfoTypeDirectory, nil)
  514. fc.sendIndexUpdate()
  515. // Wait for the child dir to be recreated and sent to the remote
  516. select {
  517. case fs := <-received:
  518. l.Debugln("sent:", fs)
  519. found := false
  520. for _, f := range fs {
  521. if f.Name == child {
  522. if f.Deleted {
  523. t.Fatalf(`File "%v" is still deleted`, child)
  524. }
  525. found = true
  526. }
  527. }
  528. if !found {
  529. t.Fatalf(`File "%v" is missing in index`, child)
  530. }
  531. case <-time.After(5 * time.Second):
  532. t.Fatalf("timed out")
  533. }
  534. }
  535. // TestRequestSymlinkWindows checks that symlinks aren't marked as deleted on windows
  536. // Issue: https://github.com/syncthing/syncthing/issues/5125
  537. func TestRequestSymlinkWindows(t *testing.T) {
  538. if runtime.GOOS != "windows" {
  539. t.Skip("windows specific test")
  540. }
  541. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  542. defer wcfgCancel()
  543. defer cleanupModelAndRemoveDir(m, fcfg.Filesystem(nil).URI())
  544. received := make(chan []protocol.FileInfo)
  545. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  546. select {
  547. case <-received:
  548. t.Error("More than one index update sent")
  549. default:
  550. }
  551. received <- fs
  552. return nil
  553. })
  554. fc.addFile("link", 0644, protocol.FileInfoTypeSymlink, nil)
  555. fc.sendIndexUpdate()
  556. select {
  557. case fs := <-received:
  558. close(received)
  559. // expected first index
  560. if len(fs) != 1 {
  561. t.Fatalf("Expected just one file in index, got %v", fs)
  562. }
  563. f := fs[0]
  564. if f.Name != "link" {
  565. t.Fatalf(`Got file info with path "%v", expected "link"`, f.Name)
  566. }
  567. if !f.IsInvalid() {
  568. t.Errorf(`File info was not marked as invalid`)
  569. }
  570. case <-time.After(time.Second):
  571. t.Fatalf("timed out before pull was finished")
  572. }
  573. sub := m.evLogger.Subscribe(events.StateChanged | events.LocalIndexUpdated)
  574. defer sub.Unsubscribe()
  575. m.ScanFolder("default")
  576. for {
  577. select {
  578. case ev := <-sub.C():
  579. switch data := ev.Data.(map[string]interface{}); {
  580. case ev.Type == events.LocalIndexUpdated:
  581. t.Fatalf("Local index was updated unexpectedly: %v", data)
  582. case ev.Type == events.StateChanged:
  583. if data["from"] == "scanning" {
  584. return
  585. }
  586. }
  587. case <-time.After(5 * time.Second):
  588. t.Fatalf("Timed out before scan finished")
  589. }
  590. }
  591. }
  592. func equalContents(path string, contents []byte) error {
  593. if bs, err := os.ReadFile(path); err != nil {
  594. return err
  595. } else if !bytes.Equal(bs, contents) {
  596. return errors.New("incorrect data")
  597. }
  598. return nil
  599. }
  600. func TestRequestRemoteRenameChanged(t *testing.T) {
  601. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  602. defer wcfgCancel()
  603. tfs := fcfg.Filesystem(nil)
  604. tmpDir := tfs.URI()
  605. defer cleanupModelAndRemoveDir(m, tfs.URI())
  606. received := make(chan []protocol.FileInfo)
  607. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  608. select {
  609. case <-received:
  610. t.Error("More than one index update sent")
  611. default:
  612. }
  613. received <- fs
  614. return nil
  615. })
  616. // setup
  617. a := "a"
  618. b := "b"
  619. data := map[string][]byte{
  620. a: []byte("aData"),
  621. b: []byte("bData"),
  622. }
  623. for _, n := range [2]string{a, b} {
  624. fc.addFile(n, 0644, protocol.FileInfoTypeFile, data[n])
  625. }
  626. fc.sendIndexUpdate()
  627. select {
  628. case fs := <-received:
  629. close(received)
  630. if len(fs) != 2 {
  631. t.Fatalf("Received index with %v indexes instead of 2", len(fs))
  632. }
  633. case <-time.After(10 * time.Second):
  634. t.Fatal("timed out")
  635. }
  636. for _, n := range [2]string{a, b} {
  637. must(t, equalContents(filepath.Join(tmpDir, n), data[n]))
  638. }
  639. var gotA, gotB, gotConfl bool
  640. done := make(chan struct{})
  641. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  642. select {
  643. case <-done:
  644. t.Error("Received more index updates than expected")
  645. return nil
  646. default:
  647. }
  648. for _, f := range fs {
  649. switch {
  650. case f.Name == a:
  651. if gotA {
  652. t.Error("Got more than one index update for", f.Name)
  653. }
  654. gotA = true
  655. case f.Name == b:
  656. if gotB {
  657. t.Error("Got more than one index update for", f.Name)
  658. }
  659. if f.Version.Counter(fc.id.Short()) == 0 {
  660. // This index entry might be superseeded
  661. // by the final one or sent before it separately.
  662. break
  663. }
  664. gotB = true
  665. case strings.HasPrefix(f.Name, "b.sync-conflict-"):
  666. if gotConfl {
  667. t.Error("Got more than one index update for conflicts of", f.Name)
  668. }
  669. gotConfl = true
  670. default:
  671. t.Error("Got unexpected file in index update", f.Name)
  672. }
  673. }
  674. if gotA && gotB && gotConfl {
  675. close(done)
  676. }
  677. return nil
  678. })
  679. fd, err := tfs.OpenFile(b, fs.OptReadWrite, 0644)
  680. if err != nil {
  681. t.Fatal(err)
  682. }
  683. otherData := []byte("otherData")
  684. if _, err = fd.Write(otherData); err != nil {
  685. t.Fatal(err)
  686. }
  687. fd.Close()
  688. // rename
  689. fc.deleteFile(a)
  690. fc.updateFile(b, 0644, protocol.FileInfoTypeFile, data[a])
  691. // Make sure the remote file for b is newer and thus stays global -> local conflict
  692. fc.mut.Lock()
  693. for i := range fc.files {
  694. if fc.files[i].Name == b {
  695. fc.files[i].ModifiedS += 100
  696. break
  697. }
  698. }
  699. fc.mut.Unlock()
  700. fc.sendIndexUpdate()
  701. select {
  702. case <-done:
  703. case <-time.After(10 * time.Second):
  704. t.Errorf("timed out without receiving all expected index updates")
  705. }
  706. // Check outcome
  707. tfs.Walk(".", func(path string, info fs.FileInfo, err error) error {
  708. switch {
  709. case path == a:
  710. t.Errorf(`File "a" was not removed`)
  711. case path == b:
  712. if err := equalContents(filepath.Join(tmpDir, b), data[a]); err != nil {
  713. t.Error(`File "b" has unexpected content (renamed from a on remote)`)
  714. }
  715. case strings.HasPrefix(path, b+".sync-conflict-"):
  716. if err := equalContents(filepath.Join(tmpDir, path), otherData); err != nil {
  717. t.Error(`Sync conflict of "b" has unexptected content`)
  718. }
  719. case path == "." || strings.HasPrefix(path, ".stfolder"):
  720. default:
  721. t.Error("Found unexpected file", path)
  722. }
  723. return nil
  724. })
  725. }
  726. func TestRequestRemoteRenameConflict(t *testing.T) {
  727. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  728. defer wcfgCancel()
  729. tfs := fcfg.Filesystem(nil)
  730. tmpDir := tfs.URI()
  731. defer cleanupModelAndRemoveDir(m, tmpDir)
  732. recv := make(chan int)
  733. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  734. recv <- len(fs)
  735. return nil
  736. })
  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(nil)
  813. defer cleanupModelAndRemoveDir(m, tfs.URI())
  814. done := make(chan struct{})
  815. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  816. select {
  817. case <-done:
  818. t.Error("More than one index update sent")
  819. default:
  820. }
  821. close(done)
  822. return nil
  823. })
  824. // setup
  825. a := "a"
  826. data := []byte("aData")
  827. fc.addFile(a, 0644, protocol.FileInfoTypeFile, data)
  828. fc.sendIndexUpdate()
  829. select {
  830. case <-done:
  831. done = make(chan struct{})
  832. case <-time.After(10 * time.Second):
  833. t.Fatal("timed out")
  834. }
  835. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  836. select {
  837. case <-done:
  838. t.Error("More than one index update sent")
  839. default:
  840. }
  841. close(done)
  842. return nil
  843. })
  844. fd, err := tfs.OpenFile(a, fs.OptReadWrite, 0644)
  845. if err != nil {
  846. t.Fatal(err)
  847. }
  848. otherData := []byte("otherData")
  849. if _, err = fd.Write(otherData); err != nil {
  850. t.Fatal(err)
  851. }
  852. fd.Close()
  853. // rename
  854. fc.deleteFile(a)
  855. fc.sendIndexUpdate()
  856. select {
  857. case <-done:
  858. case <-time.After(10 * time.Second):
  859. t.Fatal("timed out")
  860. }
  861. // Check outcome
  862. if _, err := tfs.Lstat(a); err != nil {
  863. if fs.IsNotExist(err) {
  864. t.Error(`Modified file "a" was removed`)
  865. } else {
  866. t.Error(`Error stating file "a":`, err)
  867. }
  868. }
  869. }
  870. func TestNeedFolderFiles(t *testing.T) {
  871. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  872. defer wcfgCancel()
  873. tfs := fcfg.Filesystem(nil)
  874. tmpDir := tfs.URI()
  875. defer cleanupModelAndRemoveDir(m, tmpDir)
  876. sub := m.evLogger.Subscribe(events.RemoteIndexUpdated)
  877. defer sub.Unsubscribe()
  878. errPreventSync := errors.New("you aren't getting any of this")
  879. fc.RequestCalls(func(ctx context.Context, folder, name string, blockNo int, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  880. return nil, errPreventSync
  881. })
  882. data := []byte("foo")
  883. num := 20
  884. for i := 0; i < num; i++ {
  885. fc.addFile(strconv.Itoa(i), 0644, protocol.FileInfoTypeFile, data)
  886. }
  887. fc.sendIndexUpdate()
  888. select {
  889. case <-sub.C():
  890. case <-time.After(5 * time.Second):
  891. t.Fatal("Timed out before receiving index")
  892. }
  893. progress, queued, rest, err := m.NeedFolderFiles(fcfg.ID, 1, 100)
  894. must(t, err)
  895. if got := len(progress) + len(queued) + len(rest); got != num {
  896. t.Errorf("Got %v needed items, expected %v", got, num)
  897. }
  898. exp := 10
  899. for page := 1; page < 3; page++ {
  900. progress, queued, rest, err := m.NeedFolderFiles(fcfg.ID, page, exp)
  901. must(t, err)
  902. if got := len(progress) + len(queued) + len(rest); got != exp {
  903. t.Errorf("Got %v needed items on page %v, expected %v", got, page, exp)
  904. }
  905. }
  906. }
  907. // TestIgnoreDeleteUnignore checks that the deletion of an ignored file is not
  908. // propagated upon un-ignoring.
  909. // https://github.com/syncthing/syncthing/issues/6038
  910. func TestIgnoreDeleteUnignore(t *testing.T) {
  911. w, fcfg, wCancel := tmpDefaultWrapper()
  912. defer wCancel()
  913. m := setupModel(t, w)
  914. fss := fcfg.Filesystem(nil)
  915. tmpDir := fss.URI()
  916. defer cleanupModelAndRemoveDir(m, tmpDir)
  917. folderIgnoresAlwaysReload(t, m, fcfg)
  918. m.ScanFolders()
  919. fc := addFakeConn(m, device1, fcfg.ID)
  920. fc.folder = "default"
  921. fc.mut.Lock()
  922. fc.mut.Unlock()
  923. file := "foobar"
  924. contents := []byte("test file contents\n")
  925. basicCheck := func(fs []protocol.FileInfo) {
  926. t.Helper()
  927. if len(fs) != 1 {
  928. t.Fatal("expected a single index entry, got", len(fs))
  929. } else if fs[0].Name != file {
  930. t.Fatalf("expected a index entry for %v, got one for %v", file, fs[0].Name)
  931. }
  932. }
  933. done := make(chan struct{})
  934. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  935. basicCheck(fs)
  936. close(done)
  937. return nil
  938. })
  939. writeFile(t, fss, file, contents)
  940. m.ScanFolders()
  941. select {
  942. case <-time.After(5 * time.Second):
  943. t.Fatalf("timed out before index was received")
  944. case <-done:
  945. }
  946. done = make(chan struct{})
  947. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  948. basicCheck(fs)
  949. f := fs[0]
  950. if !f.IsInvalid() {
  951. t.Errorf("Received non-invalid index update")
  952. }
  953. close(done)
  954. return nil
  955. })
  956. if err := m.SetIgnores("default", []string{"foobar"}); err != nil {
  957. panic(err)
  958. }
  959. select {
  960. case <-time.After(5 * time.Second):
  961. t.Fatal("timed out before receiving index update")
  962. case <-done:
  963. }
  964. done = make(chan struct{})
  965. fc.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  966. basicCheck(fs)
  967. f := fs[0]
  968. if f.IsInvalid() {
  969. t.Errorf("Received invalid index update")
  970. }
  971. if !f.Version.Equal(protocol.Vector{}) && f.Deleted {
  972. t.Error("Received deleted index entry with non-empty version")
  973. }
  974. l.Infoln(f)
  975. close(done)
  976. return nil
  977. })
  978. if err := fss.Remove(file); err != nil {
  979. t.Fatal(err)
  980. }
  981. if err := m.SetIgnores("default", []string{}); err != nil {
  982. panic(err)
  983. }
  984. select {
  985. case <-time.After(5 * time.Second):
  986. t.Fatalf("timed out before index was received")
  987. case <-done:
  988. }
  989. }
  990. // TestRequestLastFileProgress checks that the last pulled file (here only) is registered
  991. // as in progress.
  992. func TestRequestLastFileProgress(t *testing.T) {
  993. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  994. defer wcfgCancel()
  995. tfs := fcfg.Filesystem(nil)
  996. defer cleanupModelAndRemoveDir(m, tfs.URI())
  997. done := make(chan struct{})
  998. fc.RequestCalls(func(ctx context.Context, folder, name string, blockNo int, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  999. defer close(done)
  1000. progress, queued, rest, err := m.NeedFolderFiles(folder, 1, 10)
  1001. must(t, err)
  1002. if len(queued)+len(rest) != 0 {
  1003. t.Error(`There should not be any queued or "rest" items`)
  1004. }
  1005. if len(progress) != 1 {
  1006. t.Error("Expected exactly one item in progress.")
  1007. }
  1008. return fc.fileData[name], nil
  1009. })
  1010. contents := []byte("test file contents\n")
  1011. fc.addFile("testfile", 0644, protocol.FileInfoTypeFile, contents)
  1012. fc.sendIndexUpdate()
  1013. select {
  1014. case <-done:
  1015. case <-time.After(5 * time.Second):
  1016. t.Fatal("Timed out before file was requested")
  1017. }
  1018. }
  1019. func TestRequestIndexSenderPause(t *testing.T) {
  1020. done := make(chan struct{})
  1021. defer close(done)
  1022. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  1023. defer wcfgCancel()
  1024. tfs := fcfg.Filesystem(nil)
  1025. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1026. indexChan := make(chan []protocol.FileInfo)
  1027. fc.setIndexFn(func(ctx context.Context, folder string, fs []protocol.FileInfo) error {
  1028. select {
  1029. case indexChan <- fs:
  1030. case <-done:
  1031. case <-ctx.Done():
  1032. }
  1033. return nil
  1034. })
  1035. var seq int64 = 1
  1036. files := []protocol.FileInfo{{Name: "foo", Size: 10, Version: protocol.Vector{}.Update(myID.Short()), Sequence: seq}}
  1037. // Both devices connected, noone paused
  1038. localIndexUpdate(m, fcfg.ID, files)
  1039. select {
  1040. case <-time.After(5 * time.Second):
  1041. t.Fatal("timed out before receiving index")
  1042. case <-indexChan:
  1043. }
  1044. // Remote paused
  1045. cc := basicClusterConfig(device1, myID, fcfg.ID)
  1046. cc.Folders[0].Paused = true
  1047. m.ClusterConfig(device1, cc)
  1048. seq++
  1049. files[0].Sequence = seq
  1050. files[0].Version = files[0].Version.Update(myID.Short())
  1051. localIndexUpdate(m, fcfg.ID, files)
  1052. // I don't see what to hook into to ensure an index update is not sent.
  1053. dur := 50 * time.Millisecond
  1054. if !testing.Short() {
  1055. dur = 2 * time.Second
  1056. }
  1057. select {
  1058. case <-time.After(dur):
  1059. case <-indexChan:
  1060. t.Error("Received index despite remote being paused")
  1061. }
  1062. // Remote unpaused
  1063. cc.Folders[0].Paused = false
  1064. m.ClusterConfig(device1, cc)
  1065. select {
  1066. case <-time.After(5 * time.Second):
  1067. t.Fatal("timed out before receiving index")
  1068. case <-indexChan:
  1069. }
  1070. // Local paused and resume
  1071. pauseFolder(t, m.cfg, fcfg.ID, true)
  1072. pauseFolder(t, m.cfg, fcfg.ID, false)
  1073. seq++
  1074. files[0].Sequence = seq
  1075. files[0].Version = files[0].Version.Update(myID.Short())
  1076. localIndexUpdate(m, fcfg.ID, files)
  1077. select {
  1078. case <-time.After(5 * time.Second):
  1079. t.Fatal("timed out before receiving index")
  1080. case <-indexChan:
  1081. }
  1082. // Local and remote paused, then first resume remote, then local
  1083. cc.Folders[0].Paused = true
  1084. m.ClusterConfig(device1, cc)
  1085. pauseFolder(t, m.cfg, fcfg.ID, true)
  1086. cc.Folders[0].Paused = false
  1087. m.ClusterConfig(device1, cc)
  1088. pauseFolder(t, m.cfg, fcfg.ID, false)
  1089. seq++
  1090. files[0].Sequence = seq
  1091. files[0].Version = files[0].Version.Update(myID.Short())
  1092. localIndexUpdate(m, fcfg.ID, files)
  1093. select {
  1094. case <-time.After(5 * time.Second):
  1095. t.Fatal("timed out before receiving index")
  1096. case <-indexChan:
  1097. }
  1098. // Folder removed on remote
  1099. cc = protocol.ClusterConfig{}
  1100. m.ClusterConfig(device1, cc)
  1101. seq++
  1102. files[0].Sequence = seq
  1103. files[0].Version = files[0].Version.Update(myID.Short())
  1104. localIndexUpdate(m, fcfg.ID, files)
  1105. select {
  1106. case <-time.After(dur):
  1107. case <-indexChan:
  1108. t.Error("Received index despite remote not having the folder")
  1109. }
  1110. }
  1111. func TestRequestIndexSenderClusterConfigBeforeStart(t *testing.T) {
  1112. w, fcfg, wCancel := tmpDefaultWrapper()
  1113. defer wCancel()
  1114. tfs := fcfg.Filesystem(nil)
  1115. dir1 := "foo"
  1116. dir2 := "bar"
  1117. // Initialise db with an entry and then stop everything again
  1118. must(t, tfs.Mkdir(dir1, 0777))
  1119. m := newModel(t, w, myID, "syncthing", "dev", nil)
  1120. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1121. m.ServeBackground()
  1122. m.ScanFolders()
  1123. m.cancel()
  1124. <-m.stopped
  1125. // Add connection (sends incoming cluster config) before starting the new model
  1126. m = &testModel{
  1127. model: NewModel(m.cfg, m.id, m.clientName, m.clientVersion, m.db, m.protectedFiles, m.evLogger).(*model),
  1128. evCancel: m.evCancel,
  1129. stopped: make(chan struct{}),
  1130. }
  1131. defer cleanupModel(m)
  1132. fc := addFakeConn(m, device1, fcfg.ID)
  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.setIndexFn(func(_ context.Context, folder string, fs []protocol.FileInfo) error {
  1138. select {
  1139. case indexChan <- fs:
  1140. case <-done:
  1141. }
  1142. return nil
  1143. })
  1144. fc.ClusterConfigCalls(func(cc protocol.ClusterConfig) {
  1145. select {
  1146. case ccChan <- cc:
  1147. case <-done:
  1148. }
  1149. })
  1150. m.ServeBackground()
  1151. timeout := time.After(5 * time.Second)
  1152. // Check that cluster-config is resent after adding folders when starting model
  1153. select {
  1154. case <-timeout:
  1155. t.Fatal("timed out before receiving cluster-config")
  1156. case <-ccChan:
  1157. }
  1158. // Check that an index is sent for the newly added item
  1159. must(t, tfs.Mkdir(dir2, 0777))
  1160. m.ScanFolders()
  1161. select {
  1162. case <-timeout:
  1163. t.Fatal("timed out before receiving index")
  1164. case <-indexChan:
  1165. }
  1166. }
  1167. func TestRequestReceiveEncrypted(t *testing.T) {
  1168. if testing.Short() {
  1169. t.Skip("skipping on short testing - scrypt is too slow")
  1170. }
  1171. w, fcfg, wCancel := tmpDefaultWrapper()
  1172. defer wCancel()
  1173. tfs := fcfg.Filesystem(nil)
  1174. fcfg.Type = config.FolderTypeReceiveEncrypted
  1175. setFolder(t, w, fcfg)
  1176. encToken := protocol.PasswordToken(fcfg.ID, "pw")
  1177. must(t, tfs.Mkdir(config.DefaultMarkerName, 0777))
  1178. must(t, writeEncryptionToken(encToken, fcfg))
  1179. m := setupModel(t, w)
  1180. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1181. files := genFiles(2)
  1182. files[1].LocalFlags = protocol.FlagLocalReceiveOnly
  1183. m.fmut.RLock()
  1184. fset := m.folderFiles[fcfg.ID]
  1185. m.fmut.RUnlock()
  1186. fset.Update(protocol.LocalDeviceID, files)
  1187. indexChan := make(chan []protocol.FileInfo, 10)
  1188. done := make(chan struct{})
  1189. defer close(done)
  1190. fc := newFakeConnection(device1, m)
  1191. fc.folder = fcfg.ID
  1192. fc.setIndexFn(func(_ context.Context, _ string, fs []protocol.FileInfo) error {
  1193. select {
  1194. case indexChan <- fs:
  1195. case <-done:
  1196. }
  1197. return nil
  1198. })
  1199. m.AddConnection(fc, protocol.Hello{})
  1200. m.ClusterConfig(device1, protocol.ClusterConfig{
  1201. Folders: []protocol.Folder{
  1202. {
  1203. ID: "default",
  1204. Devices: []protocol.Device{
  1205. {
  1206. ID: myID,
  1207. EncryptionPasswordToken: encToken,
  1208. },
  1209. {ID: device1},
  1210. },
  1211. },
  1212. },
  1213. })
  1214. select {
  1215. case fs := <-indexChan:
  1216. if len(fs) != 1 {
  1217. t.Error("Expected index with one file, got", fs)
  1218. }
  1219. if got := fs[0].Name; got != files[0].Name {
  1220. t.Errorf("Expected file %v, got %v", got, files[0].Name)
  1221. }
  1222. case <-time.After(5 * time.Second):
  1223. t.Fatal("timed out before receiving index")
  1224. }
  1225. // Detects deletion, as we never really created the file on disk
  1226. // Shouldn't send anything because receive-encrypted
  1227. must(t, m.ScanFolder(fcfg.ID))
  1228. // One real file to be sent
  1229. name := "foo"
  1230. data := make([]byte, 2000)
  1231. rand.Read(data)
  1232. fc.addFile(name, 0664, protocol.FileInfoTypeFile, data)
  1233. fc.sendIndexUpdate()
  1234. select {
  1235. case fs := <-indexChan:
  1236. if len(fs) != 1 {
  1237. t.Error("Expected index with one file, got", fs)
  1238. }
  1239. if got := fs[0].Name; got != name {
  1240. t.Errorf("Expected file %v, got %v", got, files[0].Name)
  1241. }
  1242. case <-time.After(5 * time.Second):
  1243. t.Fatal("timed out before receiving index")
  1244. }
  1245. // Simulate request from device that is untrusted too, i.e. with non-empty, but garbage hash
  1246. _, err := m.Request(device1, fcfg.ID, name, 0, 1064, 0, []byte("garbage"), 0, false)
  1247. must(t, err)
  1248. changed, err := m.LocalChangedFolderFiles(fcfg.ID, 1, 10)
  1249. must(t, err)
  1250. if l := len(changed); l != 1 {
  1251. t.Errorf("Expected one locally changed file, got %v", l)
  1252. } else if changed[0].Name != files[0].Name {
  1253. t.Errorf("Expected %v, got %v", files[0].Name, changed[0].Name)
  1254. }
  1255. }
  1256. func TestRequestGlobalInvalidToValid(t *testing.T) {
  1257. done := make(chan struct{})
  1258. defer close(done)
  1259. m, fc, fcfg, wcfgCancel := setupModelWithConnection(t)
  1260. defer wcfgCancel()
  1261. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{DeviceID: device2})
  1262. waiter, err := m.cfg.Modify(func(cfg *config.Configuration) {
  1263. cfg.SetDevice(newDeviceConfiguration(cfg.Defaults.Device, device2, "device2"))
  1264. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{DeviceID: device2})
  1265. cfg.SetFolder(fcfg)
  1266. })
  1267. must(t, err)
  1268. waiter.Wait()
  1269. addFakeConn(m, device2, fcfg.ID)
  1270. tfs := fcfg.Filesystem(nil)
  1271. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1272. indexChan := make(chan []protocol.FileInfo, 1)
  1273. fc.setIndexFn(func(ctx context.Context, folder string, fs []protocol.FileInfo) error {
  1274. select {
  1275. case indexChan <- fs:
  1276. case <-done:
  1277. case <-ctx.Done():
  1278. }
  1279. return nil
  1280. })
  1281. name := "foo"
  1282. // Setup device with valid file, do not send index yet
  1283. contents := []byte("test file contents\n")
  1284. fc.addFile(name, 0644, protocol.FileInfoTypeFile, contents)
  1285. // Third device ignoring the same file
  1286. fc.mut.Lock()
  1287. file := fc.files[0]
  1288. fc.mut.Unlock()
  1289. file.SetIgnored()
  1290. m.IndexUpdate(device2, fcfg.ID, []protocol.FileInfo{prepareFileInfoForIndex(file)})
  1291. // Wait for the ignored file to be received and possible pulled
  1292. timeout := time.After(10 * time.Second)
  1293. globalUpdated := false
  1294. for {
  1295. select {
  1296. case <-timeout:
  1297. t.Fatalf("timed out (globalUpdated == %v)", globalUpdated)
  1298. default:
  1299. time.Sleep(10 * time.Millisecond)
  1300. }
  1301. if !globalUpdated {
  1302. _, ok, err := m.CurrentGlobalFile(fcfg.ID, name)
  1303. if err != nil {
  1304. t.Fatal(err)
  1305. }
  1306. if !ok {
  1307. continue
  1308. }
  1309. globalUpdated = true
  1310. }
  1311. snap, err := m.DBSnapshot(fcfg.ID)
  1312. if err != nil {
  1313. t.Fatal(err)
  1314. }
  1315. need := snap.NeedSize(protocol.LocalDeviceID)
  1316. snap.Release()
  1317. if need.Files == 0 {
  1318. break
  1319. }
  1320. }
  1321. // Send the valid file
  1322. fc.sendIndexUpdate()
  1323. gotInvalid := false
  1324. for {
  1325. select {
  1326. case <-timeout:
  1327. t.Fatal("timed out before receiving index")
  1328. case fs := <-indexChan:
  1329. if len(fs) != 1 {
  1330. t.Fatalf("Expected one file in index, got %v", len(fs))
  1331. }
  1332. if !fs[0].IsInvalid() {
  1333. return
  1334. }
  1335. if gotInvalid {
  1336. t.Fatal("Received two invalid index updates")
  1337. }
  1338. t.Log("got index with invalid file")
  1339. gotInvalid = true
  1340. }
  1341. }
  1342. }