folder_sendrecv_test.go 40 KB

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