folder_sendrecv_test.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. // Copyright (C) 2014 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. "fmt"
  12. "io"
  13. "os"
  14. "path/filepath"
  15. "runtime/pprof"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "testing"
  20. "time"
  21. "github.com/syncthing/syncthing/internal/itererr"
  22. "github.com/syncthing/syncthing/lib/build"
  23. "github.com/syncthing/syncthing/lib/config"
  24. "github.com/syncthing/syncthing/lib/events"
  25. "github.com/syncthing/syncthing/lib/fs"
  26. "github.com/syncthing/syncthing/lib/ignore"
  27. "github.com/syncthing/syncthing/lib/protocol"
  28. "github.com/syncthing/syncthing/lib/scanner"
  29. )
  30. var blocks = []protocol.BlockInfo{
  31. {Hash: []uint8{0xfa, 0x43, 0x23, 0x9b, 0xce, 0xe7, 0xb9, 0x7c, 0xa6, 0x2f, 0x0, 0x7c, 0xc6, 0x84, 0x87, 0x56, 0xa, 0x39, 0xe1, 0x9f, 0x74, 0xf3, 0xdd, 0xe7, 0x48, 0x6d, 0xb3, 0xf9, 0x8d, 0xf8, 0xe4, 0x71}}, // Zero'ed out block
  32. {Offset: 0, Size: 0x20000, Hash: []uint8{0x7e, 0xad, 0xbc, 0x36, 0xae, 0xbb, 0xcf, 0x74, 0x43, 0xe2, 0x7a, 0x5a, 0x4b, 0xb8, 0x5b, 0xce, 0xe6, 0x9e, 0x1e, 0x10, 0xf9, 0x8a, 0xbc, 0x77, 0x95, 0x2, 0x29, 0x60, 0x9e, 0x96, 0xae, 0x6c}},
  33. {Offset: 131072, Size: 0x20000, Hash: []uint8{0x3c, 0xc4, 0x20, 0xf4, 0xb, 0x2e, 0xcb, 0xb9, 0x5d, 0xce, 0x34, 0xa8, 0xc3, 0x92, 0xea, 0xf3, 0xda, 0x88, 0x33, 0xee, 0x7a, 0xb6, 0xe, 0xf1, 0x82, 0x5e, 0xb0, 0xa9, 0x26, 0xa9, 0xc0, 0xef}},
  34. {Offset: 262144, Size: 0x20000, Hash: []uint8{0x76, 0xa8, 0xc, 0x69, 0xd7, 0x5c, 0x52, 0xfd, 0xdf, 0x55, 0xef, 0x44, 0xc1, 0xd6, 0x25, 0x48, 0x4d, 0x98, 0x48, 0x4d, 0xaa, 0x50, 0xf6, 0x6b, 0x32, 0x47, 0x55, 0x81, 0x6b, 0xed, 0xee, 0xfb}},
  35. {Offset: 393216, Size: 0x20000, Hash: []uint8{0x44, 0x1e, 0xa4, 0xf2, 0x8d, 0x1f, 0xc3, 0x1b, 0x9d, 0xa5, 0x18, 0x5e, 0x59, 0x1b, 0xd8, 0x5c, 0xba, 0x7d, 0xb9, 0x8d, 0x70, 0x11, 0x5c, 0xea, 0xa1, 0x57, 0x4d, 0xcb, 0x3c, 0x5b, 0xf8, 0x6c}},
  36. {Offset: 524288, Size: 0x20000, Hash: []uint8{0x8, 0x40, 0xd0, 0x5e, 0x80, 0x0, 0x0, 0x7c, 0x8b, 0xb3, 0x8b, 0xf7, 0x7b, 0x23, 0x26, 0x28, 0xab, 0xda, 0xcf, 0x86, 0x8f, 0xc2, 0x8a, 0x39, 0xc6, 0xe6, 0x69, 0x59, 0x97, 0xb6, 0x1a, 0x43}},
  37. {Offset: 655360, Size: 0x20000, Hash: []uint8{0x38, 0x8e, 0x44, 0xcb, 0x30, 0xd8, 0x90, 0xf, 0xce, 0x7, 0x4b, 0x58, 0x86, 0xde, 0xce, 0x59, 0xa2, 0x46, 0xd2, 0xf9, 0xba, 0xaf, 0x35, 0x87, 0x38, 0xdf, 0xd2, 0xd, 0xf9, 0x45, 0xed, 0x91}},
  38. {Offset: 786432, Size: 0x20000, Hash: []uint8{0x32, 0x28, 0xcd, 0xf, 0x37, 0x21, 0xe5, 0xd4, 0x1e, 0x58, 0x87, 0x73, 0x8e, 0x36, 0xdf, 0xb2, 0x70, 0x78, 0x56, 0xc3, 0x42, 0xff, 0xf7, 0x8f, 0x37, 0x95, 0x0, 0x26, 0xa, 0xac, 0x54, 0x72}},
  39. {Offset: 917504, Size: 0x20000, Hash: []uint8{0x96, 0x6b, 0x15, 0x6b, 0xc4, 0xf, 0x19, 0x18, 0xca, 0xbb, 0x5f, 0xd6, 0xbb, 0xa2, 0xc6, 0x2a, 0xac, 0xbb, 0x8a, 0xb9, 0xce, 0xec, 0x4c, 0xdb, 0x78, 0xec, 0x57, 0x5d, 0x33, 0xf9, 0x8e, 0xaf}},
  40. }
  41. func prepareTmpFile(to fs.Filesystem) (string, error) {
  42. tmpName := fs.TempName("file")
  43. in, err := os.Open("testdata/tmpfile")
  44. if err != nil {
  45. return "", err
  46. }
  47. defer in.Close()
  48. out, err := to.Create(tmpName)
  49. if err != nil {
  50. return "", err
  51. }
  52. defer out.Close()
  53. if _, err = io.Copy(out, in); err != nil {
  54. return "", err
  55. }
  56. future := time.Now().Add(time.Hour)
  57. if err := to.Chtimes(tmpName, future, future); err != nil {
  58. return "", err
  59. }
  60. return tmpName, nil
  61. }
  62. var diffTestData = []struct {
  63. a string
  64. b string
  65. s int
  66. d []protocol.BlockInfo
  67. }{
  68. {"contents", "contents", 1024, []protocol.BlockInfo{}},
  69. {"", "", 1024, []protocol.BlockInfo{}},
  70. {"contents", "contents", 3, []protocol.BlockInfo{}},
  71. {"contents", "cantents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}}},
  72. {"contents", "contants", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}}},
  73. {"contents", "cantants", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}}},
  74. {"contents", "", 3, []protocol.BlockInfo{{Offset: 0, Size: 0}}},
  75. {"", "contents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  76. {"con", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  77. {"contents", "con", 3, nil},
  78. {"contents", "cont", 3, []protocol.BlockInfo{{Offset: 3, Size: 1}}},
  79. {"cont", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  80. }
  81. func setupFile(filename string, blockNumbers []int) protocol.FileInfo {
  82. // Create existing file
  83. existingBlocks := make([]protocol.BlockInfo, len(blockNumbers))
  84. for i := range blockNumbers {
  85. existingBlocks[i] = blocks[blockNumbers[i]]
  86. }
  87. return protocol.FileInfo{
  88. Name: filename,
  89. Blocks: existingBlocks,
  90. }
  91. }
  92. func createEmptyFileInfo(t *testing.T, name string, fs fs.Filesystem) protocol.FileInfo {
  93. t.Helper()
  94. writeFile(t, fs, name, nil)
  95. fi, err := fs.Stat(name)
  96. must(t, err)
  97. file, err := scanner.CreateFileInfo(fi, name, fs, false, false, config.XattrFilter{})
  98. must(t, err)
  99. return file
  100. }
  101. // Sets up a folder and model, but makes sure the services aren't actually running.
  102. func setupSendReceiveFolder(t testing.TB, files ...protocol.FileInfo) (*testModel, *sendReceiveFolder) {
  103. w, fcfg := newDefaultCfgWrapper(t)
  104. // Initialise model and stop immediately.
  105. model := setupModel(t, w)
  106. model.cancel()
  107. <-model.stopped
  108. r, _ := model.folderRunners.Get(fcfg.ID)
  109. f := r.(*sendReceiveFolder)
  110. f.tempPullErrors = make(map[string]string)
  111. // Update index
  112. if files != nil {
  113. f.updateLocalsFromScanning(files)
  114. }
  115. return model, f
  116. }
  117. // Layout of the files: (indexes from the above array)
  118. // 12345678 - Required file
  119. // 02005008 - Existing file (currently in the index)
  120. // 02340070 - Temp file on the disk
  121. func TestHandleFile(t *testing.T) {
  122. // After the diff between required and existing we should:
  123. // Copy: 2, 5, 8
  124. // Pull: 1, 3, 4, 6, 7
  125. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  126. existingFile := setupFile("filex", existingBlocks)
  127. requiredFile := existingFile
  128. requiredFile.Blocks = blocks[1:]
  129. _, f := setupSendReceiveFolder(t, existingFile)
  130. copyChan := make(chan copyBlocksState, 1)
  131. f.handleFile(t.Context(), requiredFile, copyChan)
  132. // Receive the results
  133. toCopy := <-copyChan
  134. if len(toCopy.blocks) != 8 {
  135. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  136. }
  137. for _, block := range blocks[1:] {
  138. found := false
  139. for _, toCopyBlock := range toCopy.blocks {
  140. if bytes.Equal(toCopyBlock.Hash, block.Hash) {
  141. found = true
  142. break
  143. }
  144. }
  145. if !found {
  146. t.Errorf("Did not find block %s", block.String())
  147. }
  148. }
  149. }
  150. func TestHandleFileWithTemp(t *testing.T) {
  151. // After diff between required and existing we should:
  152. // Copy: 2, 5, 8
  153. // Pull: 1, 3, 4, 6, 7
  154. // After dropping out blocks already on the temp file we should:
  155. // Copy: 5, 8
  156. // Pull: 1, 6
  157. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  158. existingFile := setupFile("file", existingBlocks)
  159. requiredFile := existingFile
  160. requiredFile.Blocks = blocks[1:]
  161. _, f := setupSendReceiveFolder(t, existingFile)
  162. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  163. t.Fatal(err)
  164. }
  165. copyChan := make(chan copyBlocksState, 1)
  166. f.handleFile(t.Context(), requiredFile, copyChan)
  167. // Receive the results
  168. toCopy := <-copyChan
  169. if len(toCopy.blocks) != 4 {
  170. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  171. }
  172. for _, idx := range []int{1, 5, 6, 8} {
  173. found := false
  174. block := blocks[idx]
  175. for _, toCopyBlock := range toCopy.blocks {
  176. if bytes.Equal(toCopyBlock.Hash, block.Hash) {
  177. found = true
  178. break
  179. }
  180. }
  181. if !found {
  182. t.Errorf("Did not find block %s", block.String())
  183. }
  184. }
  185. }
  186. func TestCopierFinder(t *testing.T) {
  187. // After diff between required and existing we should:
  188. // Copy: 1, 2, 3, 4, 6, 7, 8
  189. // Since there is no existing file, nor a temp file
  190. // After dropping out blocks found locally:
  191. // Pull: 1, 5, 6, 8
  192. tempFile := fs.TempName("file2")
  193. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  194. existingFile := setupFile(fs.TempName("file"), existingBlocks)
  195. existingFile.Size = 1
  196. requiredFile := existingFile
  197. requiredFile.Blocks = blocks[1:]
  198. requiredFile.Name = "file2"
  199. _, f := setupSendReceiveFolder(t, existingFile)
  200. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  201. t.Fatal(err)
  202. }
  203. copyChan := make(chan copyBlocksState)
  204. pullChan := make(chan pullBlockState, 4)
  205. finisherChan := make(chan *sharedPullerState, 1)
  206. // Run a single fetcher routine
  207. go f.copierRoutine(t.Context(), copyChan, pullChan, finisherChan)
  208. defer close(copyChan)
  209. f.handleFile(t.Context(), requiredFile, copyChan)
  210. timeout := time.After(10 * time.Second)
  211. pulls := make([]pullBlockState, 4)
  212. for i := 0; i < 4; i++ {
  213. select {
  214. case pulls[i] = <-pullChan:
  215. case <-timeout:
  216. t.Fatalf("Timed out before receiving all 4 states on pullChan (already got %v)", i)
  217. }
  218. }
  219. var finish *sharedPullerState
  220. select {
  221. case finish = <-finisherChan:
  222. case <-timeout:
  223. t.Fatal("Timed out before receiving 4 states on pullChan")
  224. }
  225. defer cleanupSharedPullerState(finish)
  226. select {
  227. case v := <-pullChan:
  228. t.Logf("%+v\n", v)
  229. t.Fatal("Pull channel had data to be read")
  230. case <-finisherChan:
  231. t.Fatal("Finisher channel has data to be read")
  232. default:
  233. }
  234. // Verify that the right blocks went into the pull list.
  235. // They are pulled in random order.
  236. for _, idx := range []int{1, 5, 6, 8} {
  237. found := false
  238. block := blocks[idx]
  239. for _, pulledBlock := range pulls {
  240. if bytes.Equal(pulledBlock.block.Hash, block.Hash) {
  241. found = true
  242. break
  243. }
  244. }
  245. if !found {
  246. t.Errorf("Did not find block %s", block.String())
  247. }
  248. if !bytes.Equal(finish.file.Blocks[idx-1].Hash, blocks[idx].Hash) {
  249. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  250. }
  251. }
  252. // Verify that the fetched blocks have actually been written to the temp file
  253. blks, err := scanner.HashFile(t.Context(), f.ID, f.Filesystem(), tempFile, protocol.MinBlockSize, nil)
  254. if err != nil {
  255. t.Log(err)
  256. }
  257. for _, eq := range []int{2, 3, 4, 7} {
  258. if !bytes.Equal(blks[eq-1].Hash, blocks[eq].Hash) {
  259. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  260. }
  261. }
  262. }
  263. // Test that updating a file removes its old blocks from the blockmap
  264. func TestCopierCleanup(t *testing.T) {
  265. // Create a file
  266. file := setupFile("test", []int{0})
  267. file.Size = 1
  268. m, f := setupSendReceiveFolder(t, file)
  269. file.Blocks = []protocol.BlockInfo{blocks[1]}
  270. file.Version = file.Version.Update(myID.Short())
  271. // Update index (removing old blocks)
  272. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  273. if vals, err := itererr.Collect(m.sdb.AllLocalBlocksWithHash(f.ID, blocks[0].Hash)); err != nil || len(vals) > 0 {
  274. t.Error("Unexpected block found")
  275. }
  276. if vals, err := itererr.Collect(m.sdb.AllLocalBlocksWithHash(f.ID, blocks[1].Hash)); err != nil || len(vals) == 0 {
  277. t.Error("Expected block not found")
  278. }
  279. file.Blocks = []protocol.BlockInfo{blocks[0]}
  280. file.Version = file.Version.Update(myID.Short())
  281. // Update index (removing old blocks)
  282. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  283. if vals, err := itererr.Collect(m.sdb.AllLocalBlocksWithHash(f.ID, blocks[0].Hash)); err != nil || len(vals) == 0 {
  284. t.Error("Unexpected block found")
  285. }
  286. if vals, err := itererr.Collect(m.sdb.AllLocalBlocksWithHash(f.ID, blocks[1].Hash)); err != nil || len(vals) > 0 {
  287. t.Error("Expected block not found")
  288. }
  289. }
  290. func TestDeregisterOnFailInCopy(t *testing.T) {
  291. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  292. m, f := setupSendReceiveFolder(t)
  293. // Set up our evet subscription early
  294. s := m.evLogger.Subscribe(events.ItemFinished)
  295. // queue.Done should be called by the finisher routine
  296. f.queue.Push("filex", 0, time.Time{})
  297. f.queue.Pop()
  298. if f.queue.lenProgress() != 1 {
  299. t.Fatal("Expected file in progress")
  300. }
  301. pullChan := make(chan pullBlockState)
  302. finisherBufferChan := make(chan *sharedPullerState, 1)
  303. finisherChan := make(chan *sharedPullerState)
  304. dbUpdateChan := make(chan dbUpdateJob, 1)
  305. copyChan, copyWg := startCopier(t.Context(), f, pullChan, finisherBufferChan)
  306. go f.finisherRoutine(t.Context(), finisherChan, dbUpdateChan, make(chan string))
  307. defer func() {
  308. close(copyChan)
  309. copyWg.Wait()
  310. close(pullChan)
  311. close(finisherBufferChan)
  312. close(finisherChan)
  313. }()
  314. f.handleFile(t.Context(), file, copyChan)
  315. // Receive a block at puller, to indicate that at least a single copier
  316. // loop has been performed.
  317. var toPull pullBlockState
  318. select {
  319. case toPull = <-pullChan:
  320. case <-time.After(10 * time.Second):
  321. t.Fatal("timed out")
  322. }
  323. // Unblock copier
  324. go func() {
  325. for range pullChan {
  326. }
  327. }()
  328. // Close the file, causing errors on further access
  329. toPull.sharedPullerState.fail(os.ErrNotExist)
  330. select {
  331. case state := <-finisherBufferChan:
  332. // At this point the file should still be registered with both the job
  333. // queue, and the progress emitter. Verify this.
  334. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  335. t.Fatal("Could not find file")
  336. }
  337. // Pass the file down the real finisher, and give it time to consume
  338. finisherChan <- state
  339. t0 := time.Now()
  340. if ev, err := s.Poll(time.Minute); err != nil {
  341. t.Fatal("Got error waiting for ItemFinished event:", err)
  342. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  343. t.Fatal("Got ItemFinished event for wrong file:", n)
  344. }
  345. t.Log("event took", time.Since(t0))
  346. state.mut.Lock()
  347. stateWriter := state.writer
  348. state.mut.Unlock()
  349. if stateWriter != nil {
  350. t.Fatal("File not closed?")
  351. }
  352. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  353. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  354. }
  355. // Doing it again should have no effect
  356. finisherChan <- state
  357. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  358. t.Fatal("Expected timeout, not another event", err)
  359. }
  360. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  361. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  362. }
  363. case <-time.After(5 * time.Second):
  364. t.Fatal("Didn't get anything to the finisher")
  365. }
  366. }
  367. func TestDeregisterOnFailInPull(t *testing.T) {
  368. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  369. m, f := setupSendReceiveFolder(t)
  370. // Set up our evet subscription early
  371. s := m.evLogger.Subscribe(events.ItemFinished)
  372. // queue.Done should be called by the finisher routine
  373. f.queue.Push("filex", 0, time.Time{})
  374. f.queue.Pop()
  375. if f.queue.lenProgress() != 1 {
  376. t.Fatal("Expected file in progress")
  377. }
  378. pullChan := make(chan pullBlockState)
  379. finisherBufferChan := make(chan *sharedPullerState)
  380. finisherChan := make(chan *sharedPullerState)
  381. dbUpdateChan := make(chan dbUpdateJob, 1)
  382. copyChan, copyWg := startCopier(t.Context(), f, pullChan, finisherBufferChan)
  383. var pullWg sync.WaitGroup
  384. pullWg.Go(func() {
  385. f.pullerRoutine(t.Context(), pullChan, finisherBufferChan)
  386. })
  387. go f.finisherRoutine(t.Context(), finisherChan, dbUpdateChan, make(chan string))
  388. defer func() {
  389. // Unblock copier and puller
  390. go func() {
  391. for range finisherBufferChan {
  392. }
  393. }()
  394. close(copyChan)
  395. copyWg.Wait()
  396. close(pullChan)
  397. pullWg.Wait()
  398. close(finisherBufferChan)
  399. close(finisherChan)
  400. }()
  401. f.handleFile(t.Context(), file, copyChan)
  402. // Receive at finisher, we should error out as puller has nowhere to pull
  403. // from.
  404. timeout = time.Second
  405. // Both the puller and copier may send to the finisherBufferChan.
  406. var state *sharedPullerState
  407. after := time.After(5 * time.Second)
  408. for {
  409. select {
  410. case state = <-finisherBufferChan:
  411. case <-after:
  412. t.Fatal("Didn't get failed state to the finisher")
  413. }
  414. if state.failed() != nil {
  415. break
  416. }
  417. }
  418. // At this point the file should still be registered with both the job
  419. // queue, and the progress emitter. Verify this.
  420. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  421. t.Fatal("Could not find file")
  422. }
  423. // Pass the file down the real finisher, and give it time to consume
  424. finisherChan <- state
  425. t0 := time.Now()
  426. if ev, err := s.Poll(time.Minute); err != nil {
  427. t.Fatal("Got error waiting for ItemFinished event:", err)
  428. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  429. t.Fatal("Got ItemFinished event for wrong file:", n)
  430. }
  431. t.Log("event took", time.Since(t0))
  432. state.mut.Lock()
  433. stateWriter := state.writer
  434. state.mut.Unlock()
  435. if stateWriter != nil {
  436. t.Fatal("File not closed?")
  437. }
  438. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  439. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  440. }
  441. // Doing it again should have no effect
  442. finisherChan <- state
  443. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  444. t.Fatal("Expected timeout, not another event", err)
  445. }
  446. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  447. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  448. }
  449. }
  450. func TestIssue3164(t *testing.T) {
  451. _, f := setupSendReceiveFolder(t)
  452. ffs := f.Filesystem()
  453. ignDir := filepath.Join("issue3164", "oktodelete")
  454. subDir := filepath.Join(ignDir, "foobar")
  455. must(t, ffs.MkdirAll(subDir, 0o777))
  456. must(t, fs.WriteFile(ffs, filepath.Join(subDir, "file"), []byte("Hello"), 0o644))
  457. must(t, fs.WriteFile(ffs, filepath.Join(ignDir, "file"), []byte("Hello"), 0o644))
  458. file := protocol.FileInfo{
  459. Name: "issue3164",
  460. }
  461. must(t, f.scanSubdirs(t.Context(), nil))
  462. matcher := ignore.New(ffs)
  463. must(t, matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""))
  464. f.ignores = matcher
  465. dbUpdateChan := make(chan dbUpdateJob, 1)
  466. f.deleteDir(file, dbUpdateChan, make(chan string))
  467. if _, err := ffs.Stat("issue3164"); !fs.IsNotExist(err) {
  468. t.Fatal(err)
  469. }
  470. }
  471. func TestDiff(t *testing.T) {
  472. for i, test := range diffTestData {
  473. a, _ := scanner.Blocks(t.Context(), bytes.NewBufferString(test.a), test.s, -1, nil)
  474. b, _ := scanner.Blocks(t.Context(), bytes.NewBufferString(test.b), test.s, -1, nil)
  475. _, d := blockDiff(a, b)
  476. if len(d) != len(test.d) {
  477. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  478. } else {
  479. for j := range test.d {
  480. if d[j].Offset != test.d[j].Offset {
  481. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  482. }
  483. if d[j].Size != test.d[j].Size {
  484. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  485. }
  486. }
  487. }
  488. }
  489. }
  490. func BenchmarkDiff(b *testing.B) {
  491. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  492. for _, test := range diffTestData {
  493. aBlocks, _ := scanner.Blocks(b.Context(), bytes.NewBufferString(test.a), test.s, -1, nil)
  494. bBlocks, _ := scanner.Blocks(b.Context(), bytes.NewBufferString(test.b), test.s, -1, nil)
  495. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{aBlocks, bBlocks})
  496. }
  497. b.ReportAllocs()
  498. b.ResetTimer()
  499. for i := 0; i < b.N; i++ {
  500. for _, tc := range testCases {
  501. blockDiff(tc.a, tc.b)
  502. }
  503. }
  504. }
  505. func TestDiffEmpty(t *testing.T) {
  506. emptyCases := []struct {
  507. a []protocol.BlockInfo
  508. b []protocol.BlockInfo
  509. need int
  510. have int
  511. }{
  512. {nil, nil, 0, 0},
  513. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  514. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  515. }
  516. for _, emptyCase := range emptyCases {
  517. h, n := blockDiff(emptyCase.a, emptyCase.b)
  518. if len(h) != emptyCase.have {
  519. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  520. }
  521. if len(n) != emptyCase.need {
  522. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  523. }
  524. }
  525. }
  526. // TestDeleteIgnorePerms checks, that a file gets deleted when the IgnorePerms
  527. // option is true and the permissions do not match between the file on disk and
  528. // in the db.
  529. func TestDeleteIgnorePerms(t *testing.T) {
  530. _, f := setupSendReceiveFolder(t)
  531. ffs := f.Filesystem()
  532. f.IgnorePerms = true
  533. name := "deleteIgnorePerms"
  534. file, err := ffs.Create(name)
  535. if err != nil {
  536. t.Error(err)
  537. }
  538. defer file.Close()
  539. stat, err := file.Stat()
  540. must(t, err)
  541. fi, err := scanner.CreateFileInfo(stat, name, ffs, false, false, config.XattrFilter{})
  542. must(t, err)
  543. ffs.Chmod(name, 0o600)
  544. if info, err := ffs.Stat(name); err == nil {
  545. fi.InodeChangeNs = info.InodeChangeTime().UnixNano()
  546. }
  547. scanChan := make(chan string, 1)
  548. err = f.checkToBeDeleted(fi, fi, true, scanChan)
  549. must(t, err)
  550. }
  551. func TestCopyOwner(t *testing.T) {
  552. // Verifies that owner and group are copied from the parent, for both
  553. // files and directories.
  554. if build.IsWindows {
  555. t.Skip("copying owner not supported on Windows")
  556. }
  557. const (
  558. expOwner = 1234
  559. expGroup = 5678
  560. )
  561. // This test hung on a regression, taking a long time to fail - speed that up.
  562. ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
  563. defer cancel()
  564. go func() {
  565. <-ctx.Done()
  566. if errors.Is(ctx.Err(), context.DeadlineExceeded) {
  567. pprof.Lookup("goroutine").WriteTo(os.Stdout, 2)
  568. panic("timed out before test finished")
  569. }
  570. }()
  571. // Set up a folder with the CopyParentOwner bit and backed by a fake
  572. // filesystem.
  573. m, f := setupSendReceiveFolder(t)
  574. f.folder.FolderConfiguration = newFolderConfiguration(m.cfg, f.ID, f.Label, config.FilesystemTypeFake, "/TestCopyOwner")
  575. f.folder.FolderConfiguration.CopyOwnershipFromParent = true
  576. // Create a parent dir with a certain owner/group.
  577. f.mtimefs.Mkdir("foo", 0o755)
  578. f.mtimefs.Lchown("foo", strconv.Itoa(expOwner), strconv.Itoa(expGroup))
  579. dir := protocol.FileInfo{
  580. Name: "foo/bar",
  581. Type: protocol.FileInfoTypeDirectory,
  582. Permissions: 0o755,
  583. }
  584. // Have the folder create a subdirectory, verify that it's the correct
  585. // owner/group.
  586. dbUpdateChan := make(chan dbUpdateJob, 1)
  587. scanChan := make(chan string)
  588. defer close(dbUpdateChan)
  589. f.handleDir(dir, dbUpdateChan, scanChan)
  590. select {
  591. case <-dbUpdateChan: // empty the channel for later
  592. case toScan := <-scanChan:
  593. t.Fatal("Unexpected receive on scanChan:", toScan)
  594. }
  595. info, err := f.mtimefs.Lstat("foo/bar")
  596. if err != nil {
  597. t.Fatal("Unexpected error (dir):", err)
  598. }
  599. if info.Owner() != expOwner || info.Group() != expGroup {
  600. t.Fatalf("Expected dir owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  601. }
  602. // Have the folder create a file, verify it's the correct owner/group.
  603. // File is zero sized to avoid having to handle copies/pulls.
  604. file := protocol.FileInfo{
  605. Name: "foo/bar/baz",
  606. Type: protocol.FileInfoTypeFile,
  607. Permissions: 0o644,
  608. }
  609. // Wire some stuff. The flow here is handleFile() -[copierChan]->
  610. // copierRoutine() -[finisherChan]-> finisherRoutine() -[dbUpdateChan]->
  611. // back to us and we're done. The copier routine doesn't do anything,
  612. // but it's the way data is passed around. When the database update
  613. // comes the finisher is done.
  614. finisherChan := make(chan *sharedPullerState)
  615. copierChan, copyWg := startCopier(t.Context(), f, nil, finisherChan)
  616. go f.finisherRoutine(t.Context(), finisherChan, dbUpdateChan, nil)
  617. defer func() {
  618. close(copierChan)
  619. copyWg.Wait()
  620. close(finisherChan)
  621. }()
  622. f.handleFile(t.Context(), file, copierChan)
  623. <-dbUpdateChan
  624. info, err = f.mtimefs.Lstat("foo/bar/baz")
  625. if err != nil {
  626. t.Fatal("Unexpected error (file):", err)
  627. }
  628. if info.Owner() != expOwner || info.Group() != expGroup {
  629. t.Fatalf("Expected file owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  630. }
  631. // Have the folder create a symlink. Verify it accordingly.
  632. symlink := protocol.FileInfo{
  633. Name: "foo/bar/sym",
  634. Type: protocol.FileInfoTypeSymlink,
  635. Permissions: 0o644,
  636. SymlinkTarget: []byte("over the rainbow"),
  637. }
  638. f.handleSymlink(symlink, dbUpdateChan, scanChan)
  639. select {
  640. case <-dbUpdateChan:
  641. case toScan := <-scanChan:
  642. t.Fatal("Unexpected receive on scanChan:", toScan)
  643. }
  644. info, err = f.mtimefs.Lstat("foo/bar/sym")
  645. if err != nil {
  646. t.Fatal("Unexpected error (file):", err)
  647. }
  648. if info.Owner() != expOwner || info.Group() != expGroup {
  649. t.Fatalf("Expected symlink owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  650. }
  651. }
  652. // TestSRConflictReplaceFileByDir checks that a conflict is created when an existing file
  653. // is replaced with a directory and versions are conflicting
  654. func TestSRConflictReplaceFileByDir(t *testing.T) {
  655. _, f := setupSendReceiveFolder(t)
  656. ffs := f.Filesystem()
  657. name := "foo"
  658. // create local file
  659. file := createEmptyFileInfo(t, name, ffs)
  660. file.Version = protocol.Vector{}.Update(myID.Short())
  661. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  662. // Simulate remote creating a dir with the same name
  663. file.Type = protocol.FileInfoTypeDirectory
  664. rem := device1.Short()
  665. file.Version = protocol.Vector{}.Update(rem)
  666. file.ModifiedBy = rem
  667. dbUpdateChan := make(chan dbUpdateJob, 1)
  668. scanChan := make(chan string, 1)
  669. f.handleDir(file, dbUpdateChan, scanChan)
  670. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  671. t.Fatal("Expected one conflict, got", len(confls))
  672. } else if scan := <-scanChan; confls[0] != scan {
  673. t.Fatal("Expected request to scan", confls[0], "got", scan)
  674. }
  675. }
  676. // TestSRConflictReplaceFileByLink checks that a conflict is created when an existing file
  677. // is replaced with a link and versions are conflicting
  678. func TestSRConflictReplaceFileByLink(t *testing.T) {
  679. _, f := setupSendReceiveFolder(t)
  680. ffs := f.Filesystem()
  681. name := "foo"
  682. // create local file
  683. file := createEmptyFileInfo(t, name, ffs)
  684. file.Version = protocol.Vector{}.Update(myID.Short())
  685. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  686. // Simulate remote creating a symlink with the same name
  687. file.Type = protocol.FileInfoTypeSymlink
  688. file.SymlinkTarget = []byte("bar")
  689. rem := device1.Short()
  690. file.Version = protocol.Vector{}.Update(rem)
  691. file.ModifiedBy = rem
  692. dbUpdateChan := make(chan dbUpdateJob, 1)
  693. scanChan := make(chan string, 1)
  694. f.handleSymlink(file, dbUpdateChan, scanChan)
  695. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  696. t.Fatal("Expected one conflict, got", len(confls))
  697. } else if scan := <-scanChan; confls[0] != scan {
  698. t.Fatal("Expected request to scan", confls[0], "got", scan)
  699. }
  700. }
  701. // TestDeleteBehindSymlink checks that we don't delete or schedule a scan
  702. // when trying to delete a file behind a symlink.
  703. func TestDeleteBehindSymlink(t *testing.T) {
  704. _, f := setupSendReceiveFolder(t)
  705. ffs := f.Filesystem()
  706. link := "link"
  707. linkFile := filepath.Join(link, "file")
  708. must(t, ffs.MkdirAll(link, 0o755))
  709. fi := createEmptyFileInfo(t, linkFile, ffs)
  710. f.updateLocalsFromScanning([]protocol.FileInfo{fi})
  711. must(t, ffs.Rename(linkFile, "file"))
  712. must(t, ffs.RemoveAll(link))
  713. must(t, ffs.CreateSymlink("/", link))
  714. fi.Deleted = true
  715. fi.Version = fi.Version.Update(device1.Short())
  716. scanChan := make(chan string, 1)
  717. dbUpdateChan := make(chan dbUpdateJob, 1)
  718. f.deleteFile(fi, dbUpdateChan, scanChan)
  719. select {
  720. case f := <-scanChan:
  721. t.Fatalf("Received %v on scanChan", f)
  722. case u := <-dbUpdateChan:
  723. if u.jobType != dbUpdateDeleteFile {
  724. t.Errorf("Expected jobType %v, got %v", dbUpdateDeleteFile, u.jobType)
  725. }
  726. if u.file.Name != fi.Name {
  727. t.Errorf("Expected update for %v, got %v", fi.Name, u.file.Name)
  728. }
  729. default:
  730. t.Fatalf("No db update received")
  731. }
  732. if _, err := ffs.Stat("file"); err != nil {
  733. t.Errorf("Expected no error when stating file behind symlink, got %v", err)
  734. }
  735. }
  736. // Reproduces https://github.com/syncthing/syncthing/issues/6559
  737. func TestPullCtxCancel(t *testing.T) {
  738. _, f := setupSendReceiveFolder(t)
  739. pullChan := make(chan pullBlockState)
  740. finisherChan := make(chan *sharedPullerState)
  741. ctx, cancel := context.WithCancel(t.Context())
  742. go f.pullerRoutine(ctx, pullChan, finisherChan)
  743. defer close(pullChan)
  744. emptyState := func() pullBlockState {
  745. return pullBlockState{
  746. sharedPullerState: newSharedPullerState(protocol.FileInfo{}, nil, f.folderID, "", nil, nil, false, false, protocol.FileInfo{}, false, false),
  747. block: protocol.BlockInfo{},
  748. }
  749. }
  750. cancel()
  751. done := make(chan struct{})
  752. defer close(done)
  753. for i := 0; i < 2; i++ {
  754. go func() {
  755. select {
  756. case pullChan <- emptyState():
  757. case <-done:
  758. }
  759. }()
  760. select {
  761. case s := <-finisherChan:
  762. if s.failed() == nil {
  763. t.Errorf("state %v not failed", i)
  764. }
  765. case <-time.After(5 * time.Second):
  766. t.Fatalf("timed out before receiving state %v on finisherChan", i)
  767. }
  768. }
  769. }
  770. func TestPullDeleteUnscannedDir(t *testing.T) {
  771. _, f := setupSendReceiveFolder(t)
  772. ffs := f.Filesystem()
  773. dir := "foobar"
  774. must(t, ffs.MkdirAll(dir, 0o777))
  775. fi := protocol.FileInfo{
  776. Name: dir,
  777. }
  778. scanChan := make(chan string, 1)
  779. dbUpdateChan := make(chan dbUpdateJob, 1)
  780. f.deleteDir(fi, dbUpdateChan, scanChan)
  781. if _, err := ffs.Stat(dir); fs.IsNotExist(err) {
  782. t.Error("directory has been deleted")
  783. }
  784. select {
  785. case toScan := <-scanChan:
  786. if toScan != dir {
  787. t.Errorf("expected %v to be scanned, got %v", dir, toScan)
  788. }
  789. default:
  790. t.Error("nothing was scheduled for scanning")
  791. }
  792. }
  793. func TestPullCaseOnlyPerformFinish(t *testing.T) {
  794. m, f := setupSendReceiveFolder(t)
  795. ffs := f.Filesystem()
  796. name := "foo"
  797. contents := []byte("contents")
  798. writeFile(t, ffs, name, contents)
  799. must(t, f.scanSubdirs(t.Context(), nil))
  800. var cur protocol.FileInfo
  801. hasCur := false
  802. it, errFn := m.LocalFiles(f.ID, protocol.LocalDeviceID)
  803. for i := range it {
  804. if hasCur {
  805. t.Fatal("got more than one file")
  806. }
  807. cur = i
  808. hasCur = true
  809. }
  810. if err := errFn(); err != nil {
  811. t.Fatal(err)
  812. }
  813. if !hasCur {
  814. t.Fatal("file is missing")
  815. }
  816. remote := cur
  817. remote.Version = protocol.Vector{}.Update(device1.Short())
  818. remote.Name = strings.ToUpper(cur.Name)
  819. temp := fs.TempName(remote.Name)
  820. writeFile(t, ffs, temp, contents)
  821. scanChan := make(chan string, 1)
  822. dbUpdateChan := make(chan dbUpdateJob, 1)
  823. err := f.performFinish(remote, cur, hasCur, temp, dbUpdateChan, scanChan)
  824. select {
  825. case <-dbUpdateChan: // boring case sensitive filesystem
  826. return
  827. case <-scanChan:
  828. t.Error("no need to scan anything here")
  829. default:
  830. }
  831. var caseErr *fs.CaseConflictError
  832. if !errors.As(err, &caseErr) {
  833. t.Error("Expected case conflict error, got", err)
  834. }
  835. }
  836. func TestPullCaseOnlyDir(t *testing.T) {
  837. testPullCaseOnlyDirOrSymlink(t, true)
  838. }
  839. func TestPullCaseOnlySymlink(t *testing.T) {
  840. if build.IsWindows {
  841. t.Skip("symlinks not supported on windows")
  842. }
  843. testPullCaseOnlyDirOrSymlink(t, false)
  844. }
  845. func testPullCaseOnlyDirOrSymlink(t *testing.T, dir bool) {
  846. m, f := setupSendReceiveFolder(t)
  847. ffs := f.Filesystem()
  848. name := "foo"
  849. if dir {
  850. must(t, ffs.Mkdir(name, 0o777))
  851. } else {
  852. must(t, ffs.CreateSymlink("target", name))
  853. }
  854. must(t, f.scanSubdirs(t.Context(), nil))
  855. var cur protocol.FileInfo
  856. hasCur := false
  857. it, errFn := m.LocalFiles(f.ID, protocol.LocalDeviceID)
  858. for i := range it {
  859. if hasCur {
  860. t.Fatal("got more than one file")
  861. }
  862. cur = i
  863. hasCur = true
  864. }
  865. if err := errFn(); err != nil {
  866. t.Fatal(err)
  867. }
  868. if !hasCur {
  869. t.Fatal("file is missing")
  870. }
  871. scanChan := make(chan string, 1)
  872. dbUpdateChan := make(chan dbUpdateJob, 1)
  873. remote := cur
  874. remote.Version = protocol.Vector{}.Update(device1.Short())
  875. remote.Name = strings.ToUpper(cur.Name)
  876. if dir {
  877. f.handleDir(remote, dbUpdateChan, scanChan)
  878. } else {
  879. f.handleSymlink(remote, dbUpdateChan, scanChan)
  880. }
  881. select {
  882. case <-dbUpdateChan: // boring case sensitive filesystem
  883. return
  884. case <-scanChan:
  885. t.Error("no need to scan anything here")
  886. default:
  887. }
  888. if errStr, ok := f.tempPullErrors[remote.Name]; !ok {
  889. t.Error("missing error for", remote.Name)
  890. } else if !strings.Contains(errStr, "uses different upper or lowercase") {
  891. t.Error("unexpected error", errStr, "for", remote.Name)
  892. }
  893. }
  894. func TestPullTempFileCaseConflict(t *testing.T) {
  895. _, f := setupSendReceiveFolder(t)
  896. copyChan := make(chan copyBlocksState, 1)
  897. file := protocol.FileInfo{Name: "foo"}
  898. confl := "Foo"
  899. tempNameConfl := fs.TempName(confl)
  900. if fd, err := f.mtimefs.Create(tempNameConfl); err != nil {
  901. t.Fatal(err)
  902. } else {
  903. if _, err := fd.Write([]byte("data")); err != nil {
  904. t.Fatal(err)
  905. }
  906. fd.Close()
  907. }
  908. f.handleFile(t.Context(), file, copyChan)
  909. cs := <-copyChan
  910. if _, err := cs.tempFile(); err != nil {
  911. t.Error(err)
  912. } else {
  913. cs.finalClose()
  914. }
  915. }
  916. func TestPullCaseOnlyRename(t *testing.T) {
  917. m, f := setupSendReceiveFolder(t)
  918. // tempNameConfl := fs.TempName(confl)
  919. name := "foo"
  920. if fd, err := f.mtimefs.Create(name); err != nil {
  921. t.Fatal(err)
  922. } else {
  923. if _, err := fd.Write([]byte("data")); err != nil {
  924. t.Fatal(err)
  925. }
  926. fd.Close()
  927. }
  928. must(t, f.scanSubdirs(t.Context(), nil))
  929. cur, ok := m.testCurrentFolderFile(f.ID, name)
  930. if !ok {
  931. t.Fatal("file missing")
  932. }
  933. deleted := cur
  934. deleted.SetDeleted(myID.Short())
  935. confl := cur
  936. confl.Name = "Foo"
  937. confl.Version = confl.Version.Update(device1.Short())
  938. dbUpdateChan := make(chan dbUpdateJob, 2)
  939. scanChan := make(chan string, 2)
  940. if err := f.renameFile(cur, deleted, confl, dbUpdateChan, scanChan); err != nil {
  941. t.Error(err)
  942. }
  943. }
  944. func TestPullSymlinkOverExistingWindows(t *testing.T) {
  945. if !build.IsWindows {
  946. t.Skip()
  947. }
  948. m, f := setupSendReceiveFolder(t)
  949. conn := addFakeConn(m, device1, f.ID)
  950. name := "foo"
  951. if fd, err := f.mtimefs.Create(name); err != nil {
  952. t.Fatal(err)
  953. } else {
  954. if _, err := fd.Write([]byte("data")); err != nil {
  955. t.Fatal(err)
  956. }
  957. fd.Close()
  958. }
  959. must(t, f.scanSubdirs(t.Context(), nil))
  960. file, ok := m.testCurrentFolderFile(f.ID, name)
  961. if !ok {
  962. t.Fatal("file missing")
  963. }
  964. must(t, m.Index(conn, &protocol.Index{Folder: f.ID, Files: []protocol.FileInfo{{Name: name, Type: protocol.FileInfoTypeSymlink, Version: file.Version.Update(device1.Short())}}}))
  965. scanChan := make(chan string)
  966. changed, err := f.pullerIteration(t.Context(), scanChan)
  967. must(t, err)
  968. if changed != 1 {
  969. t.Error("Expected one change in pull, got", changed)
  970. }
  971. if file, ok := m.testCurrentFolderFile(f.ID, name); !ok {
  972. t.Error("symlink entry missing")
  973. } else if !file.IsUnsupported() {
  974. t.Error("symlink entry isn't marked as unsupported")
  975. }
  976. if _, err := f.mtimefs.Lstat(name); err == nil {
  977. t.Error("old file still exists on disk")
  978. } else if !fs.IsNotExist(err) {
  979. t.Error(err)
  980. }
  981. }
  982. func TestPullDeleteCaseConflict(t *testing.T) {
  983. _, f := setupSendReceiveFolder(t)
  984. name := "foo"
  985. fi := protocol.FileInfo{Name: "Foo"}
  986. dbUpdateChan := make(chan dbUpdateJob, 1)
  987. scanChan := make(chan string)
  988. if fd, err := f.mtimefs.Create(name); err != nil {
  989. t.Fatal(err)
  990. } else {
  991. if _, err := fd.Write([]byte("data")); err != nil {
  992. t.Fatal(err)
  993. }
  994. fd.Close()
  995. }
  996. f.deleteFileWithCurrent(fi, protocol.FileInfo{}, false, dbUpdateChan, scanChan)
  997. select {
  998. case <-dbUpdateChan:
  999. default:
  1000. t.Error("Missing db update for file")
  1001. }
  1002. f.deleteDir(fi, dbUpdateChan, scanChan)
  1003. select {
  1004. case <-dbUpdateChan:
  1005. default:
  1006. t.Error("Missing db update for dir")
  1007. }
  1008. }
  1009. func TestPullDeleteIgnoreChildDir(t *testing.T) {
  1010. _, f := setupSendReceiveFolder(t)
  1011. parent := "parent"
  1012. del := "ignored"
  1013. child := "keep"
  1014. matcher := ignore.New(f.mtimefs)
  1015. must(t, matcher.Parse(bytes.NewBufferString(fmt.Sprintf(`
  1016. !%v
  1017. (?d)%v
  1018. `, child, del)), ""))
  1019. f.ignores = matcher
  1020. must(t, f.mtimefs.Mkdir(parent, 0o777))
  1021. must(t, f.mtimefs.Mkdir(filepath.Join(parent, del), 0o777))
  1022. must(t, f.mtimefs.Mkdir(filepath.Join(parent, del, child), 0o777))
  1023. scanChan := make(chan string, 2)
  1024. err := f.deleteDirOnDisk(parent, scanChan)
  1025. if err == nil {
  1026. t.Error("no error")
  1027. }
  1028. }
  1029. func cleanupSharedPullerState(s *sharedPullerState) {
  1030. s.mut.Lock()
  1031. defer s.mut.Unlock()
  1032. if s.writer == nil {
  1033. return
  1034. }
  1035. s.writer.mut.Lock()
  1036. s.writer.fd.Close()
  1037. s.writer.mut.Unlock()
  1038. }
  1039. func startCopier(ctx context.Context, f *sendReceiveFolder, pullChan chan<- pullBlockState, finisherChan chan<- *sharedPullerState) (chan copyBlocksState, *sync.WaitGroup) {
  1040. copyChan := make(chan copyBlocksState)
  1041. wg := new(sync.WaitGroup)
  1042. wg.Go(func() {
  1043. f.copierRoutine(ctx, copyChan, pullChan, finisherChan)
  1044. })
  1045. return copyChan, wg
  1046. }