1
0

requests_test.go 37 KB

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