folder_sendrecv_test.go 31 KB

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