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