folder_sendrecv_test.go 40 KB

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