requests_test.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  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. tfs := fcfg.Filesystem()
  1268. defer cleanupModelAndRemoveDir(m, tfs.URI())
  1269. indexChan := make(chan []protocol.FileInfo, 1)
  1270. fc.setIndexFn(func(ctx context.Context, folder string, fs []protocol.FileInfo) error {
  1271. select {
  1272. case indexChan <- fs:
  1273. case <-done:
  1274. case <-ctx.Done():
  1275. }
  1276. return nil
  1277. })
  1278. name := "foo"
  1279. // Setup device with valid file, do not send index yet
  1280. contents := []byte("test file contents\n")
  1281. fc.addFile(name, 0644, protocol.FileInfoTypeFile, contents)
  1282. // Third device ignoring the same file
  1283. fc.mut.Lock()
  1284. file := fc.files[0]
  1285. fc.mut.Unlock()
  1286. file.SetIgnored()
  1287. m.IndexUpdate(device2, fcfg.ID, []protocol.FileInfo{prepareFileInfoForIndex(file)})
  1288. // Wait for the ignored file to be received and possible pulled
  1289. timeout := time.After(10 * time.Second)
  1290. globalUpdated := false
  1291. for {
  1292. select {
  1293. case <-timeout:
  1294. t.Fatalf("timed out (globalUpdated == %v)", globalUpdated)
  1295. default:
  1296. time.Sleep(10 * time.Millisecond)
  1297. }
  1298. if !globalUpdated {
  1299. _, ok, err := m.CurrentGlobalFile(fcfg.ID, name)
  1300. if err != nil {
  1301. t.Fatal(err)
  1302. }
  1303. if !ok {
  1304. continue
  1305. }
  1306. globalUpdated = true
  1307. }
  1308. snap, err := m.DBSnapshot(fcfg.ID)
  1309. if err != nil {
  1310. t.Fatal(err)
  1311. }
  1312. need := snap.NeedSize(protocol.LocalDeviceID)
  1313. snap.Release()
  1314. if need.Files == 0 {
  1315. break
  1316. }
  1317. }
  1318. // Send the valid file
  1319. fc.sendIndexUpdate()
  1320. gotInvalid := false
  1321. for {
  1322. select {
  1323. case <-timeout:
  1324. t.Fatal("timed out before receiving index")
  1325. case fs := <-indexChan:
  1326. if len(fs) != 1 {
  1327. t.Fatalf("Expected one file in index, got %v", len(fs))
  1328. }
  1329. if !fs[0].IsInvalid() {
  1330. return
  1331. }
  1332. if gotInvalid {
  1333. t.Fatal("Received two invalid index updates")
  1334. }
  1335. t.Log("got index with invalid file")
  1336. gotInvalid = true
  1337. }
  1338. }
  1339. }