folder_sendrecv_test.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. "io"
  12. "io/ioutil"
  13. "os"
  14. "path/filepath"
  15. "runtime"
  16. "testing"
  17. "time"
  18. "github.com/syncthing/syncthing/lib/config"
  19. "github.com/syncthing/syncthing/lib/db"
  20. "github.com/syncthing/syncthing/lib/db/backend"
  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. func setupSendReceiveFolder(files ...protocol.FileInfo) (*model, *sendReceiveFolder) {
  83. w := createTmpWrapper(defaultCfg)
  84. model := newModel(w, myID, "syncthing", "dev", db.NewLowlevel(backend.OpenMemory()), nil)
  85. fcfg := testFolderConfigTmp()
  86. model.addFolder(fcfg)
  87. f := &sendReceiveFolder{
  88. folder: folder{
  89. stateTracker: newStateTracker("default", model.evLogger),
  90. model: model,
  91. fset: model.folderFiles[fcfg.ID],
  92. initialScanFinished: make(chan struct{}),
  93. ctx: context.TODO(),
  94. FolderConfiguration: fcfg,
  95. },
  96. queue: newJobQueue(),
  97. writeLimiter: newByteSemaphore(2),
  98. pullErrors: make(map[string]string),
  99. pullErrorsMut: sync.NewMutex(),
  100. }
  101. f.fs = fs.NewMtimeFS(f.Filesystem(), db.NewNamespacedKV(model.db, "mtime"))
  102. // Update index
  103. if files != nil {
  104. f.updateLocalsFromScanning(files)
  105. }
  106. // Folders are never actually started, so no initial scan will be done
  107. close(f.initialScanFinished)
  108. return model, f
  109. }
  110. func cleanupSRFolder(f *sendReceiveFolder, m *model) {
  111. m.evLogger.Stop()
  112. os.Remove(m.cfg.ConfigPath())
  113. os.RemoveAll(f.Filesystem().URI())
  114. }
  115. // Layout of the files: (indexes from the above array)
  116. // 12345678 - Required file
  117. // 02005008 - Existing file (currently in the index)
  118. // 02340070 - Temp file on the disk
  119. func TestHandleFile(t *testing.T) {
  120. // After the diff between required and existing we should:
  121. // Copy: 2, 5, 8
  122. // Pull: 1, 3, 4, 6, 7
  123. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  124. existingFile := setupFile("filex", existingBlocks)
  125. requiredFile := existingFile
  126. requiredFile.Blocks = blocks[1:]
  127. m, f := setupSendReceiveFolder(existingFile)
  128. defer cleanupSRFolder(f, m)
  129. copyChan := make(chan copyBlocksState, 1)
  130. f.handleFile(requiredFile, f.fset.Snapshot(), copyChan)
  131. // Receive the results
  132. toCopy := <-copyChan
  133. if len(toCopy.blocks) != 8 {
  134. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  135. }
  136. for _, block := range blocks[1:] {
  137. found := false
  138. for _, toCopyBlock := range toCopy.blocks {
  139. if string(toCopyBlock.Hash) == string(block.Hash) {
  140. found = true
  141. break
  142. }
  143. }
  144. if !found {
  145. t.Errorf("Did not find block %s", block.String())
  146. }
  147. }
  148. }
  149. func TestHandleFileWithTemp(t *testing.T) {
  150. // After diff between required and existing we should:
  151. // Copy: 2, 5, 8
  152. // Pull: 1, 3, 4, 6, 7
  153. // After dropping out blocks already on the temp file we should:
  154. // Copy: 5, 8
  155. // Pull: 1, 6
  156. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  157. existingFile := setupFile("file", existingBlocks)
  158. requiredFile := existingFile
  159. requiredFile.Blocks = blocks[1:]
  160. m, f := setupSendReceiveFolder(existingFile)
  161. defer cleanupSRFolder(f, m)
  162. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  163. t.Fatal(err)
  164. }
  165. copyChan := make(chan copyBlocksState, 1)
  166. f.handleFile(requiredFile, f.fset.Snapshot(), copyChan)
  167. // Receive the results
  168. toCopy := <-copyChan
  169. if len(toCopy.blocks) != 4 {
  170. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  171. }
  172. for _, idx := range []int{1, 5, 6, 8} {
  173. found := false
  174. block := blocks[idx]
  175. for _, toCopyBlock := range toCopy.blocks {
  176. if string(toCopyBlock.Hash) == string(block.Hash) {
  177. found = true
  178. break
  179. }
  180. }
  181. if !found {
  182. t.Errorf("Did not find block %s", block.String())
  183. }
  184. }
  185. }
  186. func TestCopierFinder(t *testing.T) {
  187. // After diff between required and existing we should:
  188. // Copy: 1, 2, 3, 4, 6, 7, 8
  189. // Since there is no existing file, nor a temp file
  190. // After dropping out blocks found locally:
  191. // Pull: 1, 5, 6, 8
  192. tempFile := fs.TempName("file2")
  193. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  194. existingFile := setupFile(fs.TempName("file"), existingBlocks)
  195. requiredFile := existingFile
  196. requiredFile.Blocks = blocks[1:]
  197. requiredFile.Name = "file2"
  198. m, f := setupSendReceiveFolder(existingFile)
  199. defer cleanupSRFolder(f, m)
  200. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  201. t.Fatal(err)
  202. }
  203. copyChan := make(chan copyBlocksState)
  204. pullChan := make(chan pullBlockState, 4)
  205. finisherChan := make(chan *sharedPullerState, 1)
  206. // Run a single fetcher routine
  207. go f.copierRoutine(copyChan, pullChan, finisherChan)
  208. defer close(copyChan)
  209. f.handleFile(requiredFile, f.fset.Snapshot(), copyChan)
  210. timeout := time.After(10 * time.Second)
  211. pulls := make([]pullBlockState, 4)
  212. for i := 0; i < 4; i++ {
  213. select {
  214. case pulls[i] = <-pullChan:
  215. case <-timeout:
  216. t.Fatalf("Timed out before receiving all 4 states on pullChan (already got %v)", i)
  217. }
  218. }
  219. var finish *sharedPullerState
  220. select {
  221. case finish = <-finisherChan:
  222. case <-timeout:
  223. t.Fatal("Timed out before receiving 4 states on pullChan")
  224. }
  225. defer cleanupSharedPullerState(finish)
  226. select {
  227. case <-pullChan:
  228. t.Fatal("Pull channel has data to be read")
  229. case <-finisherChan:
  230. t.Fatal("Finisher channel has data to be read")
  231. default:
  232. }
  233. // Verify that the right blocks went into the pull list.
  234. // They are pulled in random order.
  235. for _, idx := range []int{1, 5, 6, 8} {
  236. found := false
  237. block := blocks[idx]
  238. for _, pulledBlock := range pulls {
  239. if string(pulledBlock.block.Hash) == string(block.Hash) {
  240. found = true
  241. break
  242. }
  243. }
  244. if !found {
  245. t.Errorf("Did not find block %s", block.String())
  246. }
  247. if string(finish.file.Blocks[idx-1].Hash) != string(blocks[idx].Hash) {
  248. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  249. }
  250. }
  251. // Verify that the fetched blocks have actually been written to the temp file
  252. blks, err := scanner.HashFile(context.TODO(), f.Filesystem(), tempFile, protocol.MinBlockSize, nil, false)
  253. if err != nil {
  254. t.Log(err)
  255. }
  256. for _, eq := range []int{2, 3, 4, 7} {
  257. if string(blks[eq-1].Hash) != string(blocks[eq].Hash) {
  258. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  259. }
  260. }
  261. }
  262. func TestWeakHash(t *testing.T) {
  263. // Setup the model/pull environment
  264. model, fo := setupSendReceiveFolder()
  265. defer cleanupSRFolder(fo, model)
  266. ffs := fo.Filesystem()
  267. tempFile := fs.TempName("weakhash")
  268. var shift int64 = 10
  269. var size int64 = 1 << 20
  270. expectBlocks := int(size / protocol.MinBlockSize)
  271. expectPulls := int(shift / protocol.MinBlockSize)
  272. if shift > 0 {
  273. expectPulls++
  274. }
  275. f, err := ffs.Create("weakhash")
  276. must(t, err)
  277. defer f.Close()
  278. _, err = io.CopyN(f, rand.Reader, size)
  279. if err != nil {
  280. t.Error(err)
  281. }
  282. info, err := f.Stat()
  283. if err != nil {
  284. t.Error(err)
  285. }
  286. // Create two files, second file has `shifted` bytes random prefix, yet
  287. // both are of the same length, for example:
  288. // File 1: abcdefgh
  289. // File 2: xyabcdef
  290. f.Seek(0, os.SEEK_SET)
  291. existing, err := scanner.Blocks(context.TODO(), f, protocol.MinBlockSize, size, nil, true)
  292. if err != nil {
  293. t.Error(err)
  294. }
  295. f.Seek(0, os.SEEK_SET)
  296. remainder := io.LimitReader(f, size-shift)
  297. prefix := io.LimitReader(rand.Reader, shift)
  298. nf := io.MultiReader(prefix, remainder)
  299. desired, err := scanner.Blocks(context.TODO(), nf, protocol.MinBlockSize, size, nil, true)
  300. if err != nil {
  301. t.Error(err)
  302. }
  303. existingFile := protocol.FileInfo{
  304. Name: "weakhash",
  305. Blocks: existing,
  306. Size: size,
  307. ModifiedS: info.ModTime().Unix(),
  308. ModifiedNs: int32(info.ModTime().Nanosecond()),
  309. }
  310. desiredFile := protocol.FileInfo{
  311. Name: "weakhash",
  312. Size: size,
  313. Blocks: desired,
  314. ModifiedS: info.ModTime().Unix() + 1,
  315. }
  316. fo.updateLocalsFromScanning([]protocol.FileInfo{existingFile})
  317. copyChan := make(chan copyBlocksState)
  318. pullChan := make(chan pullBlockState, expectBlocks)
  319. finisherChan := make(chan *sharedPullerState, 1)
  320. // Run a single fetcher routine
  321. go fo.copierRoutine(copyChan, pullChan, finisherChan)
  322. defer close(copyChan)
  323. // Test 1 - no weak hashing, file gets fully repulled (`expectBlocks` pulls).
  324. fo.WeakHashThresholdPct = 101
  325. fo.handleFile(desiredFile, fo.fset.Snapshot(), copyChan)
  326. var pulls []pullBlockState
  327. timeout := time.After(10 * time.Second)
  328. for len(pulls) < expectBlocks {
  329. select {
  330. case pull := <-pullChan:
  331. pulls = append(pulls, pull)
  332. case <-timeout:
  333. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  334. }
  335. }
  336. finish := <-finisherChan
  337. select {
  338. case <-pullChan:
  339. t.Fatal("Pull channel has data to be read")
  340. case <-finisherChan:
  341. t.Fatal("Finisher channel has data to be read")
  342. default:
  343. }
  344. cleanupSharedPullerState(finish)
  345. if err := ffs.Remove(tempFile); err != nil {
  346. t.Fatal(err)
  347. }
  348. // Test 2 - using weak hash, expectPulls blocks pulled.
  349. fo.WeakHashThresholdPct = -1
  350. fo.handleFile(desiredFile, fo.fset.Snapshot(), copyChan)
  351. pulls = pulls[:0]
  352. for len(pulls) < expectPulls {
  353. select {
  354. case pull := <-pullChan:
  355. pulls = append(pulls, pull)
  356. case <-time.After(10 * time.Second):
  357. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  358. }
  359. }
  360. finish = <-finisherChan
  361. cleanupSharedPullerState(finish)
  362. expectShifted := expectBlocks - expectPulls
  363. if finish.copyOriginShifted != expectShifted {
  364. t.Errorf("did not copy %d shifted", expectShifted)
  365. }
  366. }
  367. // Test that updating a file removes its old blocks from the blockmap
  368. func TestCopierCleanup(t *testing.T) {
  369. iterFn := func(folder, file string, index int32) bool {
  370. return true
  371. }
  372. // Create a file
  373. file := setupFile("test", []int{0})
  374. m, f := setupSendReceiveFolder(file)
  375. defer cleanupSRFolder(f, m)
  376. file.Blocks = []protocol.BlockInfo{blocks[1]}
  377. file.Version = file.Version.Update(myID.Short())
  378. // Update index (removing old blocks)
  379. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  380. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  381. t.Error("Unexpected block found")
  382. }
  383. if !m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  384. t.Error("Expected block not found")
  385. }
  386. file.Blocks = []protocol.BlockInfo{blocks[0]}
  387. file.Version = file.Version.Update(myID.Short())
  388. // Update index (removing old blocks)
  389. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  390. if !m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  391. t.Error("Unexpected block found")
  392. }
  393. if m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  394. t.Error("Expected block not found")
  395. }
  396. }
  397. func TestDeregisterOnFailInCopy(t *testing.T) {
  398. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  399. m, f := setupSendReceiveFolder()
  400. defer cleanupSRFolder(f, m)
  401. // Set up our evet subscription early
  402. s := m.evLogger.Subscribe(events.ItemFinished)
  403. // queue.Done should be called by the finisher routine
  404. f.queue.Push("filex", 0, time.Time{})
  405. f.queue.Pop()
  406. if f.queue.lenProgress() != 1 {
  407. t.Fatal("Expected file in progress")
  408. }
  409. pullChan := make(chan pullBlockState)
  410. finisherBufferChan := make(chan *sharedPullerState)
  411. finisherChan := make(chan *sharedPullerState)
  412. dbUpdateChan := make(chan dbUpdateJob, 1)
  413. snap := f.fset.Snapshot()
  414. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  415. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, make(chan string))
  416. defer func() {
  417. close(copyChan)
  418. copyWg.Wait()
  419. close(pullChan)
  420. close(finisherBufferChan)
  421. close(finisherChan)
  422. }()
  423. f.handleFile(file, snap, copyChan)
  424. // Receive a block at puller, to indicate that at least a single copier
  425. // loop has been performed.
  426. toPull := <-pullChan
  427. // Unblock copier
  428. go func() {
  429. for range pullChan {
  430. }
  431. }()
  432. // Close the file, causing errors on further access
  433. toPull.sharedPullerState.fail(os.ErrNotExist)
  434. select {
  435. case state := <-finisherBufferChan:
  436. // At this point the file should still be registered with both the job
  437. // queue, and the progress emitter. Verify this.
  438. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  439. t.Fatal("Could not find file")
  440. }
  441. // Pass the file down the real finisher, and give it time to consume
  442. finisherChan <- state
  443. t0 := time.Now()
  444. if ev, err := s.Poll(time.Minute); err != nil {
  445. t.Fatal("Got error waiting for ItemFinished event:", err)
  446. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  447. t.Fatal("Got ItemFinished event for wrong file:", n)
  448. }
  449. t.Log("event took", time.Since(t0))
  450. state.mut.Lock()
  451. stateWriter := state.writer
  452. state.mut.Unlock()
  453. if stateWriter != nil {
  454. t.Fatal("File not closed?")
  455. }
  456. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  457. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  458. }
  459. // Doing it again should have no effect
  460. finisherChan <- state
  461. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  462. t.Fatal("Expected timeout, not another event", err)
  463. }
  464. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  465. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  466. }
  467. case <-time.After(5 * time.Second):
  468. t.Fatal("Didn't get anything to the finisher")
  469. }
  470. }
  471. func TestDeregisterOnFailInPull(t *testing.T) {
  472. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  473. m, f := setupSendReceiveFolder()
  474. defer cleanupSRFolder(f, m)
  475. // Set up our evet subscription early
  476. s := m.evLogger.Subscribe(events.ItemFinished)
  477. // queue.Done should be called by the finisher routine
  478. f.queue.Push("filex", 0, time.Time{})
  479. f.queue.Pop()
  480. if f.queue.lenProgress() != 1 {
  481. t.Fatal("Expected file in progress")
  482. }
  483. pullChan := make(chan pullBlockState)
  484. finisherBufferChan := make(chan *sharedPullerState)
  485. finisherChan := make(chan *sharedPullerState)
  486. dbUpdateChan := make(chan dbUpdateJob, 1)
  487. snap := f.fset.Snapshot()
  488. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  489. pullWg := sync.NewWaitGroup()
  490. pullWg.Add(1)
  491. go func() {
  492. f.pullerRoutine(pullChan, finisherBufferChan)
  493. pullWg.Done()
  494. }()
  495. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, make(chan string))
  496. defer func() {
  497. // Unblock copier and puller
  498. go func() {
  499. for range finisherBufferChan {
  500. }
  501. }()
  502. close(copyChan)
  503. copyWg.Wait()
  504. close(pullChan)
  505. pullWg.Wait()
  506. close(finisherBufferChan)
  507. close(finisherChan)
  508. }()
  509. f.handleFile(file, snap, copyChan)
  510. // Receive at finisher, we should error out as puller has nowhere to pull
  511. // from.
  512. timeout = time.Second
  513. // Both the puller and copier may send to the finisherBufferChan.
  514. var state *sharedPullerState
  515. after := time.After(5 * time.Second)
  516. for {
  517. select {
  518. case state = <-finisherBufferChan:
  519. case <-after:
  520. t.Fatal("Didn't get failed state to the finisher")
  521. }
  522. if state.failed() != nil {
  523. break
  524. }
  525. }
  526. // At this point the file should still be registered with both the job
  527. // queue, and the progress emitter. Verify this.
  528. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  529. t.Fatal("Could not find file")
  530. }
  531. // Pass the file down the real finisher, and give it time to consume
  532. finisherChan <- state
  533. t0 := time.Now()
  534. if ev, err := s.Poll(time.Minute); err != nil {
  535. t.Fatal("Got error waiting for ItemFinished event:", err)
  536. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  537. t.Fatal("Got ItemFinished event for wrong file:", n)
  538. }
  539. t.Log("event took", time.Since(t0))
  540. state.mut.Lock()
  541. stateWriter := state.writer
  542. state.mut.Unlock()
  543. if stateWriter != nil {
  544. t.Fatal("File not closed?")
  545. }
  546. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  547. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  548. }
  549. // Doing it again should have no effect
  550. finisherChan <- state
  551. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  552. t.Fatal("Expected timeout, not another event", err)
  553. }
  554. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  555. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  556. }
  557. }
  558. func TestIssue3164(t *testing.T) {
  559. m, f := setupSendReceiveFolder()
  560. defer cleanupSRFolder(f, m)
  561. ffs := f.Filesystem()
  562. tmpDir := ffs.URI()
  563. ignDir := filepath.Join("issue3164", "oktodelete")
  564. subDir := filepath.Join(ignDir, "foobar")
  565. must(t, ffs.MkdirAll(subDir, 0777))
  566. must(t, ioutil.WriteFile(filepath.Join(tmpDir, subDir, "file"), []byte("Hello"), 0644))
  567. must(t, ioutil.WriteFile(filepath.Join(tmpDir, ignDir, "file"), []byte("Hello"), 0644))
  568. file := protocol.FileInfo{
  569. Name: "issue3164",
  570. }
  571. matcher := ignore.New(ffs)
  572. must(t, matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""))
  573. f.ignores = matcher
  574. dbUpdateChan := make(chan dbUpdateJob, 1)
  575. f.deleteDir(file, f.fset.Snapshot(), dbUpdateChan, make(chan string))
  576. if _, err := ffs.Stat("issue3164"); !fs.IsNotExist(err) {
  577. t.Fatal(err)
  578. }
  579. }
  580. func TestDiff(t *testing.T) {
  581. for i, test := range diffTestData {
  582. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  583. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  584. _, d := blockDiff(a, b)
  585. if len(d) != len(test.d) {
  586. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  587. } else {
  588. for j := range test.d {
  589. if d[j].Offset != test.d[j].Offset {
  590. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  591. }
  592. if d[j].Size != test.d[j].Size {
  593. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  594. }
  595. }
  596. }
  597. }
  598. }
  599. func BenchmarkDiff(b *testing.B) {
  600. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  601. for _, test := range diffTestData {
  602. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  603. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  604. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{a, b})
  605. }
  606. b.ReportAllocs()
  607. b.ResetTimer()
  608. for i := 0; i < b.N; i++ {
  609. for _, tc := range testCases {
  610. blockDiff(tc.a, tc.b)
  611. }
  612. }
  613. }
  614. func TestDiffEmpty(t *testing.T) {
  615. emptyCases := []struct {
  616. a []protocol.BlockInfo
  617. b []protocol.BlockInfo
  618. need int
  619. have int
  620. }{
  621. {nil, nil, 0, 0},
  622. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  623. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  624. }
  625. for _, emptyCase := range emptyCases {
  626. h, n := blockDiff(emptyCase.a, emptyCase.b)
  627. if len(h) != emptyCase.have {
  628. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  629. }
  630. if len(n) != emptyCase.need {
  631. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  632. }
  633. }
  634. }
  635. // TestDeleteIgnorePerms checks, that a file gets deleted when the IgnorePerms
  636. // option is true and the permissions do not match between the file on disk and
  637. // in the db.
  638. func TestDeleteIgnorePerms(t *testing.T) {
  639. m, f := setupSendReceiveFolder()
  640. defer cleanupSRFolder(f, m)
  641. ffs := f.Filesystem()
  642. f.IgnorePerms = true
  643. name := "deleteIgnorePerms"
  644. file, err := ffs.Create(name)
  645. if err != nil {
  646. t.Error(err)
  647. }
  648. defer file.Close()
  649. stat, err := file.Stat()
  650. must(t, err)
  651. fi, err := scanner.CreateFileInfo(stat, name, ffs)
  652. must(t, err)
  653. ffs.Chmod(name, 0600)
  654. scanChan := make(chan string)
  655. finished := make(chan struct{})
  656. go func() {
  657. err = f.checkToBeDeleted(fi, scanChan)
  658. close(finished)
  659. }()
  660. select {
  661. case <-scanChan:
  662. <-finished
  663. case <-finished:
  664. }
  665. must(t, err)
  666. }
  667. func TestCopyOwner(t *testing.T) {
  668. // Verifies that owner and group are copied from the parent, for both
  669. // files and directories.
  670. if runtime.GOOS == "windows" {
  671. t.Skip("copying owner not supported on Windows")
  672. }
  673. const (
  674. expOwner = 1234
  675. expGroup = 5678
  676. )
  677. // Set up a folder with the CopyParentOwner bit and backed by a fake
  678. // filesystem.
  679. m, f := setupSendReceiveFolder()
  680. defer cleanupSRFolder(f, m)
  681. f.folder.FolderConfiguration = config.NewFolderConfiguration(m.id, f.ID, f.Label, fs.FilesystemTypeFake, "/TestCopyOwner")
  682. f.folder.FolderConfiguration.CopyOwnershipFromParent = true
  683. f.fs = f.Filesystem()
  684. // Create a parent dir with a certain owner/group.
  685. f.fs.Mkdir("foo", 0755)
  686. f.fs.Lchown("foo", expOwner, expGroup)
  687. dir := protocol.FileInfo{
  688. Name: "foo/bar",
  689. Type: protocol.FileInfoTypeDirectory,
  690. Permissions: 0755,
  691. }
  692. // Have the folder create a subdirectory, verify that it's the correct
  693. // owner/group.
  694. dbUpdateChan := make(chan dbUpdateJob, 1)
  695. defer close(dbUpdateChan)
  696. f.handleDir(dir, f.fset.Snapshot(), dbUpdateChan, nil)
  697. <-dbUpdateChan // empty the channel for later
  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, nil)
  743. <-dbUpdateChan
  744. info, err = f.fs.Lstat("foo/bar/sym")
  745. if err != nil {
  746. t.Fatal("Unexpected error (file):", err)
  747. }
  748. if info.Owner() != expOwner || info.Group() != expGroup {
  749. t.Fatalf("Expected symlink owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  750. }
  751. }
  752. // TestSRConflictReplaceFileByDir checks that a conflict is created when an existing file
  753. // is replaced with a directory and versions are conflicting
  754. func TestSRConflictReplaceFileByDir(t *testing.T) {
  755. m, f := setupSendReceiveFolder()
  756. defer cleanupSRFolder(f, m)
  757. ffs := f.Filesystem()
  758. name := "foo"
  759. // create local file
  760. file := createFile(t, name, ffs)
  761. file.Version = protocol.Vector{}.Update(myID.Short())
  762. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  763. // Simulate remote creating a dir with the same name
  764. file.Type = protocol.FileInfoTypeDirectory
  765. rem := device1.Short()
  766. file.Version = protocol.Vector{}.Update(rem)
  767. file.ModifiedBy = rem
  768. dbUpdateChan := make(chan dbUpdateJob, 1)
  769. scanChan := make(chan string, 1)
  770. f.handleDir(file, f.fset.Snapshot(), dbUpdateChan, scanChan)
  771. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  772. t.Fatal("Expected one conflict, got", len(confls))
  773. } else if scan := <-scanChan; confls[0] != scan {
  774. t.Fatal("Expected request to scan", confls[0], "got", scan)
  775. }
  776. }
  777. // TestSRConflictReplaceFileByLink checks that a conflict is created when an existing file
  778. // is replaced with a link and versions are conflicting
  779. func TestSRConflictReplaceFileByLink(t *testing.T) {
  780. m, f := setupSendReceiveFolder()
  781. defer cleanupSRFolder(f, m)
  782. ffs := f.Filesystem()
  783. name := "foo"
  784. // create local file
  785. file := createFile(t, name, ffs)
  786. file.Version = protocol.Vector{}.Update(myID.Short())
  787. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  788. // Simulate remote creating a symlink with the same name
  789. file.Type = protocol.FileInfoTypeSymlink
  790. file.SymlinkTarget = "bar"
  791. rem := device1.Short()
  792. file.Version = protocol.Vector{}.Update(rem)
  793. file.ModifiedBy = rem
  794. dbUpdateChan := make(chan dbUpdateJob, 1)
  795. scanChan := make(chan string, 1)
  796. f.handleSymlink(file, f.fset.Snapshot(), dbUpdateChan, scanChan)
  797. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  798. t.Fatal("Expected one conflict, got", len(confls))
  799. } else if scan := <-scanChan; confls[0] != scan {
  800. t.Fatal("Expected request to scan", confls[0], "got", scan)
  801. }
  802. }
  803. // TestDeleteBehindSymlink checks that we don't delete or schedule a scan
  804. // when trying to delete a file behind a symlink.
  805. func TestDeleteBehindSymlink(t *testing.T) {
  806. m, f := setupSendReceiveFolder()
  807. defer cleanupSRFolder(f, m)
  808. ffs := f.Filesystem()
  809. destDir := createTmpDir()
  810. defer os.RemoveAll(destDir)
  811. destFs := fs.NewFilesystem(fs.FilesystemTypeBasic, destDir)
  812. link := "link"
  813. file := filepath.Join(link, "file")
  814. must(t, ffs.MkdirAll(link, 0755))
  815. fi := createFile(t, file, ffs)
  816. f.updateLocalsFromScanning([]protocol.FileInfo{fi})
  817. must(t, osutil.RenameOrCopy(ffs, destFs, file, "file"))
  818. must(t, ffs.RemoveAll(link))
  819. if err := osutil.DebugSymlinkForTestsOnly(destFs.URI(), filepath.Join(ffs.URI(), link)); err != nil {
  820. if runtime.GOOS == "windows" {
  821. // Probably we require permissions we don't have.
  822. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  823. } else {
  824. t.Fatal(err)
  825. }
  826. }
  827. fi.Deleted = true
  828. fi.Version = fi.Version.Update(device1.Short())
  829. scanChan := make(chan string, 1)
  830. dbUpdateChan := make(chan dbUpdateJob, 1)
  831. f.deleteFile(fi, f.fset.Snapshot(), dbUpdateChan, scanChan)
  832. select {
  833. case f := <-scanChan:
  834. t.Fatalf("Received %v on scanChan", f)
  835. case u := <-dbUpdateChan:
  836. if u.jobType != dbUpdateDeleteFile {
  837. t.Errorf("Expected jobType %v, got %v", dbUpdateDeleteFile, u.jobType)
  838. }
  839. if u.file.Name != fi.Name {
  840. t.Errorf("Expected update for %v, got %v", fi.Name, u.file.Name)
  841. }
  842. default:
  843. t.Fatalf("No db update received")
  844. }
  845. if _, err := destFs.Stat("file"); err != nil {
  846. t.Errorf("Expected no error when stating file behind symlink, got %v", err)
  847. }
  848. }
  849. // Reproduces https://github.com/syncthing/syncthing/issues/6559
  850. func TestPullCtxCancel(t *testing.T) {
  851. m, f := setupSendReceiveFolder()
  852. defer cleanupSRFolder(f, m)
  853. pullChan := make(chan pullBlockState)
  854. finisherChan := make(chan *sharedPullerState)
  855. var cancel context.CancelFunc
  856. f.ctx, cancel = context.WithCancel(context.Background())
  857. go f.pullerRoutine(pullChan, finisherChan)
  858. defer close(pullChan)
  859. emptyState := func() pullBlockState {
  860. return pullBlockState{
  861. sharedPullerState: newSharedPullerState(protocol.FileInfo{}, nil, f.folderID, "", nil, nil, false, false, protocol.FileInfo{}, false, false),
  862. block: protocol.BlockInfo{},
  863. }
  864. }
  865. cancel()
  866. done := make(chan struct{})
  867. defer close(done)
  868. for i := 0; i < 2; i++ {
  869. go func() {
  870. select {
  871. case pullChan <- emptyState():
  872. case <-done:
  873. }
  874. }()
  875. select {
  876. case s := <-finisherChan:
  877. if s.failed() == nil {
  878. t.Errorf("state %v not failed", i)
  879. }
  880. case <-time.After(5 * time.Second):
  881. t.Fatalf("timed out before receiving state %v on finisherChan", i)
  882. }
  883. }
  884. }
  885. func cleanupSharedPullerState(s *sharedPullerState) {
  886. s.mut.Lock()
  887. defer s.mut.Unlock()
  888. if s.writer == nil {
  889. return
  890. }
  891. s.writer.mut.Lock()
  892. s.writer.fd.Close()
  893. s.writer.mut.Unlock()
  894. }
  895. func startCopier(f *sendReceiveFolder, pullChan chan<- pullBlockState, finisherChan chan<- *sharedPullerState) (chan copyBlocksState, sync.WaitGroup) {
  896. copyChan := make(chan copyBlocksState)
  897. wg := sync.NewWaitGroup()
  898. wg.Add(1)
  899. go func() {
  900. f.copierRoutine(copyChan, pullChan, finisherChan)
  901. wg.Done()
  902. }()
  903. return copyChan, wg
  904. }