folder_sendrecv_test.go 39 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. "errors"
  11. "fmt"
  12. "io"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "testing"
  18. "time"
  19. "github.com/syncthing/syncthing/lib/build"
  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/protocol"
  25. "github.com/syncthing/syncthing/lib/rand"
  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. func prepareTmpFile(to fs.Filesystem) (string, error) {
  41. tmpName := fs.TempName("file")
  42. in, err := os.Open("testdata/tmpfile")
  43. if err != nil {
  44. return "", err
  45. }
  46. defer in.Close()
  47. out, err := to.Create(tmpName)
  48. if err != nil {
  49. return "", err
  50. }
  51. defer out.Close()
  52. if _, err = io.Copy(out, in); err != nil {
  53. return "", err
  54. }
  55. future := time.Now().Add(time.Hour)
  56. if err := to.Chtimes(tmpName, future, future); err != nil {
  57. return "", err
  58. }
  59. return tmpName, nil
  60. }
  61. var folders = []string{"default"}
  62. var diffTestData = []struct {
  63. a string
  64. b string
  65. s int
  66. d []protocol.BlockInfo
  67. }{
  68. {"contents", "contents", 1024, []protocol.BlockInfo{}},
  69. {"", "", 1024, []protocol.BlockInfo{}},
  70. {"contents", "contents", 3, []protocol.BlockInfo{}},
  71. {"contents", "cantents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}}},
  72. {"contents", "contants", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}}},
  73. {"contents", "cantants", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}}},
  74. {"contents", "", 3, []protocol.BlockInfo{{Offset: 0, Size: 0}}},
  75. {"", "contents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  76. {"con", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  77. {"contents", "con", 3, nil},
  78. {"contents", "cont", 3, []protocol.BlockInfo{{Offset: 3, Size: 1}}},
  79. {"cont", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  80. }
  81. func setupFile(filename string, blockNumbers []int) protocol.FileInfo {
  82. // Create existing file
  83. existingBlocks := make([]protocol.BlockInfo, len(blockNumbers))
  84. for i := range blockNumbers {
  85. existingBlocks[i] = blocks[blockNumbers[i]]
  86. }
  87. return protocol.FileInfo{
  88. Name: filename,
  89. Blocks: existingBlocks,
  90. }
  91. }
  92. func createEmptyFileInfo(t *testing.T, name string, fs fs.Filesystem) protocol.FileInfo {
  93. t.Helper()
  94. writeFile(t, fs, name, nil)
  95. fi, err := fs.Stat(name)
  96. must(t, err)
  97. file, err := scanner.CreateFileInfo(fi, name, fs, false, false, config.XattrFilter{})
  98. must(t, err)
  99. return file
  100. }
  101. // Sets up a folder and model, but makes sure the services aren't actually running.
  102. func setupSendReceiveFolder(t testing.TB, files ...protocol.FileInfo) (*testModel, *sendReceiveFolder, context.CancelFunc) {
  103. w, fcfg, wCancel := newDefaultCfgWrapper()
  104. // Initialise model and stop immediately.
  105. model := setupModel(t, w)
  106. model.cancel()
  107. <-model.stopped
  108. r, _ := model.folderRunners.Get(fcfg.ID)
  109. f := r.(*sendReceiveFolder)
  110. f.tempPullErrors = make(map[string]string)
  111. f.ctx = context.Background()
  112. // Update index
  113. if files != nil {
  114. f.updateLocalsFromScanning(files)
  115. }
  116. return model, f, wCancel
  117. }
  118. // Layout of the files: (indexes from the above array)
  119. // 12345678 - Required file
  120. // 02005008 - Existing file (currently in the index)
  121. // 02340070 - Temp file on the disk
  122. func TestHandleFile(t *testing.T) {
  123. // After the diff between required and existing we should:
  124. // Copy: 2, 5, 8
  125. // Pull: 1, 3, 4, 6, 7
  126. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  127. existingFile := setupFile("filex", existingBlocks)
  128. requiredFile := existingFile
  129. requiredFile.Blocks = blocks[1:]
  130. _, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  131. defer wcfgCancel()
  132. copyChan := make(chan copyBlocksState, 1)
  133. f.handleFile(requiredFile, fsetSnapshot(t, f.fset), copyChan)
  134. // Receive the results
  135. toCopy := <-copyChan
  136. if len(toCopy.blocks) != 8 {
  137. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  138. }
  139. for _, block := range blocks[1:] {
  140. found := false
  141. for _, toCopyBlock := range toCopy.blocks {
  142. if bytes.Equal(toCopyBlock.Hash, block.Hash) {
  143. found = true
  144. break
  145. }
  146. }
  147. if !found {
  148. t.Errorf("Did not find block %s", block.String())
  149. }
  150. }
  151. }
  152. func TestHandleFileWithTemp(t *testing.T) {
  153. // After diff between required and existing we should:
  154. // Copy: 2, 5, 8
  155. // Pull: 1, 3, 4, 6, 7
  156. // After dropping out blocks already on the temp file we should:
  157. // Copy: 5, 8
  158. // Pull: 1, 6
  159. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  160. existingFile := setupFile("file", existingBlocks)
  161. requiredFile := existingFile
  162. requiredFile.Blocks = blocks[1:]
  163. _, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  164. defer wcfgCancel()
  165. if _, err := prepareTmpFile(f.Filesystem(nil)); err != nil {
  166. t.Fatal(err)
  167. }
  168. copyChan := make(chan copyBlocksState, 1)
  169. f.handleFile(requiredFile, fsetSnapshot(t, f.fset), copyChan)
  170. // Receive the results
  171. toCopy := <-copyChan
  172. if len(toCopy.blocks) != 4 {
  173. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  174. }
  175. for _, idx := range []int{1, 5, 6, 8} {
  176. found := false
  177. block := blocks[idx]
  178. for _, toCopyBlock := range toCopy.blocks {
  179. if bytes.Equal(toCopyBlock.Hash, block.Hash) {
  180. found = true
  181. break
  182. }
  183. }
  184. if !found {
  185. t.Errorf("Did not find block %s", block.String())
  186. }
  187. }
  188. }
  189. func TestCopierFinder(t *testing.T) {
  190. // After diff between required and existing we should:
  191. // Copy: 1, 2, 3, 4, 6, 7, 8
  192. // Since there is no existing file, nor a temp file
  193. // After dropping out blocks found locally:
  194. // Pull: 1, 5, 6, 8
  195. tempFile := fs.TempName("file2")
  196. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  197. existingFile := setupFile(fs.TempName("file"), existingBlocks)
  198. existingFile.Size = 1
  199. requiredFile := existingFile
  200. requiredFile.Blocks = blocks[1:]
  201. requiredFile.Name = "file2"
  202. _, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  203. defer wcfgCancel()
  204. if _, err := prepareTmpFile(f.Filesystem(nil)); err != nil {
  205. t.Fatal(err)
  206. }
  207. copyChan := make(chan copyBlocksState)
  208. pullChan := make(chan pullBlockState, 4)
  209. finisherChan := make(chan *sharedPullerState, 1)
  210. // Run a single fetcher routine
  211. go f.copierRoutine(copyChan, pullChan, finisherChan)
  212. defer close(copyChan)
  213. f.handleFile(requiredFile, fsetSnapshot(t, f.fset), copyChan)
  214. timeout := time.After(10 * time.Second)
  215. pulls := make([]pullBlockState, 4)
  216. for i := 0; i < 4; i++ {
  217. select {
  218. case pulls[i] = <-pullChan:
  219. case <-timeout:
  220. t.Fatalf("Timed out before receiving all 4 states on pullChan (already got %v)", i)
  221. }
  222. }
  223. var finish *sharedPullerState
  224. select {
  225. case finish = <-finisherChan:
  226. case <-timeout:
  227. t.Fatal("Timed out before receiving 4 states on pullChan")
  228. }
  229. defer cleanupSharedPullerState(finish)
  230. select {
  231. case <-pullChan:
  232. t.Fatal("Pull channel has data to be read")
  233. case <-finisherChan:
  234. t.Fatal("Finisher channel has data to be read")
  235. default:
  236. }
  237. // Verify that the right blocks went into the pull list.
  238. // They are pulled in random order.
  239. for _, idx := range []int{1, 5, 6, 8} {
  240. found := false
  241. block := blocks[idx]
  242. for _, pulledBlock := range pulls {
  243. if bytes.Equal(pulledBlock.block.Hash, block.Hash) {
  244. found = true
  245. break
  246. }
  247. }
  248. if !found {
  249. t.Errorf("Did not find block %s", block.String())
  250. }
  251. if !bytes.Equal(finish.file.Blocks[idx-1].Hash, blocks[idx].Hash) {
  252. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  253. }
  254. }
  255. // Verify that the fetched blocks have actually been written to the temp file
  256. blks, err := scanner.HashFile(context.TODO(), f.ID, f.Filesystem(nil), tempFile, protocol.MinBlockSize, nil, false)
  257. if err != nil {
  258. t.Log(err)
  259. }
  260. for _, eq := range []int{2, 3, 4, 7} {
  261. if !bytes.Equal(blks[eq-1].Hash, blocks[eq].Hash) {
  262. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  263. }
  264. }
  265. }
  266. func TestWeakHash(t *testing.T) {
  267. // Setup the model/pull environment
  268. _, fo, wcfgCancel := setupSendReceiveFolder(t)
  269. defer wcfgCancel()
  270. ffs := fo.Filesystem(nil)
  271. tempFile := fs.TempName("weakhash")
  272. var shift int64 = 10
  273. var size int64 = 1 << 20
  274. expectBlocks := int(size / protocol.MinBlockSize)
  275. expectPulls := int(shift / protocol.MinBlockSize)
  276. if shift > 0 {
  277. expectPulls++
  278. }
  279. f, err := ffs.Create("weakhash")
  280. must(t, err)
  281. defer f.Close()
  282. _, err = io.CopyN(f, rand.Reader, size)
  283. if err != nil {
  284. t.Error(err)
  285. }
  286. info, err := f.Stat()
  287. if err != nil {
  288. t.Error(err)
  289. }
  290. // Create two files, second file has `shifted` bytes random prefix, yet
  291. // both are of the same length, for example:
  292. // File 1: abcdefgh
  293. // File 2: xyabcdef
  294. f.Seek(0, io.SeekStart)
  295. existing, err := scanner.Blocks(context.TODO(), f, protocol.MinBlockSize, size, nil, true)
  296. if err != nil {
  297. t.Error(err)
  298. }
  299. f.Seek(0, io.SeekStart)
  300. remainder := io.LimitReader(f, size-shift)
  301. prefix := io.LimitReader(rand.Reader, shift)
  302. nf := io.MultiReader(prefix, remainder)
  303. desired, err := scanner.Blocks(context.TODO(), nf, protocol.MinBlockSize, size, nil, true)
  304. if err != nil {
  305. t.Error(err)
  306. }
  307. existingFile := protocol.FileInfo{
  308. Name: "weakhash",
  309. Blocks: existing,
  310. Size: size,
  311. ModifiedS: info.ModTime().Unix(),
  312. ModifiedNs: info.ModTime().Nanosecond(),
  313. }
  314. desiredFile := protocol.FileInfo{
  315. Name: "weakhash",
  316. Size: size,
  317. Blocks: desired,
  318. ModifiedS: info.ModTime().Unix() + 1,
  319. }
  320. fo.updateLocalsFromScanning([]protocol.FileInfo{existingFile})
  321. copyChan := make(chan copyBlocksState)
  322. pullChan := make(chan pullBlockState, expectBlocks)
  323. finisherChan := make(chan *sharedPullerState, 1)
  324. // Run a single fetcher routine
  325. go fo.copierRoutine(copyChan, pullChan, finisherChan)
  326. defer close(copyChan)
  327. // Test 1 - no weak hashing, file gets fully repulled (`expectBlocks` pulls).
  328. fo.WeakHashThresholdPct = 101
  329. fo.handleFile(desiredFile, fsetSnapshot(t, fo.fset), copyChan)
  330. var pulls []pullBlockState
  331. timeout := time.After(10 * time.Second)
  332. for len(pulls) < expectBlocks {
  333. select {
  334. case pull := <-pullChan:
  335. pulls = append(pulls, pull)
  336. case <-timeout:
  337. t.Fatalf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  338. }
  339. }
  340. finish := <-finisherChan
  341. select {
  342. case <-pullChan:
  343. t.Fatal("Pull channel has data to be read")
  344. case <-finisherChan:
  345. t.Fatal("Finisher channel has data to be read")
  346. default:
  347. }
  348. cleanupSharedPullerState(finish)
  349. if err := ffs.Remove(tempFile); err != nil {
  350. t.Fatal(err)
  351. }
  352. // Test 2 - using weak hash, expectPulls blocks pulled.
  353. fo.WeakHashThresholdPct = -1
  354. fo.handleFile(desiredFile, fsetSnapshot(t, fo.fset), copyChan)
  355. pulls = pulls[:0]
  356. for len(pulls) < expectPulls {
  357. select {
  358. case pull := <-pullChan:
  359. pulls = append(pulls, pull)
  360. case <-time.After(10 * time.Second):
  361. t.Fatalf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  362. }
  363. }
  364. finish = <-finisherChan
  365. cleanupSharedPullerState(finish)
  366. expectShifted := expectBlocks - expectPulls
  367. if finish.copyOriginShifted != expectShifted {
  368. t.Errorf("did not copy %d shifted", expectShifted)
  369. }
  370. }
  371. // Test that updating a file removes its old blocks from the blockmap
  372. func TestCopierCleanup(t *testing.T) {
  373. iterFn := func(folder, file string, index int32) bool {
  374. return true
  375. }
  376. // Create a file
  377. file := setupFile("test", []int{0})
  378. file.Size = 1
  379. m, f, wcfgCancel := setupSendReceiveFolder(t, file)
  380. defer wcfgCancel()
  381. file.Blocks = []protocol.BlockInfo{blocks[1]}
  382. file.Version = file.Version.Update(myID.Short())
  383. // Update index (removing old blocks)
  384. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  385. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  386. t.Error("Unexpected block found")
  387. }
  388. if !m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  389. t.Error("Expected block not found")
  390. }
  391. file.Blocks = []protocol.BlockInfo{blocks[0]}
  392. file.Version = file.Version.Update(myID.Short())
  393. // Update index (removing old blocks)
  394. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  395. if !m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  396. t.Error("Unexpected block found")
  397. }
  398. if m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  399. t.Error("Expected block not found")
  400. }
  401. }
  402. func TestDeregisterOnFailInCopy(t *testing.T) {
  403. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  404. m, f, wcfgCancel := setupSendReceiveFolder(t)
  405. defer wcfgCancel()
  406. // Set up our evet subscription early
  407. s := m.evLogger.Subscribe(events.ItemFinished)
  408. // queue.Done should be called by the finisher routine
  409. f.queue.Push("filex", 0, time.Time{})
  410. f.queue.Pop()
  411. if f.queue.lenProgress() != 1 {
  412. t.Fatal("Expected file in progress")
  413. }
  414. pullChan := make(chan pullBlockState)
  415. finisherBufferChan := make(chan *sharedPullerState, 1)
  416. finisherChan := make(chan *sharedPullerState)
  417. dbUpdateChan := make(chan dbUpdateJob, 1)
  418. snap := fsetSnapshot(t, f.fset)
  419. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  420. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, make(chan string))
  421. defer func() {
  422. close(copyChan)
  423. copyWg.Wait()
  424. close(pullChan)
  425. close(finisherBufferChan)
  426. close(finisherChan)
  427. }()
  428. f.handleFile(file, snap, copyChan)
  429. // Receive a block at puller, to indicate that at least a single copier
  430. // loop has been performed.
  431. var toPull pullBlockState
  432. select {
  433. case toPull = <-pullChan:
  434. case <-time.After(10 * time.Second):
  435. t.Fatal("timed out")
  436. }
  437. // Unblock copier
  438. go func() {
  439. for range pullChan {
  440. }
  441. }()
  442. // Close the file, causing errors on further access
  443. toPull.sharedPullerState.fail(os.ErrNotExist)
  444. select {
  445. case state := <-finisherBufferChan:
  446. // At this point the file should still be registered with both the job
  447. // queue, and the progress emitter. Verify this.
  448. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  449. t.Fatal("Could not find file")
  450. }
  451. // Pass the file down the real finisher, and give it time to consume
  452. finisherChan <- state
  453. t0 := time.Now()
  454. if ev, err := s.Poll(time.Minute); err != nil {
  455. t.Fatal("Got error waiting for ItemFinished event:", err)
  456. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  457. t.Fatal("Got ItemFinished event for wrong file:", n)
  458. }
  459. t.Log("event took", time.Since(t0))
  460. state.mut.Lock()
  461. stateWriter := state.writer
  462. state.mut.Unlock()
  463. if stateWriter != nil {
  464. t.Fatal("File not closed?")
  465. }
  466. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  467. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  468. }
  469. // Doing it again should have no effect
  470. finisherChan <- state
  471. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  472. t.Fatal("Expected timeout, not another event", err)
  473. }
  474. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  475. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  476. }
  477. case <-time.After(5 * time.Second):
  478. t.Fatal("Didn't get anything to the finisher")
  479. }
  480. }
  481. func TestDeregisterOnFailInPull(t *testing.T) {
  482. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  483. m, f, wcfgCancel := setupSendReceiveFolder(t)
  484. defer wcfgCancel()
  485. // Set up our evet subscription early
  486. s := m.evLogger.Subscribe(events.ItemFinished)
  487. // queue.Done should be called by the finisher routine
  488. f.queue.Push("filex", 0, time.Time{})
  489. f.queue.Pop()
  490. if f.queue.lenProgress() != 1 {
  491. t.Fatal("Expected file in progress")
  492. }
  493. pullChan := make(chan pullBlockState)
  494. finisherBufferChan := make(chan *sharedPullerState)
  495. finisherChan := make(chan *sharedPullerState)
  496. dbUpdateChan := make(chan dbUpdateJob, 1)
  497. snap := fsetSnapshot(t, f.fset)
  498. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  499. pullWg := sync.NewWaitGroup()
  500. pullWg.Add(1)
  501. go func() {
  502. f.pullerRoutine(snap, pullChan, finisherBufferChan)
  503. pullWg.Done()
  504. }()
  505. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, make(chan string))
  506. defer func() {
  507. // Unblock copier and puller
  508. go func() {
  509. for range finisherBufferChan {
  510. }
  511. }()
  512. close(copyChan)
  513. copyWg.Wait()
  514. close(pullChan)
  515. pullWg.Wait()
  516. close(finisherBufferChan)
  517. close(finisherChan)
  518. }()
  519. f.handleFile(file, snap, copyChan)
  520. // Receive at finisher, we should error out as puller has nowhere to pull
  521. // from.
  522. timeout = time.Second
  523. // Both the puller and copier may send to the finisherBufferChan.
  524. var state *sharedPullerState
  525. after := time.After(5 * time.Second)
  526. for {
  527. select {
  528. case state = <-finisherBufferChan:
  529. case <-after:
  530. t.Fatal("Didn't get failed state to the finisher")
  531. }
  532. if state.failed() != nil {
  533. break
  534. }
  535. }
  536. // At this point the file should still be registered with both the job
  537. // queue, and the progress emitter. Verify this.
  538. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  539. t.Fatal("Could not find file")
  540. }
  541. // Pass the file down the real finisher, and give it time to consume
  542. finisherChan <- state
  543. t0 := time.Now()
  544. if ev, err := s.Poll(time.Minute); err != nil {
  545. t.Fatal("Got error waiting for ItemFinished event:", err)
  546. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  547. t.Fatal("Got ItemFinished event for wrong file:", n)
  548. }
  549. t.Log("event took", time.Since(t0))
  550. state.mut.Lock()
  551. stateWriter := state.writer
  552. state.mut.Unlock()
  553. if stateWriter != nil {
  554. t.Fatal("File not closed?")
  555. }
  556. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  557. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  558. }
  559. // Doing it again should have no effect
  560. finisherChan <- state
  561. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  562. t.Fatal("Expected timeout, not another event", err)
  563. }
  564. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  565. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  566. }
  567. }
  568. func TestIssue3164(t *testing.T) {
  569. _, f, wcfgCancel := setupSendReceiveFolder(t)
  570. defer wcfgCancel()
  571. ffs := f.Filesystem(nil)
  572. ignDir := filepath.Join("issue3164", "oktodelete")
  573. subDir := filepath.Join(ignDir, "foobar")
  574. must(t, ffs.MkdirAll(subDir, 0o777))
  575. must(t, fs.WriteFile(ffs, filepath.Join(subDir, "file"), []byte("Hello"), 0o644))
  576. must(t, fs.WriteFile(ffs, filepath.Join(ignDir, "file"), []byte("Hello"), 0o644))
  577. file := protocol.FileInfo{
  578. Name: "issue3164",
  579. }
  580. must(t, f.scanSubdirs(nil))
  581. matcher := ignore.New(ffs)
  582. must(t, matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""))
  583. f.ignores = matcher
  584. dbUpdateChan := make(chan dbUpdateJob, 1)
  585. f.deleteDir(file, fsetSnapshot(t, f.fset), dbUpdateChan, make(chan string))
  586. if _, err := ffs.Stat("issue3164"); !fs.IsNotExist(err) {
  587. t.Fatal(err)
  588. }
  589. }
  590. func TestDiff(t *testing.T) {
  591. for i, test := range diffTestData {
  592. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  593. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  594. _, d := blockDiff(a, b)
  595. if len(d) != len(test.d) {
  596. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  597. } else {
  598. for j := range test.d {
  599. if d[j].Offset != test.d[j].Offset {
  600. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  601. }
  602. if d[j].Size != test.d[j].Size {
  603. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  604. }
  605. }
  606. }
  607. }
  608. }
  609. func BenchmarkDiff(b *testing.B) {
  610. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  611. for _, test := range diffTestData {
  612. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  613. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  614. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{a, b})
  615. }
  616. b.ReportAllocs()
  617. b.ResetTimer()
  618. for i := 0; i < b.N; i++ {
  619. for _, tc := range testCases {
  620. blockDiff(tc.a, tc.b)
  621. }
  622. }
  623. }
  624. func TestDiffEmpty(t *testing.T) {
  625. emptyCases := []struct {
  626. a []protocol.BlockInfo
  627. b []protocol.BlockInfo
  628. need int
  629. have int
  630. }{
  631. {nil, nil, 0, 0},
  632. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  633. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  634. }
  635. for _, emptyCase := range emptyCases {
  636. h, n := blockDiff(emptyCase.a, emptyCase.b)
  637. if len(h) != emptyCase.have {
  638. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  639. }
  640. if len(n) != emptyCase.need {
  641. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  642. }
  643. }
  644. }
  645. // TestDeleteIgnorePerms checks, that a file gets deleted when the IgnorePerms
  646. // option is true and the permissions do not match between the file on disk and
  647. // in the db.
  648. func TestDeleteIgnorePerms(t *testing.T) {
  649. _, f, wcfgCancel := setupSendReceiveFolder(t)
  650. defer wcfgCancel()
  651. ffs := f.Filesystem(nil)
  652. f.IgnorePerms = true
  653. name := "deleteIgnorePerms"
  654. file, err := ffs.Create(name)
  655. if err != nil {
  656. t.Error(err)
  657. }
  658. defer file.Close()
  659. stat, err := file.Stat()
  660. must(t, err)
  661. fi, err := scanner.CreateFileInfo(stat, name, ffs, false, false, config.XattrFilter{})
  662. must(t, err)
  663. ffs.Chmod(name, 0o600)
  664. if info, err := ffs.Stat(name); err == nil {
  665. fi.InodeChangeNs = info.InodeChangeTime().UnixNano()
  666. }
  667. scanChan := make(chan string, 1)
  668. err = f.checkToBeDeleted(fi, fi, true, scanChan)
  669. must(t, err)
  670. }
  671. func TestCopyOwner(t *testing.T) {
  672. // Verifies that owner and group are copied from the parent, for both
  673. // files and directories.
  674. if build.IsWindows {
  675. t.Skip("copying owner not supported on Windows")
  676. }
  677. const (
  678. expOwner = 1234
  679. expGroup = 5678
  680. )
  681. // Set up a folder with the CopyParentOwner bit and backed by a fake
  682. // filesystem.
  683. m, f, wcfgCancel := setupSendReceiveFolder(t)
  684. defer wcfgCancel()
  685. f.folder.FolderConfiguration = newFolderConfiguration(m.cfg, f.ID, f.Label, fs.FilesystemTypeFake, "/TestCopyOwner")
  686. f.folder.FolderConfiguration.CopyOwnershipFromParent = true
  687. f.fset = newFileSet(t, f.ID, m.db)
  688. f.mtimefs = f.Filesystem(f.fset)
  689. // Create a parent dir with a certain owner/group.
  690. f.mtimefs.Mkdir("foo", 0o755)
  691. f.mtimefs.Lchown("foo", strconv.Itoa(expOwner), strconv.Itoa(expGroup))
  692. dir := protocol.FileInfo{
  693. Name: "foo/bar",
  694. Type: protocol.FileInfoTypeDirectory,
  695. Permissions: 0o755,
  696. }
  697. // Have the folder create a subdirectory, verify that it's the correct
  698. // owner/group.
  699. dbUpdateChan := make(chan dbUpdateJob, 1)
  700. scanChan := make(chan string)
  701. defer close(dbUpdateChan)
  702. f.handleDir(dir, fsetSnapshot(t, f.fset), dbUpdateChan, scanChan)
  703. select {
  704. case <-dbUpdateChan: // empty the channel for later
  705. case toScan := <-scanChan:
  706. t.Fatal("Unexpected receive on scanChan:", toScan)
  707. }
  708. info, err := f.mtimefs.Lstat("foo/bar")
  709. if err != nil {
  710. t.Fatal("Unexpected error (dir):", err)
  711. }
  712. if info.Owner() != expOwner || info.Group() != expGroup {
  713. t.Fatalf("Expected dir owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  714. }
  715. // Have the folder create a file, verify it's the correct owner/group.
  716. // File is zero sized to avoid having to handle copies/pulls.
  717. file := protocol.FileInfo{
  718. Name: "foo/bar/baz",
  719. Type: protocol.FileInfoTypeFile,
  720. Permissions: 0o644,
  721. }
  722. // Wire some stuff. The flow here is handleFile() -[copierChan]->
  723. // copierRoutine() -[finisherChan]-> finisherRoutine() -[dbUpdateChan]->
  724. // back to us and we're done. The copier routine doesn't do anything,
  725. // but it's the way data is passed around. When the database update
  726. // comes the finisher is done.
  727. snap := fsetSnapshot(t, f.fset)
  728. finisherChan := make(chan *sharedPullerState)
  729. copierChan, copyWg := startCopier(f, nil, finisherChan)
  730. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, nil)
  731. defer func() {
  732. close(copierChan)
  733. copyWg.Wait()
  734. close(finisherChan)
  735. }()
  736. f.handleFile(file, snap, copierChan)
  737. <-dbUpdateChan
  738. info, err = f.mtimefs.Lstat("foo/bar/baz")
  739. if err != nil {
  740. t.Fatal("Unexpected error (file):", err)
  741. }
  742. if info.Owner() != expOwner || info.Group() != expGroup {
  743. t.Fatalf("Expected file owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  744. }
  745. // Have the folder create a symlink. Verify it accordingly.
  746. symlink := protocol.FileInfo{
  747. Name: "foo/bar/sym",
  748. Type: protocol.FileInfoTypeSymlink,
  749. Permissions: 0o644,
  750. SymlinkTarget: "over the rainbow",
  751. }
  752. f.handleSymlink(symlink, snap, dbUpdateChan, scanChan)
  753. select {
  754. case <-dbUpdateChan:
  755. case toScan := <-scanChan:
  756. t.Fatal("Unexpected receive on scanChan:", toScan)
  757. }
  758. info, err = f.mtimefs.Lstat("foo/bar/sym")
  759. if err != nil {
  760. t.Fatal("Unexpected error (file):", err)
  761. }
  762. if info.Owner() != expOwner || info.Group() != expGroup {
  763. t.Fatalf("Expected symlink owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  764. }
  765. }
  766. // TestSRConflictReplaceFileByDir checks that a conflict is created when an existing file
  767. // is replaced with a directory and versions are conflicting
  768. func TestSRConflictReplaceFileByDir(t *testing.T) {
  769. _, f, wcfgCancel := setupSendReceiveFolder(t)
  770. defer wcfgCancel()
  771. ffs := f.Filesystem(nil)
  772. name := "foo"
  773. // create local file
  774. file := createEmptyFileInfo(t, name, ffs)
  775. file.Version = protocol.Vector{}.Update(myID.Short())
  776. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  777. // Simulate remote creating a dir with the same name
  778. file.Type = protocol.FileInfoTypeDirectory
  779. rem := device1.Short()
  780. file.Version = protocol.Vector{}.Update(rem)
  781. file.ModifiedBy = rem
  782. dbUpdateChan := make(chan dbUpdateJob, 1)
  783. scanChan := make(chan string, 1)
  784. f.handleDir(file, fsetSnapshot(t, f.fset), dbUpdateChan, scanChan)
  785. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  786. t.Fatal("Expected one conflict, got", len(confls))
  787. } else if scan := <-scanChan; confls[0] != scan {
  788. t.Fatal("Expected request to scan", confls[0], "got", scan)
  789. }
  790. }
  791. // TestSRConflictReplaceFileByLink checks that a conflict is created when an existing file
  792. // is replaced with a link and versions are conflicting
  793. func TestSRConflictReplaceFileByLink(t *testing.T) {
  794. _, f, wcfgCancel := setupSendReceiveFolder(t)
  795. defer wcfgCancel()
  796. ffs := f.Filesystem(nil)
  797. name := "foo"
  798. // create local file
  799. file := createEmptyFileInfo(t, name, ffs)
  800. file.Version = protocol.Vector{}.Update(myID.Short())
  801. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  802. // Simulate remote creating a symlink with the same name
  803. file.Type = protocol.FileInfoTypeSymlink
  804. file.SymlinkTarget = "bar"
  805. rem := device1.Short()
  806. file.Version = protocol.Vector{}.Update(rem)
  807. file.ModifiedBy = rem
  808. dbUpdateChan := make(chan dbUpdateJob, 1)
  809. scanChan := make(chan string, 1)
  810. f.handleSymlink(file, fsetSnapshot(t, f.fset), dbUpdateChan, scanChan)
  811. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  812. t.Fatal("Expected one conflict, got", len(confls))
  813. } else if scan := <-scanChan; confls[0] != scan {
  814. t.Fatal("Expected request to scan", confls[0], "got", scan)
  815. }
  816. }
  817. // TestDeleteBehindSymlink checks that we don't delete or schedule a scan
  818. // when trying to delete a file behind a symlink.
  819. func TestDeleteBehindSymlink(t *testing.T) {
  820. _, f, wcfgCancel := setupSendReceiveFolder(t)
  821. defer wcfgCancel()
  822. ffs := f.Filesystem(nil)
  823. link := "link"
  824. linkFile := filepath.Join(link, "file")
  825. must(t, ffs.MkdirAll(link, 0o755))
  826. fi := createEmptyFileInfo(t, linkFile, ffs)
  827. f.updateLocalsFromScanning([]protocol.FileInfo{fi})
  828. must(t, ffs.Rename(linkFile, "file"))
  829. must(t, ffs.RemoveAll(link))
  830. must(t, ffs.CreateSymlink("/", link))
  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, fsetSnapshot(t, f.fset), 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 := ffs.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. _, f, wcfgCancel := setupSendReceiveFolder(t)
  856. defer wcfgCancel()
  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(fsetSnapshot(t, f.fset), 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. _, f, wcfgCancel := setupSendReceiveFolder(t)
  891. defer wcfgCancel()
  892. ffs := f.Filesystem(nil)
  893. dir := "foobar"
  894. must(t, ffs.MkdirAll(dir, 0o777))
  895. fi := protocol.FileInfo{
  896. Name: dir,
  897. }
  898. scanChan := make(chan string, 1)
  899. dbUpdateChan := make(chan dbUpdateJob, 1)
  900. f.deleteDir(fi, fsetSnapshot(t, f.fset), 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, wcfgCancel := setupSendReceiveFolder(t)
  915. defer wcfgCancel()
  916. ffs := f.Filesystem(nil)
  917. name := "foo"
  918. contents := []byte("contents")
  919. writeFile(t, ffs, name, contents)
  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. writeFile(t, ffs, temp, contents)
  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 build.IsWindows {
  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, wcfgCancel := setupSendReceiveFolder(t)
  967. defer wcfgCancel()
  968. ffs := f.Filesystem(nil)
  969. name := "foo"
  970. if dir {
  971. must(t, ffs.Mkdir(name, 0o777))
  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, "uses different upper or lowercase") {
  1011. t.Error("unexpected error", errStr, "for", remote.Name)
  1012. }
  1013. }
  1014. func TestPullTempFileCaseConflict(t *testing.T) {
  1015. _, f, wcfgCancel := setupSendReceiveFolder(t)
  1016. defer wcfgCancel()
  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.mtimefs.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, fsetSnapshot(t, f.fset), copyChan)
  1030. cs := <-copyChan
  1031. if _, err := cs.tempFile(); err != nil {
  1032. t.Error(err)
  1033. } else {
  1034. cs.finalClose()
  1035. }
  1036. }
  1037. func TestPullCaseOnlyRename(t *testing.T) {
  1038. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1039. defer 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 !build.IsWindows {
  1070. t.Skip()
  1071. }
  1072. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1073. defer wcfgCancel()
  1074. conn := 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(conn, 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. _, f, wcfgCancel := setupSendReceiveFolder(t)
  1109. defer 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. _, f, wcfgCancel := setupSendReceiveFolder(t)
  1139. defer 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, 0o777))
  1150. must(t, f.mtimefs.Mkdir(filepath.Join(parent, del), 0o777))
  1151. must(t, f.mtimefs.Mkdir(filepath.Join(parent, del, child), 0o777))
  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. }