requests_test.go 37 KB

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