folder_sendrecv_test.go 39 KB

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