requests_test.go 35 KB

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