requests_test.go 39 KB

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