folder_sendrecv_test.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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. "crypto/rand"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. "strings"
  18. "testing"
  19. "time"
  20. "github.com/syncthing/syncthing/lib/events"
  21. "github.com/syncthing/syncthing/lib/fs"
  22. "github.com/syncthing/syncthing/lib/ignore"
  23. "github.com/syncthing/syncthing/lib/osutil"
  24. "github.com/syncthing/syncthing/lib/protocol"
  25. "github.com/syncthing/syncthing/lib/scanner"
  26. "github.com/syncthing/syncthing/lib/sync"
  27. )
  28. var blocks = []protocol.BlockInfo{
  29. {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
  30. {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}},
  31. {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}},
  32. {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}},
  33. {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}},
  34. {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}},
  35. {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}},
  36. {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}},
  37. {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}},
  38. }
  39. var folders = []string{"default"}
  40. var diffTestData = []struct {
  41. a string
  42. b string
  43. s int
  44. d []protocol.BlockInfo
  45. }{
  46. {"contents", "contents", 1024, []protocol.BlockInfo{}},
  47. {"", "", 1024, []protocol.BlockInfo{}},
  48. {"contents", "contents", 3, []protocol.BlockInfo{}},
  49. {"contents", "cantents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}}},
  50. {"contents", "contants", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}}},
  51. {"contents", "cantants", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}}},
  52. {"contents", "", 3, []protocol.BlockInfo{{Offset: 0, Size: 0}}},
  53. {"", "contents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  54. {"con", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  55. {"contents", "con", 3, nil},
  56. {"contents", "cont", 3, []protocol.BlockInfo{{Offset: 3, Size: 1}}},
  57. {"cont", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  58. }
  59. func setupFile(filename string, blockNumbers []int) protocol.FileInfo {
  60. // Create existing file
  61. existingBlocks := make([]protocol.BlockInfo, len(blockNumbers))
  62. for i := range blockNumbers {
  63. existingBlocks[i] = blocks[blockNumbers[i]]
  64. }
  65. return protocol.FileInfo{
  66. Name: filename,
  67. Blocks: existingBlocks,
  68. }
  69. }
  70. func createEmptyFileInfo(t *testing.T, name string, fs fs.Filesystem) protocol.FileInfo {
  71. t.Helper()
  72. writeFile(t, fs, name, nil)
  73. fi, err := fs.Stat(name)
  74. must(t, err)
  75. file, err := scanner.CreateFileInfo(fi, name, fs)
  76. must(t, err)
  77. return file
  78. }
  79. // Sets up a folder and model, but makes sure the services aren't actually running.
  80. func setupSendReceiveFolder(t testing.TB, files ...protocol.FileInfo) (*testModel, *sendReceiveFolder, context.CancelFunc) {
  81. w, fcfg, wCancel := tmpDefaultWrapper()
  82. // Initialise model and stop immediately.
  83. model := setupModel(t, w)
  84. model.cancel()
  85. <-model.stopped
  86. f := model.folderRunners[fcfg.ID].(*sendReceiveFolder)
  87. f.tempPullErrors = make(map[string]string)
  88. f.ctx = context.Background()
  89. // Update index
  90. if files != nil {
  91. f.updateLocalsFromScanning(files)
  92. }
  93. return model, f, wCancel
  94. }
  95. func cleanupSRFolder(f *sendReceiveFolder, m *testModel, wrapperCancel context.CancelFunc) {
  96. wrapperCancel()
  97. os.Remove(m.cfg.ConfigPath())
  98. os.RemoveAll(f.Filesystem().URI())
  99. }
  100. // Layout of the files: (indexes from the above array)
  101. // 12345678 - Required file
  102. // 02005008 - Existing file (currently in the index)
  103. // 02340070 - Temp file on the disk
  104. func TestHandleFile(t *testing.T) {
  105. // After the diff between required and existing we should:
  106. // Copy: 2, 5, 8
  107. // Pull: 1, 3, 4, 6, 7
  108. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  109. existingFile := setupFile("filex", existingBlocks)
  110. requiredFile := existingFile
  111. requiredFile.Blocks = blocks[1:]
  112. m, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  113. defer cleanupSRFolder(f, m, wcfgCancel)
  114. copyChan := make(chan copyBlocksState, 1)
  115. f.handleFile(requiredFile, fsetSnapshot(t, f.fset), copyChan)
  116. // Receive the results
  117. toCopy := <-copyChan
  118. if len(toCopy.blocks) != 8 {
  119. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  120. }
  121. for _, block := range blocks[1:] {
  122. found := false
  123. for _, toCopyBlock := range toCopy.blocks {
  124. if string(toCopyBlock.Hash) == string(block.Hash) {
  125. found = true
  126. break
  127. }
  128. }
  129. if !found {
  130. t.Errorf("Did not find block %s", block.String())
  131. }
  132. }
  133. }
  134. func TestHandleFileWithTemp(t *testing.T) {
  135. // After diff between required and existing we should:
  136. // Copy: 2, 5, 8
  137. // Pull: 1, 3, 4, 6, 7
  138. // After dropping out blocks already on the temp file we should:
  139. // Copy: 5, 8
  140. // Pull: 1, 6
  141. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  142. existingFile := setupFile("file", existingBlocks)
  143. requiredFile := existingFile
  144. requiredFile.Blocks = blocks[1:]
  145. m, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  146. defer cleanupSRFolder(f, m, wcfgCancel)
  147. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  148. t.Fatal(err)
  149. }
  150. copyChan := make(chan copyBlocksState, 1)
  151. f.handleFile(requiredFile, fsetSnapshot(t, f.fset), copyChan)
  152. // Receive the results
  153. toCopy := <-copyChan
  154. if len(toCopy.blocks) != 4 {
  155. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  156. }
  157. for _, idx := range []int{1, 5, 6, 8} {
  158. found := false
  159. block := blocks[idx]
  160. for _, toCopyBlock := range toCopy.blocks {
  161. if string(toCopyBlock.Hash) == string(block.Hash) {
  162. found = true
  163. break
  164. }
  165. }
  166. if !found {
  167. t.Errorf("Did not find block %s", block.String())
  168. }
  169. }
  170. }
  171. func TestCopierFinder(t *testing.T) {
  172. methods := []fs.CopyRangeMethod{fs.CopyRangeMethodStandard, fs.CopyRangeMethodAllWithFallback}
  173. if runtime.GOOS == "linux" {
  174. methods = append(methods, fs.CopyRangeMethodSendFile)
  175. }
  176. for _, method := range methods {
  177. t.Run(method.String(), func(t *testing.T) {
  178. // After diff between required and existing we should:
  179. // Copy: 1, 2, 3, 4, 6, 7, 8
  180. // Since there is no existing file, nor a temp file
  181. // After dropping out blocks found locally:
  182. // Pull: 1, 5, 6, 8
  183. tempFile := fs.TempName("file2")
  184. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  185. existingFile := setupFile(fs.TempName("file"), existingBlocks)
  186. existingFile.Size = 1
  187. requiredFile := existingFile
  188. requiredFile.Blocks = blocks[1:]
  189. requiredFile.Name = "file2"
  190. m, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  191. f.CopyRangeMethod = method
  192. defer cleanupSRFolder(f, m, wcfgCancel)
  193. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  194. t.Fatal(err)
  195. }
  196. copyChan := make(chan copyBlocksState)
  197. pullChan := make(chan pullBlockState, 4)
  198. finisherChan := make(chan *sharedPullerState, 1)
  199. // Run a single fetcher routine
  200. go f.copierRoutine(copyChan, pullChan, finisherChan)
  201. defer close(copyChan)
  202. f.handleFile(requiredFile, fsetSnapshot(t, f.fset), copyChan)
  203. timeout := time.After(10 * time.Second)
  204. pulls := make([]pullBlockState, 4)
  205. for i := 0; i < 4; i++ {
  206. select {
  207. case pulls[i] = <-pullChan:
  208. case <-timeout:
  209. t.Fatalf("Timed out before receiving all 4 states on pullChan (already got %v)", i)
  210. }
  211. }
  212. var finish *sharedPullerState
  213. select {
  214. case finish = <-finisherChan:
  215. case <-timeout:
  216. t.Fatal("Timed out before receiving 4 states on pullChan")
  217. }
  218. defer cleanupSharedPullerState(finish)
  219. select {
  220. case <-pullChan:
  221. t.Fatal("Pull channel has data to be read")
  222. case <-finisherChan:
  223. t.Fatal("Finisher channel has data to be read")
  224. default:
  225. }
  226. // Verify that the right blocks went into the pull list.
  227. // They are pulled in random order.
  228. for _, idx := range []int{1, 5, 6, 8} {
  229. found := false
  230. block := blocks[idx]
  231. for _, pulledBlock := range pulls {
  232. if string(pulledBlock.block.Hash) == string(block.Hash) {
  233. found = true
  234. break
  235. }
  236. }
  237. if !found {
  238. t.Errorf("Did not find block %s", block.String())
  239. }
  240. if string(finish.file.Blocks[idx-1].Hash) != string(blocks[idx].Hash) {
  241. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  242. }
  243. }
  244. // Verify that the fetched blocks have actually been written to the temp file
  245. blks, err := scanner.HashFile(context.TODO(), f.Filesystem(), tempFile, protocol.MinBlockSize, nil, false)
  246. if err != nil {
  247. t.Log(err)
  248. }
  249. for _, eq := range []int{2, 3, 4, 7} {
  250. if string(blks[eq-1].Hash) != string(blocks[eq].Hash) {
  251. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  252. }
  253. }
  254. })
  255. }
  256. }
  257. func TestWeakHash(t *testing.T) {
  258. // Setup the model/pull environment
  259. model, fo, wcfgCancel := setupSendReceiveFolder(t)
  260. defer cleanupSRFolder(fo, model, wcfgCancel)
  261. ffs := fo.Filesystem()
  262. tempFile := fs.TempName("weakhash")
  263. var shift int64 = 10
  264. var size int64 = 1 << 20
  265. expectBlocks := int(size / protocol.MinBlockSize)
  266. expectPulls := int(shift / protocol.MinBlockSize)
  267. if shift > 0 {
  268. expectPulls++
  269. }
  270. f, err := ffs.Create("weakhash")
  271. must(t, err)
  272. defer f.Close()
  273. _, err = io.CopyN(f, rand.Reader, size)
  274. if err != nil {
  275. t.Error(err)
  276. }
  277. info, err := f.Stat()
  278. if err != nil {
  279. t.Error(err)
  280. }
  281. // Create two files, second file has `shifted` bytes random prefix, yet
  282. // both are of the same length, for example:
  283. // File 1: abcdefgh
  284. // File 2: xyabcdef
  285. f.Seek(0, os.SEEK_SET)
  286. existing, err := scanner.Blocks(context.TODO(), f, protocol.MinBlockSize, size, nil, true)
  287. if err != nil {
  288. t.Error(err)
  289. }
  290. f.Seek(0, os.SEEK_SET)
  291. remainder := io.LimitReader(f, size-shift)
  292. prefix := io.LimitReader(rand.Reader, shift)
  293. nf := io.MultiReader(prefix, remainder)
  294. desired, err := scanner.Blocks(context.TODO(), nf, protocol.MinBlockSize, size, nil, true)
  295. if err != nil {
  296. t.Error(err)
  297. }
  298. existingFile := protocol.FileInfo{
  299. Name: "weakhash",
  300. Blocks: existing,
  301. Size: size,
  302. ModifiedS: info.ModTime().Unix(),
  303. ModifiedNs: info.ModTime().Nanosecond(),
  304. }
  305. desiredFile := protocol.FileInfo{
  306. Name: "weakhash",
  307. Size: size,
  308. Blocks: desired,
  309. ModifiedS: info.ModTime().Unix() + 1,
  310. }
  311. fo.updateLocalsFromScanning([]protocol.FileInfo{existingFile})
  312. copyChan := make(chan copyBlocksState)
  313. pullChan := make(chan pullBlockState, expectBlocks)
  314. finisherChan := make(chan *sharedPullerState, 1)
  315. // Run a single fetcher routine
  316. go fo.copierRoutine(copyChan, pullChan, finisherChan)
  317. defer close(copyChan)
  318. // Test 1 - no weak hashing, file gets fully repulled (`expectBlocks` pulls).
  319. fo.WeakHashThresholdPct = 101
  320. fo.handleFile(desiredFile, fsetSnapshot(t, fo.fset), copyChan)
  321. var pulls []pullBlockState
  322. timeout := time.After(10 * time.Second)
  323. for len(pulls) < expectBlocks {
  324. select {
  325. case pull := <-pullChan:
  326. pulls = append(pulls, pull)
  327. case <-timeout:
  328. t.Fatalf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  329. }
  330. }
  331. finish := <-finisherChan
  332. select {
  333. case <-pullChan:
  334. t.Fatal("Pull channel has data to be read")
  335. case <-finisherChan:
  336. t.Fatal("Finisher channel has data to be read")
  337. default:
  338. }
  339. cleanupSharedPullerState(finish)
  340. if err := ffs.Remove(tempFile); err != nil {
  341. t.Fatal(err)
  342. }
  343. // Test 2 - using weak hash, expectPulls blocks pulled.
  344. fo.WeakHashThresholdPct = -1
  345. fo.handleFile(desiredFile, fsetSnapshot(t, fo.fset), copyChan)
  346. pulls = pulls[:0]
  347. for len(pulls) < expectPulls {
  348. select {
  349. case pull := <-pullChan:
  350. pulls = append(pulls, pull)
  351. case <-time.After(10 * time.Second):
  352. t.Fatalf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  353. }
  354. }
  355. finish = <-finisherChan
  356. cleanupSharedPullerState(finish)
  357. expectShifted := expectBlocks - expectPulls
  358. if finish.copyOriginShifted != expectShifted {
  359. t.Errorf("did not copy %d shifted", expectShifted)
  360. }
  361. }
  362. // Test that updating a file removes its old blocks from the blockmap
  363. func TestCopierCleanup(t *testing.T) {
  364. iterFn := func(folder, file string, index int32) bool {
  365. return true
  366. }
  367. // Create a file
  368. file := setupFile("test", []int{0})
  369. file.Size = 1
  370. m, f, wcfgCancel := setupSendReceiveFolder(t, file)
  371. defer cleanupSRFolder(f, m, wcfgCancel)
  372. file.Blocks = []protocol.BlockInfo{blocks[1]}
  373. file.Version = file.Version.Update(myID.Short())
  374. // Update index (removing old blocks)
  375. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  376. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  377. t.Error("Unexpected block found")
  378. }
  379. if !m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  380. t.Error("Expected block not found")
  381. }
  382. file.Blocks = []protocol.BlockInfo{blocks[0]}
  383. file.Version = file.Version.Update(myID.Short())
  384. // Update index (removing old blocks)
  385. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  386. if !m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  387. t.Error("Unexpected block found")
  388. }
  389. if m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  390. t.Error("Expected block not found")
  391. }
  392. }
  393. func TestDeregisterOnFailInCopy(t *testing.T) {
  394. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  395. m, f, wcfgCancel := setupSendReceiveFolder(t)
  396. defer cleanupSRFolder(f, m, wcfgCancel)
  397. // Set up our evet subscription early
  398. s := m.evLogger.Subscribe(events.ItemFinished)
  399. // queue.Done should be called by the finisher routine
  400. f.queue.Push("filex", 0, time.Time{})
  401. f.queue.Pop()
  402. if f.queue.lenProgress() != 1 {
  403. t.Fatal("Expected file in progress")
  404. }
  405. pullChan := make(chan pullBlockState)
  406. finisherBufferChan := make(chan *sharedPullerState, 1)
  407. finisherChan := make(chan *sharedPullerState)
  408. dbUpdateChan := make(chan dbUpdateJob, 1)
  409. snap := fsetSnapshot(t, f.fset)
  410. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  411. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, make(chan string))
  412. defer func() {
  413. close(copyChan)
  414. copyWg.Wait()
  415. close(pullChan)
  416. close(finisherBufferChan)
  417. close(finisherChan)
  418. }()
  419. f.handleFile(file, snap, copyChan)
  420. // Receive a block at puller, to indicate that at least a single copier
  421. // loop has been performed.
  422. var toPull pullBlockState
  423. select {
  424. case toPull = <-pullChan:
  425. case <-time.After(10 * time.Second):
  426. t.Fatal("timed out")
  427. }
  428. // Unblock copier
  429. go func() {
  430. for range pullChan {
  431. }
  432. }()
  433. // Close the file, causing errors on further access
  434. toPull.sharedPullerState.fail(os.ErrNotExist)
  435. select {
  436. case state := <-finisherBufferChan:
  437. // At this point the file should still be registered with both the job
  438. // queue, and the progress emitter. Verify this.
  439. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  440. t.Fatal("Could not find file")
  441. }
  442. // Pass the file down the real finisher, and give it time to consume
  443. finisherChan <- state
  444. t0 := time.Now()
  445. if ev, err := s.Poll(time.Minute); err != nil {
  446. t.Fatal("Got error waiting for ItemFinished event:", err)
  447. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  448. t.Fatal("Got ItemFinished event for wrong file:", n)
  449. }
  450. t.Log("event took", time.Since(t0))
  451. state.mut.Lock()
  452. stateWriter := state.writer
  453. state.mut.Unlock()
  454. if stateWriter != nil {
  455. t.Fatal("File not closed?")
  456. }
  457. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  458. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  459. }
  460. // Doing it again should have no effect
  461. finisherChan <- state
  462. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  463. t.Fatal("Expected timeout, not another event", err)
  464. }
  465. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  466. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  467. }
  468. case <-time.After(5 * time.Second):
  469. t.Fatal("Didn't get anything to the finisher")
  470. }
  471. }
  472. func TestDeregisterOnFailInPull(t *testing.T) {
  473. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  474. m, f, wcfgCancel := setupSendReceiveFolder(t)
  475. defer cleanupSRFolder(f, m, wcfgCancel)
  476. // Set up our evet subscription early
  477. s := m.evLogger.Subscribe(events.ItemFinished)
  478. // queue.Done should be called by the finisher routine
  479. f.queue.Push("filex", 0, time.Time{})
  480. f.queue.Pop()
  481. if f.queue.lenProgress() != 1 {
  482. t.Fatal("Expected file in progress")
  483. }
  484. pullChan := make(chan pullBlockState)
  485. finisherBufferChan := make(chan *sharedPullerState)
  486. finisherChan := make(chan *sharedPullerState)
  487. dbUpdateChan := make(chan dbUpdateJob, 1)
  488. snap := fsetSnapshot(t, f.fset)
  489. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  490. pullWg := sync.NewWaitGroup()
  491. pullWg.Add(1)
  492. go func() {
  493. f.pullerRoutine(snap, pullChan, finisherBufferChan)
  494. pullWg.Done()
  495. }()
  496. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, make(chan string))
  497. defer func() {
  498. // Unblock copier and puller
  499. go func() {
  500. for range finisherBufferChan {
  501. }
  502. }()
  503. close(copyChan)
  504. copyWg.Wait()
  505. close(pullChan)
  506. pullWg.Wait()
  507. close(finisherBufferChan)
  508. close(finisherChan)
  509. }()
  510. f.handleFile(file, snap, copyChan)
  511. // Receive at finisher, we should error out as puller has nowhere to pull
  512. // from.
  513. timeout = time.Second
  514. // Both the puller and copier may send to the finisherBufferChan.
  515. var state *sharedPullerState
  516. after := time.After(5 * time.Second)
  517. for {
  518. select {
  519. case state = <-finisherBufferChan:
  520. case <-after:
  521. t.Fatal("Didn't get failed state to the finisher")
  522. }
  523. if state.failed() != nil {
  524. break
  525. }
  526. }
  527. // At this point the file should still be registered with both the job
  528. // queue, and the progress emitter. Verify this.
  529. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  530. t.Fatal("Could not find file")
  531. }
  532. // Pass the file down the real finisher, and give it time to consume
  533. finisherChan <- state
  534. t0 := time.Now()
  535. if ev, err := s.Poll(time.Minute); err != nil {
  536. t.Fatal("Got error waiting for ItemFinished event:", err)
  537. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  538. t.Fatal("Got ItemFinished event for wrong file:", n)
  539. }
  540. t.Log("event took", time.Since(t0))
  541. state.mut.Lock()
  542. stateWriter := state.writer
  543. state.mut.Unlock()
  544. if stateWriter != nil {
  545. t.Fatal("File not closed?")
  546. }
  547. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  548. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  549. }
  550. // Doing it again should have no effect
  551. finisherChan <- state
  552. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  553. t.Fatal("Expected timeout, not another event", err)
  554. }
  555. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  556. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  557. }
  558. }
  559. func TestIssue3164(t *testing.T) {
  560. m, f, wcfgCancel := setupSendReceiveFolder(t)
  561. defer cleanupSRFolder(f, m, wcfgCancel)
  562. ffs := f.Filesystem()
  563. tmpDir := ffs.URI()
  564. ignDir := filepath.Join("issue3164", "oktodelete")
  565. subDir := filepath.Join(ignDir, "foobar")
  566. must(t, ffs.MkdirAll(subDir, 0777))
  567. must(t, os.WriteFile(filepath.Join(tmpDir, subDir, "file"), []byte("Hello"), 0644))
  568. must(t, os.WriteFile(filepath.Join(tmpDir, ignDir, "file"), []byte("Hello"), 0644))
  569. file := protocol.FileInfo{
  570. Name: "issue3164",
  571. }
  572. must(t, f.scanSubdirs(nil))
  573. matcher := ignore.New(ffs)
  574. must(t, matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""))
  575. f.ignores = matcher
  576. dbUpdateChan := make(chan dbUpdateJob, 1)
  577. f.deleteDir(file, fsetSnapshot(t, f.fset), dbUpdateChan, make(chan string))
  578. if _, err := ffs.Stat("issue3164"); !fs.IsNotExist(err) {
  579. t.Fatal(err)
  580. }
  581. }
  582. func TestDiff(t *testing.T) {
  583. for i, test := range diffTestData {
  584. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  585. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  586. _, d := blockDiff(a, b)
  587. if len(d) != len(test.d) {
  588. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  589. } else {
  590. for j := range test.d {
  591. if d[j].Offset != test.d[j].Offset {
  592. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  593. }
  594. if d[j].Size != test.d[j].Size {
  595. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  596. }
  597. }
  598. }
  599. }
  600. }
  601. func BenchmarkDiff(b *testing.B) {
  602. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  603. for _, test := range diffTestData {
  604. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  605. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  606. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{a, b})
  607. }
  608. b.ReportAllocs()
  609. b.ResetTimer()
  610. for i := 0; i < b.N; i++ {
  611. for _, tc := range testCases {
  612. blockDiff(tc.a, tc.b)
  613. }
  614. }
  615. }
  616. func TestDiffEmpty(t *testing.T) {
  617. emptyCases := []struct {
  618. a []protocol.BlockInfo
  619. b []protocol.BlockInfo
  620. need int
  621. have int
  622. }{
  623. {nil, nil, 0, 0},
  624. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  625. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  626. }
  627. for _, emptyCase := range emptyCases {
  628. h, n := blockDiff(emptyCase.a, emptyCase.b)
  629. if len(h) != emptyCase.have {
  630. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  631. }
  632. if len(n) != emptyCase.need {
  633. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  634. }
  635. }
  636. }
  637. // TestDeleteIgnorePerms checks, that a file gets deleted when the IgnorePerms
  638. // option is true and the permissions do not match between the file on disk and
  639. // in the db.
  640. func TestDeleteIgnorePerms(t *testing.T) {
  641. m, f, wcfgCancel := setupSendReceiveFolder(t)
  642. defer cleanupSRFolder(f, m, wcfgCancel)
  643. ffs := f.Filesystem()
  644. f.IgnorePerms = true
  645. name := "deleteIgnorePerms"
  646. file, err := ffs.Create(name)
  647. if err != nil {
  648. t.Error(err)
  649. }
  650. defer file.Close()
  651. stat, err := file.Stat()
  652. must(t, err)
  653. fi, err := scanner.CreateFileInfo(stat, name, ffs)
  654. must(t, err)
  655. ffs.Chmod(name, 0600)
  656. scanChan := make(chan string, 1)
  657. err = f.checkToBeDeleted(fi, fi, true, scanChan)
  658. must(t, err)
  659. }
  660. func TestCopyOwner(t *testing.T) {
  661. // Verifies that owner and group are copied from the parent, for both
  662. // files and directories.
  663. if runtime.GOOS == "windows" {
  664. t.Skip("copying owner not supported on Windows")
  665. }
  666. const (
  667. expOwner = 1234
  668. expGroup = 5678
  669. )
  670. // Set up a folder with the CopyParentOwner bit and backed by a fake
  671. // filesystem.
  672. m, f, wcfgCancel := setupSendReceiveFolder(t)
  673. defer cleanupSRFolder(f, m, wcfgCancel)
  674. f.folder.FolderConfiguration = newFolderConfiguration(m.cfg, f.ID, f.Label, fs.FilesystemTypeFake, "/TestCopyOwner")
  675. f.folder.FolderConfiguration.CopyOwnershipFromParent = true
  676. f.fset = newFileSet(t, f.ID, m.db)
  677. f.mtimefs = f.fset.MtimeFS(f.Filesystem())
  678. // Create a parent dir with a certain owner/group.
  679. f.mtimefs.Mkdir("foo", 0755)
  680. f.mtimefs.Lchown("foo", expOwner, expGroup)
  681. dir := protocol.FileInfo{
  682. Name: "foo/bar",
  683. Type: protocol.FileInfoTypeDirectory,
  684. Permissions: 0755,
  685. }
  686. // Have the folder create a subdirectory, verify that it's the correct
  687. // owner/group.
  688. dbUpdateChan := make(chan dbUpdateJob, 1)
  689. scanChan := make(chan string)
  690. defer close(dbUpdateChan)
  691. f.handleDir(dir, fsetSnapshot(t, f.fset), dbUpdateChan, scanChan)
  692. select {
  693. case <-dbUpdateChan: // empty the channel for later
  694. case toScan := <-scanChan:
  695. t.Fatal("Unexpected receive on scanChan:", toScan)
  696. }
  697. info, err := f.mtimefs.Lstat("foo/bar")
  698. if err != nil {
  699. t.Fatal("Unexpected error (dir):", err)
  700. }
  701. if info.Owner() != expOwner || info.Group() != expGroup {
  702. t.Fatalf("Expected dir owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  703. }
  704. // Have the folder create a file, verify it's the correct owner/group.
  705. // File is zero sized to avoid having to handle copies/pulls.
  706. file := protocol.FileInfo{
  707. Name: "foo/bar/baz",
  708. Type: protocol.FileInfoTypeFile,
  709. Permissions: 0644,
  710. }
  711. // Wire some stuff. The flow here is handleFile() -[copierChan]->
  712. // copierRoutine() -[finisherChan]-> finisherRoutine() -[dbUpdateChan]->
  713. // back to us and we're done. The copier routine doesn't do anything,
  714. // but it's the way data is passed around. When the database update
  715. // comes the finisher is done.
  716. snap := fsetSnapshot(t, f.fset)
  717. finisherChan := make(chan *sharedPullerState)
  718. copierChan, copyWg := startCopier(f, nil, finisherChan)
  719. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, nil)
  720. defer func() {
  721. close(copierChan)
  722. copyWg.Wait()
  723. close(finisherChan)
  724. }()
  725. f.handleFile(file, snap, copierChan)
  726. <-dbUpdateChan
  727. info, err = f.mtimefs.Lstat("foo/bar/baz")
  728. if err != nil {
  729. t.Fatal("Unexpected error (file):", err)
  730. }
  731. if info.Owner() != expOwner || info.Group() != expGroup {
  732. t.Fatalf("Expected file owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  733. }
  734. // Have the folder create a symlink. Verify it accordingly.
  735. symlink := protocol.FileInfo{
  736. Name: "foo/bar/sym",
  737. Type: protocol.FileInfoTypeSymlink,
  738. Permissions: 0644,
  739. SymlinkTarget: "over the rainbow",
  740. }
  741. f.handleSymlink(symlink, snap, dbUpdateChan, scanChan)
  742. select {
  743. case <-dbUpdateChan:
  744. case toScan := <-scanChan:
  745. t.Fatal("Unexpected receive on scanChan:", toScan)
  746. }
  747. info, err = f.mtimefs.Lstat("foo/bar/sym")
  748. if err != nil {
  749. t.Fatal("Unexpected error (file):", err)
  750. }
  751. if info.Owner() != expOwner || info.Group() != expGroup {
  752. t.Fatalf("Expected symlink owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  753. }
  754. }
  755. // TestSRConflictReplaceFileByDir checks that a conflict is created when an existing file
  756. // is replaced with a directory and versions are conflicting
  757. func TestSRConflictReplaceFileByDir(t *testing.T) {
  758. m, f, wcfgCancel := setupSendReceiveFolder(t)
  759. defer cleanupSRFolder(f, m, wcfgCancel)
  760. ffs := f.Filesystem()
  761. name := "foo"
  762. // create local file
  763. file := createEmptyFileInfo(t, name, ffs)
  764. file.Version = protocol.Vector{}.Update(myID.Short())
  765. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  766. // Simulate remote creating a dir with the same name
  767. file.Type = protocol.FileInfoTypeDirectory
  768. rem := device1.Short()
  769. file.Version = protocol.Vector{}.Update(rem)
  770. file.ModifiedBy = rem
  771. dbUpdateChan := make(chan dbUpdateJob, 1)
  772. scanChan := make(chan string, 1)
  773. f.handleDir(file, fsetSnapshot(t, f.fset), dbUpdateChan, scanChan)
  774. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  775. t.Fatal("Expected one conflict, got", len(confls))
  776. } else if scan := <-scanChan; confls[0] != scan {
  777. t.Fatal("Expected request to scan", confls[0], "got", scan)
  778. }
  779. }
  780. // TestSRConflictReplaceFileByLink checks that a conflict is created when an existing file
  781. // is replaced with a link and versions are conflicting
  782. func TestSRConflictReplaceFileByLink(t *testing.T) {
  783. m, f, wcfgCancel := setupSendReceiveFolder(t)
  784. defer cleanupSRFolder(f, m, wcfgCancel)
  785. ffs := f.Filesystem()
  786. name := "foo"
  787. // create local file
  788. file := createEmptyFileInfo(t, name, ffs)
  789. file.Version = protocol.Vector{}.Update(myID.Short())
  790. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  791. // Simulate remote creating a symlink with the same name
  792. file.Type = protocol.FileInfoTypeSymlink
  793. file.SymlinkTarget = "bar"
  794. rem := device1.Short()
  795. file.Version = protocol.Vector{}.Update(rem)
  796. file.ModifiedBy = rem
  797. dbUpdateChan := make(chan dbUpdateJob, 1)
  798. scanChan := make(chan string, 1)
  799. f.handleSymlink(file, fsetSnapshot(t, f.fset), dbUpdateChan, scanChan)
  800. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  801. t.Fatal("Expected one conflict, got", len(confls))
  802. } else if scan := <-scanChan; confls[0] != scan {
  803. t.Fatal("Expected request to scan", confls[0], "got", scan)
  804. }
  805. }
  806. // TestDeleteBehindSymlink checks that we don't delete or schedule a scan
  807. // when trying to delete a file behind a symlink.
  808. func TestDeleteBehindSymlink(t *testing.T) {
  809. m, f, wcfgCancel := setupSendReceiveFolder(t)
  810. defer cleanupSRFolder(f, m, wcfgCancel)
  811. ffs := f.Filesystem()
  812. destDir := createTmpDir()
  813. defer os.RemoveAll(destDir)
  814. destFs := fs.NewFilesystem(fs.FilesystemTypeBasic, destDir)
  815. link := "link"
  816. file := filepath.Join(link, "file")
  817. must(t, ffs.MkdirAll(link, 0755))
  818. fi := createEmptyFileInfo(t, file, ffs)
  819. f.updateLocalsFromScanning([]protocol.FileInfo{fi})
  820. must(t, osutil.RenameOrCopy(fs.CopyRangeMethodStandard, ffs, destFs, file, "file"))
  821. must(t, ffs.RemoveAll(link))
  822. if err := fs.DebugSymlinkForTestsOnly(destFs, ffs, "", link); err != nil {
  823. if runtime.GOOS == "windows" {
  824. // Probably we require permissions we don't have.
  825. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  826. } else {
  827. t.Fatal(err)
  828. }
  829. }
  830. fi.Deleted = true
  831. fi.Version = fi.Version.Update(device1.Short())
  832. scanChan := make(chan string, 1)
  833. dbUpdateChan := make(chan dbUpdateJob, 1)
  834. f.deleteFile(fi, fsetSnapshot(t, f.fset), dbUpdateChan, scanChan)
  835. select {
  836. case f := <-scanChan:
  837. t.Fatalf("Received %v on scanChan", f)
  838. case u := <-dbUpdateChan:
  839. if u.jobType != dbUpdateDeleteFile {
  840. t.Errorf("Expected jobType %v, got %v", dbUpdateDeleteFile, u.jobType)
  841. }
  842. if u.file.Name != fi.Name {
  843. t.Errorf("Expected update for %v, got %v", fi.Name, u.file.Name)
  844. }
  845. default:
  846. t.Fatalf("No db update received")
  847. }
  848. if _, err := destFs.Stat("file"); err != nil {
  849. t.Errorf("Expected no error when stating file behind symlink, got %v", err)
  850. }
  851. }
  852. // Reproduces https://github.com/syncthing/syncthing/issues/6559
  853. func TestPullCtxCancel(t *testing.T) {
  854. m, f, wcfgCancel := setupSendReceiveFolder(t)
  855. defer cleanupSRFolder(f, m, wcfgCancel)
  856. pullChan := make(chan pullBlockState)
  857. finisherChan := make(chan *sharedPullerState)
  858. var cancel context.CancelFunc
  859. f.ctx, cancel = context.WithCancel(context.Background())
  860. go f.pullerRoutine(fsetSnapshot(t, f.fset), pullChan, finisherChan)
  861. defer close(pullChan)
  862. emptyState := func() pullBlockState {
  863. return pullBlockState{
  864. sharedPullerState: newSharedPullerState(protocol.FileInfo{}, nil, f.folderID, "", nil, nil, false, false, protocol.FileInfo{}, false, false),
  865. block: protocol.BlockInfo{},
  866. }
  867. }
  868. cancel()
  869. done := make(chan struct{})
  870. defer close(done)
  871. for i := 0; i < 2; i++ {
  872. go func() {
  873. select {
  874. case pullChan <- emptyState():
  875. case <-done:
  876. }
  877. }()
  878. select {
  879. case s := <-finisherChan:
  880. if s.failed() == nil {
  881. t.Errorf("state %v not failed", i)
  882. }
  883. case <-time.After(5 * time.Second):
  884. t.Fatalf("timed out before receiving state %v on finisherChan", i)
  885. }
  886. }
  887. }
  888. func TestPullDeleteUnscannedDir(t *testing.T) {
  889. m, f, wcfgCancel := setupSendReceiveFolder(t)
  890. defer cleanupSRFolder(f, m, wcfgCancel)
  891. ffs := f.Filesystem()
  892. dir := "foobar"
  893. must(t, ffs.MkdirAll(dir, 0777))
  894. fi := protocol.FileInfo{
  895. Name: dir,
  896. }
  897. scanChan := make(chan string, 1)
  898. dbUpdateChan := make(chan dbUpdateJob, 1)
  899. f.deleteDir(fi, fsetSnapshot(t, f.fset), dbUpdateChan, scanChan)
  900. if _, err := ffs.Stat(dir); fs.IsNotExist(err) {
  901. t.Error("directory has been deleted")
  902. }
  903. select {
  904. case toScan := <-scanChan:
  905. if toScan != dir {
  906. t.Errorf("expected %v to be scanned, got %v", dir, toScan)
  907. }
  908. default:
  909. t.Error("nothing was scheduled for scanning")
  910. }
  911. }
  912. func TestPullCaseOnlyPerformFinish(t *testing.T) {
  913. m, f, wcfgCancel := setupSendReceiveFolder(t)
  914. defer cleanupSRFolder(f, m, wcfgCancel)
  915. ffs := f.Filesystem()
  916. name := "foo"
  917. contents := []byte("contents")
  918. writeFile(t, ffs, name, contents)
  919. must(t, f.scanSubdirs(nil))
  920. var cur protocol.FileInfo
  921. hasCur := false
  922. snap := dbSnapshot(t, m, f.ID)
  923. defer snap.Release()
  924. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileIntf) bool {
  925. if hasCur {
  926. t.Fatal("got more than one file")
  927. }
  928. cur = i.(protocol.FileInfo)
  929. hasCur = true
  930. return true
  931. })
  932. if !hasCur {
  933. t.Fatal("file is missing")
  934. }
  935. remote := *(&cur)
  936. remote.Version = protocol.Vector{}.Update(device1.Short())
  937. remote.Name = strings.ToUpper(cur.Name)
  938. temp := fs.TempName(remote.Name)
  939. writeFile(t, ffs, temp, contents)
  940. scanChan := make(chan string, 1)
  941. dbUpdateChan := make(chan dbUpdateJob, 1)
  942. err := f.performFinish(remote, cur, hasCur, temp, snap, dbUpdateChan, scanChan)
  943. select {
  944. case <-dbUpdateChan: // boring case sensitive filesystem
  945. return
  946. case <-scanChan:
  947. t.Error("no need to scan anything here")
  948. default:
  949. }
  950. var caseErr *fs.ErrCaseConflict
  951. if !errors.As(err, &caseErr) {
  952. t.Error("Expected case conflict error, got", err)
  953. }
  954. }
  955. func TestPullCaseOnlyDir(t *testing.T) {
  956. testPullCaseOnlyDirOrSymlink(t, true)
  957. }
  958. func TestPullCaseOnlySymlink(t *testing.T) {
  959. if runtime.GOOS == "windows" {
  960. t.Skip("symlinks not supported on windows")
  961. }
  962. testPullCaseOnlyDirOrSymlink(t, false)
  963. }
  964. func testPullCaseOnlyDirOrSymlink(t *testing.T, dir bool) {
  965. m, f, wcfgCancel := setupSendReceiveFolder(t)
  966. defer cleanupSRFolder(f, m, wcfgCancel)
  967. ffs := f.Filesystem()
  968. name := "foo"
  969. if dir {
  970. must(t, ffs.Mkdir(name, 0777))
  971. } else {
  972. must(t, ffs.CreateSymlink("target", name))
  973. }
  974. must(t, f.scanSubdirs(nil))
  975. var cur protocol.FileInfo
  976. hasCur := false
  977. snap := dbSnapshot(t, m, f.ID)
  978. defer snap.Release()
  979. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileIntf) bool {
  980. if hasCur {
  981. t.Fatal("got more than one file")
  982. }
  983. cur = i.(protocol.FileInfo)
  984. hasCur = true
  985. return true
  986. })
  987. if !hasCur {
  988. t.Fatal("file is missing")
  989. }
  990. scanChan := make(chan string, 1)
  991. dbUpdateChan := make(chan dbUpdateJob, 1)
  992. remote := *(&cur)
  993. remote.Version = protocol.Vector{}.Update(device1.Short())
  994. remote.Name = strings.ToUpper(cur.Name)
  995. if dir {
  996. f.handleDir(remote, snap, dbUpdateChan, scanChan)
  997. } else {
  998. f.handleSymlink(remote, snap, dbUpdateChan, scanChan)
  999. }
  1000. select {
  1001. case <-dbUpdateChan: // boring case sensitive filesystem
  1002. return
  1003. case <-scanChan:
  1004. t.Error("no need to scan anything here")
  1005. default:
  1006. }
  1007. if errStr, ok := f.tempPullErrors[remote.Name]; !ok {
  1008. t.Error("missing error for", remote.Name)
  1009. } else if !strings.Contains(errStr, "uses different upper or lowercase") {
  1010. t.Error("unexpected error", errStr, "for", remote.Name)
  1011. }
  1012. }
  1013. func TestPullTempFileCaseConflict(t *testing.T) {
  1014. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1015. defer cleanupSRFolder(f, m, wcfgCancel)
  1016. copyChan := make(chan copyBlocksState, 1)
  1017. file := protocol.FileInfo{Name: "foo"}
  1018. confl := "Foo"
  1019. tempNameConfl := fs.TempName(confl)
  1020. if fd, err := f.mtimefs.Create(tempNameConfl); err != nil {
  1021. t.Fatal(err)
  1022. } else {
  1023. if _, err := fd.Write([]byte("data")); err != nil {
  1024. t.Fatal(err)
  1025. }
  1026. fd.Close()
  1027. }
  1028. f.handleFile(file, fsetSnapshot(t, f.fset), copyChan)
  1029. cs := <-copyChan
  1030. if _, err := cs.tempFile(); err != nil {
  1031. t.Error(err)
  1032. }
  1033. }
  1034. func TestPullCaseOnlyRename(t *testing.T) {
  1035. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1036. defer cleanupSRFolder(f, m, wcfgCancel)
  1037. // tempNameConfl := fs.TempName(confl)
  1038. name := "foo"
  1039. if fd, err := f.mtimefs.Create(name); err != nil {
  1040. t.Fatal(err)
  1041. } else {
  1042. if _, err := fd.Write([]byte("data")); err != nil {
  1043. t.Fatal(err)
  1044. }
  1045. fd.Close()
  1046. }
  1047. must(t, f.scanSubdirs(nil))
  1048. cur, ok := m.testCurrentFolderFile(f.ID, name)
  1049. if !ok {
  1050. t.Fatal("file missing")
  1051. }
  1052. deleted := cur
  1053. deleted.SetDeleted(myID.Short())
  1054. confl := cur
  1055. confl.Name = "Foo"
  1056. confl.Version = confl.Version.Update(device1.Short())
  1057. dbUpdateChan := make(chan dbUpdateJob, 2)
  1058. scanChan := make(chan string, 2)
  1059. snap := fsetSnapshot(t, f.fset)
  1060. defer snap.Release()
  1061. if err := f.renameFile(cur, deleted, confl, snap, dbUpdateChan, scanChan); err != nil {
  1062. t.Error(err)
  1063. }
  1064. }
  1065. func TestPullSymlinkOverExistingWindows(t *testing.T) {
  1066. if runtime.GOOS != "windows" {
  1067. t.Skip()
  1068. }
  1069. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1070. defer cleanupSRFolder(f, m, wcfgCancel)
  1071. addFakeConn(m, device1, f.ID)
  1072. name := "foo"
  1073. if fd, err := f.mtimefs.Create(name); err != nil {
  1074. t.Fatal(err)
  1075. } else {
  1076. if _, err := fd.Write([]byte("data")); err != nil {
  1077. t.Fatal(err)
  1078. }
  1079. fd.Close()
  1080. }
  1081. must(t, f.scanSubdirs(nil))
  1082. file, ok := m.testCurrentFolderFile(f.ID, name)
  1083. if !ok {
  1084. t.Fatal("file missing")
  1085. }
  1086. must(t, m.Index(device1, f.ID, []protocol.FileInfo{{Name: name, Type: protocol.FileInfoTypeSymlink, Version: file.Version.Update(device1.Short())}}))
  1087. scanChan := make(chan string)
  1088. changed, err := f.pullerIteration(scanChan)
  1089. must(t, err)
  1090. if changed != 1 {
  1091. t.Error("Expected one change in pull, got", changed)
  1092. }
  1093. if file, ok := m.testCurrentFolderFile(f.ID, name); !ok {
  1094. t.Error("symlink entry missing")
  1095. } else if !file.IsUnsupported() {
  1096. t.Error("symlink entry isn't marked as unsupported")
  1097. }
  1098. if _, err := f.mtimefs.Lstat(name); err == nil {
  1099. t.Error("old file still exists on disk")
  1100. } else if !fs.IsNotExist(err) {
  1101. t.Error(err)
  1102. }
  1103. }
  1104. func TestPullDeleteCaseConflict(t *testing.T) {
  1105. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1106. defer cleanupSRFolder(f, m, wcfgCancel)
  1107. name := "foo"
  1108. fi := protocol.FileInfo{Name: "Foo"}
  1109. dbUpdateChan := make(chan dbUpdateJob, 1)
  1110. scanChan := make(chan string)
  1111. if fd, err := f.mtimefs.Create(name); err != nil {
  1112. t.Fatal(err)
  1113. } else {
  1114. if _, err := fd.Write([]byte("data")); err != nil {
  1115. t.Fatal(err)
  1116. }
  1117. fd.Close()
  1118. }
  1119. f.deleteFileWithCurrent(fi, protocol.FileInfo{}, false, dbUpdateChan, scanChan)
  1120. select {
  1121. case <-dbUpdateChan:
  1122. default:
  1123. t.Error("Missing db update for file")
  1124. }
  1125. snap := fsetSnapshot(t, f.fset)
  1126. defer snap.Release()
  1127. f.deleteDir(fi, snap, dbUpdateChan, scanChan)
  1128. select {
  1129. case <-dbUpdateChan:
  1130. default:
  1131. t.Error("Missing db update for dir")
  1132. }
  1133. }
  1134. func TestPullDeleteIgnoreChildDir(t *testing.T) {
  1135. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1136. defer cleanupSRFolder(f, m, wcfgCancel)
  1137. parent := "parent"
  1138. del := "ignored"
  1139. child := "keep"
  1140. matcher := ignore.New(f.mtimefs)
  1141. must(t, matcher.Parse(bytes.NewBufferString(fmt.Sprintf(`
  1142. !%v
  1143. (?d)%v
  1144. `, child, del)), ""))
  1145. f.ignores = matcher
  1146. must(t, f.mtimefs.Mkdir(parent, 0777))
  1147. must(t, f.mtimefs.Mkdir(filepath.Join(parent, del), 0777))
  1148. must(t, f.mtimefs.Mkdir(filepath.Join(parent, del, child), 0777))
  1149. scanChan := make(chan string, 2)
  1150. err := f.deleteDirOnDisk(parent, fsetSnapshot(t, f.fset), scanChan)
  1151. if err == nil {
  1152. t.Error("no error")
  1153. }
  1154. }
  1155. func cleanupSharedPullerState(s *sharedPullerState) {
  1156. s.mut.Lock()
  1157. defer s.mut.Unlock()
  1158. if s.writer == nil {
  1159. return
  1160. }
  1161. s.writer.mut.Lock()
  1162. s.writer.fd.Close()
  1163. s.writer.mut.Unlock()
  1164. }
  1165. func startCopier(f *sendReceiveFolder, pullChan chan<- pullBlockState, finisherChan chan<- *sharedPullerState) (chan copyBlocksState, sync.WaitGroup) {
  1166. copyChan := make(chan copyBlocksState)
  1167. wg := sync.NewWaitGroup()
  1168. wg.Add(1)
  1169. go func() {
  1170. f.copierRoutine(copyChan, pullChan, finisherChan)
  1171. wg.Done()
  1172. }()
  1173. return copyChan, wg
  1174. }