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. "io/ioutil"
  15. "os"
  16. "path/filepath"
  17. "runtime"
  18. "strings"
  19. "testing"
  20. "time"
  21. "github.com/syncthing/syncthing/lib/events"
  22. "github.com/syncthing/syncthing/lib/fs"
  23. "github.com/syncthing/syncthing/lib/ignore"
  24. "github.com/syncthing/syncthing/lib/osutil"
  25. "github.com/syncthing/syncthing/lib/protocol"
  26. "github.com/syncthing/syncthing/lib/scanner"
  27. "github.com/syncthing/syncthing/lib/sync"
  28. )
  29. var blocks = []protocol.BlockInfo{
  30. {Hash: []uint8{0xfa, 0x43, 0x23, 0x9b, 0xce, 0xe7, 0xb9, 0x7c, 0xa6, 0x2f, 0x0, 0x7c, 0xc6, 0x84, 0x87, 0x56, 0xa, 0x39, 0xe1, 0x9f, 0x74, 0xf3, 0xdd, 0xe7, 0x48, 0x6d, 0xb3, 0xf9, 0x8d, 0xf8, 0xe4, 0x71}}, // Zero'ed out block
  31. {Offset: 0, Size: 0x20000, Hash: []uint8{0x7e, 0xad, 0xbc, 0x36, 0xae, 0xbb, 0xcf, 0x74, 0x43, 0xe2, 0x7a, 0x5a, 0x4b, 0xb8, 0x5b, 0xce, 0xe6, 0x9e, 0x1e, 0x10, 0xf9, 0x8a, 0xbc, 0x77, 0x95, 0x2, 0x29, 0x60, 0x9e, 0x96, 0xae, 0x6c}},
  32. {Offset: 131072, Size: 0x20000, Hash: []uint8{0x3c, 0xc4, 0x20, 0xf4, 0xb, 0x2e, 0xcb, 0xb9, 0x5d, 0xce, 0x34, 0xa8, 0xc3, 0x92, 0xea, 0xf3, 0xda, 0x88, 0x33, 0xee, 0x7a, 0xb6, 0xe, 0xf1, 0x82, 0x5e, 0xb0, 0xa9, 0x26, 0xa9, 0xc0, 0xef}},
  33. {Offset: 262144, Size: 0x20000, Hash: []uint8{0x76, 0xa8, 0xc, 0x69, 0xd7, 0x5c, 0x52, 0xfd, 0xdf, 0x55, 0xef, 0x44, 0xc1, 0xd6, 0x25, 0x48, 0x4d, 0x98, 0x48, 0x4d, 0xaa, 0x50, 0xf6, 0x6b, 0x32, 0x47, 0x55, 0x81, 0x6b, 0xed, 0xee, 0xfb}},
  34. {Offset: 393216, Size: 0x20000, Hash: []uint8{0x44, 0x1e, 0xa4, 0xf2, 0x8d, 0x1f, 0xc3, 0x1b, 0x9d, 0xa5, 0x18, 0x5e, 0x59, 0x1b, 0xd8, 0x5c, 0xba, 0x7d, 0xb9, 0x8d, 0x70, 0x11, 0x5c, 0xea, 0xa1, 0x57, 0x4d, 0xcb, 0x3c, 0x5b, 0xf8, 0x6c}},
  35. {Offset: 524288, Size: 0x20000, Hash: []uint8{0x8, 0x40, 0xd0, 0x5e, 0x80, 0x0, 0x0, 0x7c, 0x8b, 0xb3, 0x8b, 0xf7, 0x7b, 0x23, 0x26, 0x28, 0xab, 0xda, 0xcf, 0x86, 0x8f, 0xc2, 0x8a, 0x39, 0xc6, 0xe6, 0x69, 0x59, 0x97, 0xb6, 0x1a, 0x43}},
  36. {Offset: 655360, Size: 0x20000, Hash: []uint8{0x38, 0x8e, 0x44, 0xcb, 0x30, 0xd8, 0x90, 0xf, 0xce, 0x7, 0x4b, 0x58, 0x86, 0xde, 0xce, 0x59, 0xa2, 0x46, 0xd2, 0xf9, 0xba, 0xaf, 0x35, 0x87, 0x38, 0xdf, 0xd2, 0xd, 0xf9, 0x45, 0xed, 0x91}},
  37. {Offset: 786432, Size: 0x20000, Hash: []uint8{0x32, 0x28, 0xcd, 0xf, 0x37, 0x21, 0xe5, 0xd4, 0x1e, 0x58, 0x87, 0x73, 0x8e, 0x36, 0xdf, 0xb2, 0x70, 0x78, 0x56, 0xc3, 0x42, 0xff, 0xf7, 0x8f, 0x37, 0x95, 0x0, 0x26, 0xa, 0xac, 0x54, 0x72}},
  38. {Offset: 917504, Size: 0x20000, Hash: []uint8{0x96, 0x6b, 0x15, 0x6b, 0xc4, 0xf, 0x19, 0x18, 0xca, 0xbb, 0x5f, 0xd6, 0xbb, 0xa2, 0xc6, 0x2a, 0xac, 0xbb, 0x8a, 0xb9, 0xce, 0xec, 0x4c, 0xdb, 0x78, 0xec, 0x57, 0x5d, 0x33, 0xf9, 0x8e, 0xaf}},
  39. }
  40. var folders = []string{"default"}
  41. var diffTestData = []struct {
  42. a string
  43. b string
  44. s int
  45. d []protocol.BlockInfo
  46. }{
  47. {"contents", "contents", 1024, []protocol.BlockInfo{}},
  48. {"", "", 1024, []protocol.BlockInfo{}},
  49. {"contents", "contents", 3, []protocol.BlockInfo{}},
  50. {"contents", "cantents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}}},
  51. {"contents", "contants", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}}},
  52. {"contents", "cantants", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}}},
  53. {"contents", "", 3, []protocol.BlockInfo{{Offset: 0, Size: 0}}},
  54. {"", "contents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  55. {"con", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  56. {"contents", "con", 3, nil},
  57. {"contents", "cont", 3, []protocol.BlockInfo{{Offset: 3, Size: 1}}},
  58. {"cont", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  59. }
  60. func setupFile(filename string, blockNumbers []int) protocol.FileInfo {
  61. // Create existing file
  62. existingBlocks := make([]protocol.BlockInfo, len(blockNumbers))
  63. for i := range blockNumbers {
  64. existingBlocks[i] = blocks[blockNumbers[i]]
  65. }
  66. return protocol.FileInfo{
  67. Name: filename,
  68. Blocks: existingBlocks,
  69. }
  70. }
  71. func createFile(t *testing.T, name string, fs fs.Filesystem) protocol.FileInfo {
  72. t.Helper()
  73. f, err := fs.Create(name)
  74. must(t, err)
  75. f.Close()
  76. fi, err := fs.Stat(name)
  77. must(t, err)
  78. file, err := scanner.CreateFileInfo(fi, name, fs)
  79. must(t, err)
  80. return file
  81. }
  82. // Sets up a folder and model, but makes sure the services aren't actually running.
  83. func setupSendReceiveFolder(t testing.TB, files ...protocol.FileInfo) (*testModel, *sendReceiveFolder, context.CancelFunc) {
  84. w, fcfg, wCancel := tmpDefaultWrapper()
  85. // Initialise model and stop immediately.
  86. model := setupModel(t, w)
  87. model.cancel()
  88. <-model.stopped
  89. f := model.folderRunners[fcfg.ID].(*sendReceiveFolder)
  90. f.tempPullErrors = make(map[string]string)
  91. f.ctx = context.Background()
  92. // Update index
  93. if files != nil {
  94. f.updateLocalsFromScanning(files)
  95. }
  96. return model, f, wCancel
  97. }
  98. func cleanupSRFolder(f *sendReceiveFolder, m *testModel, wrapperCancel context.CancelFunc) {
  99. wrapperCancel()
  100. os.Remove(m.cfg.ConfigPath())
  101. os.RemoveAll(f.Filesystem().URI())
  102. }
  103. // Layout of the files: (indexes from the above array)
  104. // 12345678 - Required file
  105. // 02005008 - Existing file (currently in the index)
  106. // 02340070 - Temp file on the disk
  107. func TestHandleFile(t *testing.T) {
  108. // After the diff between required and existing we should:
  109. // Copy: 2, 5, 8
  110. // Pull: 1, 3, 4, 6, 7
  111. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  112. existingFile := setupFile("filex", existingBlocks)
  113. requiredFile := existingFile
  114. requiredFile.Blocks = blocks[1:]
  115. m, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  116. defer cleanupSRFolder(f, m, wcfgCancel)
  117. copyChan := make(chan copyBlocksState, 1)
  118. f.handleFile(requiredFile, f.fset.Snapshot(), copyChan)
  119. // Receive the results
  120. toCopy := <-copyChan
  121. if len(toCopy.blocks) != 8 {
  122. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  123. }
  124. for _, block := range blocks[1:] {
  125. found := false
  126. for _, toCopyBlock := range toCopy.blocks {
  127. if string(toCopyBlock.Hash) == string(block.Hash) {
  128. found = true
  129. break
  130. }
  131. }
  132. if !found {
  133. t.Errorf("Did not find block %s", block.String())
  134. }
  135. }
  136. }
  137. func TestHandleFileWithTemp(t *testing.T) {
  138. // After diff between required and existing we should:
  139. // Copy: 2, 5, 8
  140. // Pull: 1, 3, 4, 6, 7
  141. // After dropping out blocks already on the temp file we should:
  142. // Copy: 5, 8
  143. // Pull: 1, 6
  144. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  145. existingFile := setupFile("file", existingBlocks)
  146. requiredFile := existingFile
  147. requiredFile.Blocks = blocks[1:]
  148. m, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  149. defer cleanupSRFolder(f, m, wcfgCancel)
  150. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  151. t.Fatal(err)
  152. }
  153. copyChan := make(chan copyBlocksState, 1)
  154. f.handleFile(requiredFile, f.fset.Snapshot(), copyChan)
  155. // Receive the results
  156. toCopy := <-copyChan
  157. if len(toCopy.blocks) != 4 {
  158. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  159. }
  160. for _, idx := range []int{1, 5, 6, 8} {
  161. found := false
  162. block := blocks[idx]
  163. for _, toCopyBlock := range toCopy.blocks {
  164. if string(toCopyBlock.Hash) == string(block.Hash) {
  165. found = true
  166. break
  167. }
  168. }
  169. if !found {
  170. t.Errorf("Did not find block %s", block.String())
  171. }
  172. }
  173. }
  174. func TestCopierFinder(t *testing.T) {
  175. methods := []fs.CopyRangeMethod{fs.CopyRangeMethodStandard, fs.CopyRangeMethodAllWithFallback}
  176. if runtime.GOOS == "linux" {
  177. methods = append(methods, fs.CopyRangeMethodSendFile)
  178. }
  179. for _, method := range methods {
  180. t.Run(method.String(), func(t *testing.T) {
  181. // After diff between required and existing we should:
  182. // Copy: 1, 2, 3, 4, 6, 7, 8
  183. // Since there is no existing file, nor a temp file
  184. // After dropping out blocks found locally:
  185. // Pull: 1, 5, 6, 8
  186. tempFile := fs.TempName("file2")
  187. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  188. existingFile := setupFile(fs.TempName("file"), existingBlocks)
  189. existingFile.Size = 1
  190. requiredFile := existingFile
  191. requiredFile.Blocks = blocks[1:]
  192. requiredFile.Name = "file2"
  193. m, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  194. f.CopyRangeMethod = method
  195. defer cleanupSRFolder(f, m, wcfgCancel)
  196. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  197. t.Fatal(err)
  198. }
  199. copyChan := make(chan copyBlocksState)
  200. pullChan := make(chan pullBlockState, 4)
  201. finisherChan := make(chan *sharedPullerState, 1)
  202. // Run a single fetcher routine
  203. go f.copierRoutine(copyChan, pullChan, finisherChan)
  204. defer close(copyChan)
  205. f.handleFile(requiredFile, f.fset.Snapshot(), copyChan)
  206. timeout := time.After(10 * time.Second)
  207. pulls := make([]pullBlockState, 4)
  208. for i := 0; i < 4; i++ {
  209. select {
  210. case pulls[i] = <-pullChan:
  211. case <-timeout:
  212. t.Fatalf("Timed out before receiving all 4 states on pullChan (already got %v)", i)
  213. }
  214. }
  215. var finish *sharedPullerState
  216. select {
  217. case finish = <-finisherChan:
  218. case <-timeout:
  219. t.Fatal("Timed out before receiving 4 states on pullChan")
  220. }
  221. defer cleanupSharedPullerState(finish)
  222. select {
  223. case <-pullChan:
  224. t.Fatal("Pull channel has data to be read")
  225. case <-finisherChan:
  226. t.Fatal("Finisher channel has data to be read")
  227. default:
  228. }
  229. // Verify that the right blocks went into the pull list.
  230. // They are pulled in random order.
  231. for _, idx := range []int{1, 5, 6, 8} {
  232. found := false
  233. block := blocks[idx]
  234. for _, pulledBlock := range pulls {
  235. if string(pulledBlock.block.Hash) == string(block.Hash) {
  236. found = true
  237. break
  238. }
  239. }
  240. if !found {
  241. t.Errorf("Did not find block %s", block.String())
  242. }
  243. if string(finish.file.Blocks[idx-1].Hash) != string(blocks[idx].Hash) {
  244. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  245. }
  246. }
  247. // Verify that the fetched blocks have actually been written to the temp file
  248. blks, err := scanner.HashFile(context.TODO(), f.Filesystem(), tempFile, protocol.MinBlockSize, nil, false)
  249. if err != nil {
  250. t.Log(err)
  251. }
  252. for _, eq := range []int{2, 3, 4, 7} {
  253. if string(blks[eq-1].Hash) != string(blocks[eq].Hash) {
  254. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  255. }
  256. }
  257. })
  258. }
  259. }
  260. func TestWeakHash(t *testing.T) {
  261. // Setup the model/pull environment
  262. model, fo, wcfgCancel := setupSendReceiveFolder(t)
  263. defer cleanupSRFolder(fo, model, wcfgCancel)
  264. ffs := fo.Filesystem()
  265. tempFile := fs.TempName("weakhash")
  266. var shift int64 = 10
  267. var size int64 = 1 << 20
  268. expectBlocks := int(size / protocol.MinBlockSize)
  269. expectPulls := int(shift / protocol.MinBlockSize)
  270. if shift > 0 {
  271. expectPulls++
  272. }
  273. f, err := ffs.Create("weakhash")
  274. must(t, err)
  275. defer f.Close()
  276. _, err = io.CopyN(f, rand.Reader, size)
  277. if err != nil {
  278. t.Error(err)
  279. }
  280. info, err := f.Stat()
  281. if err != nil {
  282. t.Error(err)
  283. }
  284. // Create two files, second file has `shifted` bytes random prefix, yet
  285. // both are of the same length, for example:
  286. // File 1: abcdefgh
  287. // File 2: xyabcdef
  288. f.Seek(0, os.SEEK_SET)
  289. existing, err := scanner.Blocks(context.TODO(), f, protocol.MinBlockSize, size, nil, true)
  290. if err != nil {
  291. t.Error(err)
  292. }
  293. f.Seek(0, os.SEEK_SET)
  294. remainder := io.LimitReader(f, size-shift)
  295. prefix := io.LimitReader(rand.Reader, shift)
  296. nf := io.MultiReader(prefix, remainder)
  297. desired, err := scanner.Blocks(context.TODO(), nf, protocol.MinBlockSize, size, nil, true)
  298. if err != nil {
  299. t.Error(err)
  300. }
  301. existingFile := protocol.FileInfo{
  302. Name: "weakhash",
  303. Blocks: existing,
  304. Size: size,
  305. ModifiedS: info.ModTime().Unix(),
  306. ModifiedNs: info.ModTime().Nanosecond(),
  307. }
  308. desiredFile := protocol.FileInfo{
  309. Name: "weakhash",
  310. Size: size,
  311. Blocks: desired,
  312. ModifiedS: info.ModTime().Unix() + 1,
  313. }
  314. fo.updateLocalsFromScanning([]protocol.FileInfo{existingFile})
  315. copyChan := make(chan copyBlocksState)
  316. pullChan := make(chan pullBlockState, expectBlocks)
  317. finisherChan := make(chan *sharedPullerState, 1)
  318. // Run a single fetcher routine
  319. go fo.copierRoutine(copyChan, pullChan, finisherChan)
  320. defer close(copyChan)
  321. // Test 1 - no weak hashing, file gets fully repulled (`expectBlocks` pulls).
  322. fo.WeakHashThresholdPct = 101
  323. fo.handleFile(desiredFile, fo.fset.Snapshot(), copyChan)
  324. var pulls []pullBlockState
  325. timeout := time.After(10 * time.Second)
  326. for len(pulls) < expectBlocks {
  327. select {
  328. case pull := <-pullChan:
  329. pulls = append(pulls, pull)
  330. case <-timeout:
  331. t.Fatalf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  332. }
  333. }
  334. finish := <-finisherChan
  335. select {
  336. case <-pullChan:
  337. t.Fatal("Pull channel has data to be read")
  338. case <-finisherChan:
  339. t.Fatal("Finisher channel has data to be read")
  340. default:
  341. }
  342. cleanupSharedPullerState(finish)
  343. if err := ffs.Remove(tempFile); err != nil {
  344. t.Fatal(err)
  345. }
  346. // Test 2 - using weak hash, expectPulls blocks pulled.
  347. fo.WeakHashThresholdPct = -1
  348. fo.handleFile(desiredFile, fo.fset.Snapshot(), copyChan)
  349. pulls = pulls[:0]
  350. for len(pulls) < expectPulls {
  351. select {
  352. case pull := <-pullChan:
  353. pulls = append(pulls, pull)
  354. case <-time.After(10 * time.Second):
  355. t.Fatalf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  356. }
  357. }
  358. finish = <-finisherChan
  359. cleanupSharedPullerState(finish)
  360. expectShifted := expectBlocks - expectPulls
  361. if finish.copyOriginShifted != expectShifted {
  362. t.Errorf("did not copy %d shifted", expectShifted)
  363. }
  364. }
  365. // Test that updating a file removes its old blocks from the blockmap
  366. func TestCopierCleanup(t *testing.T) {
  367. iterFn := func(folder, file string, index int32) bool {
  368. return true
  369. }
  370. // Create a file
  371. file := setupFile("test", []int{0})
  372. file.Size = 1
  373. m, f, wcfgCancel := setupSendReceiveFolder(t, file)
  374. defer cleanupSRFolder(f, m, wcfgCancel)
  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, wcfgCancel := setupSendReceiveFolder(t)
  399. defer cleanupSRFolder(f, m, wcfgCancel)
  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, 1)
  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. var toPull pullBlockState
  426. select {
  427. case toPull = <-pullChan:
  428. case <-time.After(10 * time.Second):
  429. t.Fatal("timed out")
  430. }
  431. // Unblock copier
  432. go func() {
  433. for range pullChan {
  434. }
  435. }()
  436. // Close the file, causing errors on further access
  437. toPull.sharedPullerState.fail(os.ErrNotExist)
  438. select {
  439. case state := <-finisherBufferChan:
  440. // At this point the file should still be registered with both the job
  441. // queue, and the progress emitter. Verify this.
  442. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  443. t.Fatal("Could not find file")
  444. }
  445. // Pass the file down the real finisher, and give it time to consume
  446. finisherChan <- state
  447. t0 := time.Now()
  448. if ev, err := s.Poll(time.Minute); err != nil {
  449. t.Fatal("Got error waiting for ItemFinished event:", err)
  450. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  451. t.Fatal("Got ItemFinished event for wrong file:", n)
  452. }
  453. t.Log("event took", time.Since(t0))
  454. state.mut.Lock()
  455. stateWriter := state.writer
  456. state.mut.Unlock()
  457. if stateWriter != nil {
  458. t.Fatal("File not closed?")
  459. }
  460. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  461. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  462. }
  463. // Doing it again should have no effect
  464. finisherChan <- state
  465. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  466. t.Fatal("Expected timeout, not another event", err)
  467. }
  468. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  469. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  470. }
  471. case <-time.After(5 * time.Second):
  472. t.Fatal("Didn't get anything to the finisher")
  473. }
  474. }
  475. func TestDeregisterOnFailInPull(t *testing.T) {
  476. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  477. m, f, wcfgCancel := setupSendReceiveFolder(t)
  478. defer cleanupSRFolder(f, m, wcfgCancel)
  479. // Set up our evet subscription early
  480. s := m.evLogger.Subscribe(events.ItemFinished)
  481. // queue.Done should be called by the finisher routine
  482. f.queue.Push("filex", 0, time.Time{})
  483. f.queue.Pop()
  484. if f.queue.lenProgress() != 1 {
  485. t.Fatal("Expected file in progress")
  486. }
  487. pullChan := make(chan pullBlockState)
  488. finisherBufferChan := make(chan *sharedPullerState)
  489. finisherChan := make(chan *sharedPullerState)
  490. dbUpdateChan := make(chan dbUpdateJob, 1)
  491. snap := f.fset.Snapshot()
  492. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  493. pullWg := sync.NewWaitGroup()
  494. pullWg.Add(1)
  495. go func() {
  496. f.pullerRoutine(pullChan, finisherBufferChan)
  497. pullWg.Done()
  498. }()
  499. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, make(chan string))
  500. defer func() {
  501. // Unblock copier and puller
  502. go func() {
  503. for range finisherBufferChan {
  504. }
  505. }()
  506. close(copyChan)
  507. copyWg.Wait()
  508. close(pullChan)
  509. pullWg.Wait()
  510. close(finisherBufferChan)
  511. close(finisherChan)
  512. }()
  513. f.handleFile(file, snap, copyChan)
  514. // Receive at finisher, we should error out as puller has nowhere to pull
  515. // from.
  516. timeout = time.Second
  517. // Both the puller and copier may send to the finisherBufferChan.
  518. var state *sharedPullerState
  519. after := time.After(5 * time.Second)
  520. for {
  521. select {
  522. case state = <-finisherBufferChan:
  523. case <-after:
  524. t.Fatal("Didn't get failed state to the finisher")
  525. }
  526. if state.failed() != nil {
  527. break
  528. }
  529. }
  530. // At this point the file should still be registered with both the job
  531. // queue, and the progress emitter. Verify this.
  532. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  533. t.Fatal("Could not find file")
  534. }
  535. // Pass the file down the real finisher, and give it time to consume
  536. finisherChan <- state
  537. t0 := time.Now()
  538. if ev, err := s.Poll(time.Minute); err != nil {
  539. t.Fatal("Got error waiting for ItemFinished event:", err)
  540. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  541. t.Fatal("Got ItemFinished event for wrong file:", n)
  542. }
  543. t.Log("event took", time.Since(t0))
  544. state.mut.Lock()
  545. stateWriter := state.writer
  546. state.mut.Unlock()
  547. if stateWriter != nil {
  548. t.Fatal("File not closed?")
  549. }
  550. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  551. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  552. }
  553. // Doing it again should have no effect
  554. finisherChan <- state
  555. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  556. t.Fatal("Expected timeout, not another event", err)
  557. }
  558. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  559. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  560. }
  561. }
  562. func TestIssue3164(t *testing.T) {
  563. m, f, wcfgCancel := setupSendReceiveFolder(t)
  564. defer cleanupSRFolder(f, m, wcfgCancel)
  565. ffs := f.Filesystem()
  566. tmpDir := ffs.URI()
  567. ignDir := filepath.Join("issue3164", "oktodelete")
  568. subDir := filepath.Join(ignDir, "foobar")
  569. must(t, ffs.MkdirAll(subDir, 0777))
  570. must(t, ioutil.WriteFile(filepath.Join(tmpDir, subDir, "file"), []byte("Hello"), 0644))
  571. must(t, ioutil.WriteFile(filepath.Join(tmpDir, ignDir, "file"), []byte("Hello"), 0644))
  572. file := protocol.FileInfo{
  573. Name: "issue3164",
  574. }
  575. must(t, f.scanSubdirs(nil))
  576. matcher := ignore.New(ffs)
  577. must(t, matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""))
  578. f.ignores = matcher
  579. dbUpdateChan := make(chan dbUpdateJob, 1)
  580. f.deleteDir(file, f.fset.Snapshot(), dbUpdateChan, make(chan string))
  581. if _, err := ffs.Stat("issue3164"); !fs.IsNotExist(err) {
  582. t.Fatal(err)
  583. }
  584. }
  585. func TestDiff(t *testing.T) {
  586. for i, test := range diffTestData {
  587. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  588. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  589. _, d := blockDiff(a, b)
  590. if len(d) != len(test.d) {
  591. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  592. } else {
  593. for j := range test.d {
  594. if d[j].Offset != test.d[j].Offset {
  595. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  596. }
  597. if d[j].Size != test.d[j].Size {
  598. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  599. }
  600. }
  601. }
  602. }
  603. }
  604. func BenchmarkDiff(b *testing.B) {
  605. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  606. for _, test := range diffTestData {
  607. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  608. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  609. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{a, b})
  610. }
  611. b.ReportAllocs()
  612. b.ResetTimer()
  613. for i := 0; i < b.N; i++ {
  614. for _, tc := range testCases {
  615. blockDiff(tc.a, tc.b)
  616. }
  617. }
  618. }
  619. func TestDiffEmpty(t *testing.T) {
  620. emptyCases := []struct {
  621. a []protocol.BlockInfo
  622. b []protocol.BlockInfo
  623. need int
  624. have int
  625. }{
  626. {nil, nil, 0, 0},
  627. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  628. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  629. }
  630. for _, emptyCase := range emptyCases {
  631. h, n := blockDiff(emptyCase.a, emptyCase.b)
  632. if len(h) != emptyCase.have {
  633. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  634. }
  635. if len(n) != emptyCase.need {
  636. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  637. }
  638. }
  639. }
  640. // TestDeleteIgnorePerms checks, that a file gets deleted when the IgnorePerms
  641. // option is true and the permissions do not match between the file on disk and
  642. // in the db.
  643. func TestDeleteIgnorePerms(t *testing.T) {
  644. m, f, wcfgCancel := setupSendReceiveFolder(t)
  645. defer cleanupSRFolder(f, m, wcfgCancel)
  646. ffs := f.Filesystem()
  647. f.IgnorePerms = true
  648. name := "deleteIgnorePerms"
  649. file, err := ffs.Create(name)
  650. if err != nil {
  651. t.Error(err)
  652. }
  653. defer file.Close()
  654. stat, err := file.Stat()
  655. must(t, err)
  656. fi, err := scanner.CreateFileInfo(stat, name, ffs)
  657. must(t, err)
  658. ffs.Chmod(name, 0600)
  659. scanChan := make(chan string, 1)
  660. err = f.checkToBeDeleted(fi, fi, true, scanChan)
  661. must(t, err)
  662. }
  663. func TestCopyOwner(t *testing.T) {
  664. // Verifies that owner and group are copied from the parent, for both
  665. // files and directories.
  666. if runtime.GOOS == "windows" {
  667. t.Skip("copying owner not supported on Windows")
  668. }
  669. const (
  670. expOwner = 1234
  671. expGroup = 5678
  672. )
  673. // Set up a folder with the CopyParentOwner bit and backed by a fake
  674. // filesystem.
  675. m, f, wcfgCancel := setupSendReceiveFolder(t)
  676. defer cleanupSRFolder(f, m, wcfgCancel)
  677. f.folder.FolderConfiguration = newFolderConfiguration(m.cfg, f.ID, f.Label, fs.FilesystemTypeFake, "/TestCopyOwner")
  678. f.folder.FolderConfiguration.CopyOwnershipFromParent = true
  679. f.fset = newFileSet(t, f.ID, f.Filesystem(), m.db)
  680. f.mtimefs = f.fset.MtimeFS()
  681. // Create a parent dir with a certain owner/group.
  682. f.mtimefs.Mkdir("foo", 0755)
  683. f.mtimefs.Lchown("foo", expOwner, expGroup)
  684. dir := protocol.FileInfo{
  685. Name: "foo/bar",
  686. Type: protocol.FileInfoTypeDirectory,
  687. Permissions: 0755,
  688. }
  689. // Have the folder create a subdirectory, verify that it's the correct
  690. // owner/group.
  691. dbUpdateChan := make(chan dbUpdateJob, 1)
  692. scanChan := make(chan string)
  693. defer close(dbUpdateChan)
  694. f.handleDir(dir, f.fset.Snapshot(), dbUpdateChan, scanChan)
  695. select {
  696. case <-dbUpdateChan: // empty the channel for later
  697. case toScan := <-scanChan:
  698. t.Fatal("Unexpected receive on scanChan:", toScan)
  699. }
  700. info, err := f.mtimefs.Lstat("foo/bar")
  701. if err != nil {
  702. t.Fatal("Unexpected error (dir):", err)
  703. }
  704. if info.Owner() != expOwner || info.Group() != expGroup {
  705. t.Fatalf("Expected dir owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  706. }
  707. // Have the folder create a file, verify it's the correct owner/group.
  708. // File is zero sized to avoid having to handle copies/pulls.
  709. file := protocol.FileInfo{
  710. Name: "foo/bar/baz",
  711. Type: protocol.FileInfoTypeFile,
  712. Permissions: 0644,
  713. }
  714. // Wire some stuff. The flow here is handleFile() -[copierChan]->
  715. // copierRoutine() -[finisherChan]-> finisherRoutine() -[dbUpdateChan]->
  716. // back to us and we're done. The copier routine doesn't do anything,
  717. // but it's the way data is passed around. When the database update
  718. // comes the finisher is done.
  719. snap := f.fset.Snapshot()
  720. finisherChan := make(chan *sharedPullerState)
  721. copierChan, copyWg := startCopier(f, nil, finisherChan)
  722. go f.finisherRoutine(snap, finisherChan, dbUpdateChan, nil)
  723. defer func() {
  724. close(copierChan)
  725. copyWg.Wait()
  726. close(finisherChan)
  727. }()
  728. f.handleFile(file, snap, copierChan)
  729. <-dbUpdateChan
  730. info, err = f.mtimefs.Lstat("foo/bar/baz")
  731. if err != nil {
  732. t.Fatal("Unexpected error (file):", err)
  733. }
  734. if info.Owner() != expOwner || info.Group() != expGroup {
  735. t.Fatalf("Expected file owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  736. }
  737. // Have the folder create a symlink. Verify it accordingly.
  738. symlink := protocol.FileInfo{
  739. Name: "foo/bar/sym",
  740. Type: protocol.FileInfoTypeSymlink,
  741. Permissions: 0644,
  742. SymlinkTarget: "over the rainbow",
  743. }
  744. f.handleSymlink(symlink, snap, dbUpdateChan, scanChan)
  745. select {
  746. case <-dbUpdateChan:
  747. case toScan := <-scanChan:
  748. t.Fatal("Unexpected receive on scanChan:", toScan)
  749. }
  750. info, err = f.mtimefs.Lstat("foo/bar/sym")
  751. if err != nil {
  752. t.Fatal("Unexpected error (file):", err)
  753. }
  754. if info.Owner() != expOwner || info.Group() != expGroup {
  755. t.Fatalf("Expected symlink owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  756. }
  757. }
  758. // TestSRConflictReplaceFileByDir checks that a conflict is created when an existing file
  759. // is replaced with a directory and versions are conflicting
  760. func TestSRConflictReplaceFileByDir(t *testing.T) {
  761. m, f, wcfgCancel := setupSendReceiveFolder(t)
  762. defer cleanupSRFolder(f, m, wcfgCancel)
  763. ffs := f.Filesystem()
  764. name := "foo"
  765. // create local file
  766. file := createFile(t, name, ffs)
  767. file.Version = protocol.Vector{}.Update(myID.Short())
  768. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  769. // Simulate remote creating a dir with the same name
  770. file.Type = protocol.FileInfoTypeDirectory
  771. rem := device1.Short()
  772. file.Version = protocol.Vector{}.Update(rem)
  773. file.ModifiedBy = rem
  774. dbUpdateChan := make(chan dbUpdateJob, 1)
  775. scanChan := make(chan string, 1)
  776. f.handleDir(file, f.fset.Snapshot(), dbUpdateChan, scanChan)
  777. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  778. t.Fatal("Expected one conflict, got", len(confls))
  779. } else if scan := <-scanChan; confls[0] != scan {
  780. t.Fatal("Expected request to scan", confls[0], "got", scan)
  781. }
  782. }
  783. // TestSRConflictReplaceFileByLink checks that a conflict is created when an existing file
  784. // is replaced with a link and versions are conflicting
  785. func TestSRConflictReplaceFileByLink(t *testing.T) {
  786. m, f, wcfgCancel := setupSendReceiveFolder(t)
  787. defer cleanupSRFolder(f, m, wcfgCancel)
  788. ffs := f.Filesystem()
  789. name := "foo"
  790. // create local file
  791. file := createFile(t, name, ffs)
  792. file.Version = protocol.Vector{}.Update(myID.Short())
  793. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  794. // Simulate remote creating a symlink with the same name
  795. file.Type = protocol.FileInfoTypeSymlink
  796. file.SymlinkTarget = "bar"
  797. rem := device1.Short()
  798. file.Version = protocol.Vector{}.Update(rem)
  799. file.ModifiedBy = rem
  800. dbUpdateChan := make(chan dbUpdateJob, 1)
  801. scanChan := make(chan string, 1)
  802. f.handleSymlink(file, f.fset.Snapshot(), dbUpdateChan, scanChan)
  803. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  804. t.Fatal("Expected one conflict, got", len(confls))
  805. } else if scan := <-scanChan; confls[0] != scan {
  806. t.Fatal("Expected request to scan", confls[0], "got", scan)
  807. }
  808. }
  809. // TestDeleteBehindSymlink checks that we don't delete or schedule a scan
  810. // when trying to delete a file behind a symlink.
  811. func TestDeleteBehindSymlink(t *testing.T) {
  812. m, f, wcfgCancel := setupSendReceiveFolder(t)
  813. defer cleanupSRFolder(f, m, wcfgCancel)
  814. ffs := f.Filesystem()
  815. destDir := createTmpDir()
  816. defer os.RemoveAll(destDir)
  817. destFs := fs.NewFilesystem(fs.FilesystemTypeBasic, destDir)
  818. link := "link"
  819. file := filepath.Join(link, "file")
  820. must(t, ffs.MkdirAll(link, 0755))
  821. fi := createFile(t, file, ffs)
  822. f.updateLocalsFromScanning([]protocol.FileInfo{fi})
  823. must(t, osutil.RenameOrCopy(fs.CopyRangeMethodStandard, ffs, destFs, file, "file"))
  824. must(t, ffs.RemoveAll(link))
  825. if err := fs.DebugSymlinkForTestsOnly(destFs, ffs, "", link); err != nil {
  826. if runtime.GOOS == "windows" {
  827. // Probably we require permissions we don't have.
  828. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  829. } else {
  830. t.Fatal(err)
  831. }
  832. }
  833. fi.Deleted = true
  834. fi.Version = fi.Version.Update(device1.Short())
  835. scanChan := make(chan string, 1)
  836. dbUpdateChan := make(chan dbUpdateJob, 1)
  837. f.deleteFile(fi, f.fset.Snapshot(), dbUpdateChan, scanChan)
  838. select {
  839. case f := <-scanChan:
  840. t.Fatalf("Received %v on scanChan", f)
  841. case u := <-dbUpdateChan:
  842. if u.jobType != dbUpdateDeleteFile {
  843. t.Errorf("Expected jobType %v, got %v", dbUpdateDeleteFile, u.jobType)
  844. }
  845. if u.file.Name != fi.Name {
  846. t.Errorf("Expected update for %v, got %v", fi.Name, u.file.Name)
  847. }
  848. default:
  849. t.Fatalf("No db update received")
  850. }
  851. if _, err := destFs.Stat("file"); err != nil {
  852. t.Errorf("Expected no error when stating file behind symlink, got %v", err)
  853. }
  854. }
  855. // Reproduces https://github.com/syncthing/syncthing/issues/6559
  856. func TestPullCtxCancel(t *testing.T) {
  857. m, f, wcfgCancel := setupSendReceiveFolder(t)
  858. defer cleanupSRFolder(f, m, wcfgCancel)
  859. pullChan := make(chan pullBlockState)
  860. finisherChan := make(chan *sharedPullerState)
  861. var cancel context.CancelFunc
  862. f.ctx, cancel = context.WithCancel(context.Background())
  863. go f.pullerRoutine(pullChan, finisherChan)
  864. defer close(pullChan)
  865. emptyState := func() pullBlockState {
  866. return pullBlockState{
  867. sharedPullerState: newSharedPullerState(protocol.FileInfo{}, nil, f.folderID, "", nil, nil, false, false, protocol.FileInfo{}, false, false),
  868. block: protocol.BlockInfo{},
  869. }
  870. }
  871. cancel()
  872. done := make(chan struct{})
  873. defer close(done)
  874. for i := 0; i < 2; i++ {
  875. go func() {
  876. select {
  877. case pullChan <- emptyState():
  878. case <-done:
  879. }
  880. }()
  881. select {
  882. case s := <-finisherChan:
  883. if s.failed() == nil {
  884. t.Errorf("state %v not failed", i)
  885. }
  886. case <-time.After(5 * time.Second):
  887. t.Fatalf("timed out before receiving state %v on finisherChan", i)
  888. }
  889. }
  890. }
  891. func TestPullDeleteUnscannedDir(t *testing.T) {
  892. m, f, wcfgCancel := setupSendReceiveFolder(t)
  893. defer cleanupSRFolder(f, m, wcfgCancel)
  894. ffs := f.Filesystem()
  895. dir := "foobar"
  896. must(t, ffs.MkdirAll(dir, 0777))
  897. fi := protocol.FileInfo{
  898. Name: dir,
  899. }
  900. scanChan := make(chan string, 1)
  901. dbUpdateChan := make(chan dbUpdateJob, 1)
  902. f.deleteDir(fi, f.fset.Snapshot(), dbUpdateChan, scanChan)
  903. if _, err := ffs.Stat(dir); fs.IsNotExist(err) {
  904. t.Error("directory has been deleted")
  905. }
  906. select {
  907. case toScan := <-scanChan:
  908. if toScan != dir {
  909. t.Errorf("expected %v to be scanned, got %v", dir, toScan)
  910. }
  911. default:
  912. t.Error("nothing was scheduled for scanning")
  913. }
  914. }
  915. func TestPullCaseOnlyPerformFinish(t *testing.T) {
  916. m, f, wcfgCancel := setupSendReceiveFolder(t)
  917. defer cleanupSRFolder(f, m, wcfgCancel)
  918. ffs := f.Filesystem()
  919. name := "foo"
  920. contents := []byte("contents")
  921. must(t, writeFile(ffs, name, contents, 0644))
  922. must(t, f.scanSubdirs(nil))
  923. var cur protocol.FileInfo
  924. hasCur := false
  925. snap := dbSnapshot(t, m, f.ID)
  926. defer snap.Release()
  927. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileIntf) bool {
  928. if hasCur {
  929. t.Fatal("got more than one file")
  930. }
  931. cur = i.(protocol.FileInfo)
  932. hasCur = true
  933. return true
  934. })
  935. if !hasCur {
  936. t.Fatal("file is missing")
  937. }
  938. remote := *(&cur)
  939. remote.Version = protocol.Vector{}.Update(device1.Short())
  940. remote.Name = strings.ToUpper(cur.Name)
  941. temp := fs.TempName(remote.Name)
  942. must(t, writeFile(ffs, temp, contents, 0644))
  943. scanChan := make(chan string, 1)
  944. dbUpdateChan := make(chan dbUpdateJob, 1)
  945. err := f.performFinish(remote, cur, hasCur, temp, snap, dbUpdateChan, scanChan)
  946. select {
  947. case <-dbUpdateChan: // boring case sensitive filesystem
  948. return
  949. case <-scanChan:
  950. t.Error("no need to scan anything here")
  951. default:
  952. }
  953. var caseErr *fs.ErrCaseConflict
  954. if !errors.As(err, &caseErr) {
  955. t.Error("Expected case conflict error, got", err)
  956. }
  957. }
  958. func TestPullCaseOnlyDir(t *testing.T) {
  959. testPullCaseOnlyDirOrSymlink(t, true)
  960. }
  961. func TestPullCaseOnlySymlink(t *testing.T) {
  962. if runtime.GOOS == "windows" {
  963. t.Skip("symlinks not supported on windows")
  964. }
  965. testPullCaseOnlyDirOrSymlink(t, false)
  966. }
  967. func testPullCaseOnlyDirOrSymlink(t *testing.T, dir bool) {
  968. m, f, wcfgCancel := setupSendReceiveFolder(t)
  969. defer cleanupSRFolder(f, m, wcfgCancel)
  970. ffs := f.Filesystem()
  971. name := "foo"
  972. if dir {
  973. must(t, ffs.Mkdir(name, 0777))
  974. } else {
  975. must(t, ffs.CreateSymlink("target", name))
  976. }
  977. must(t, f.scanSubdirs(nil))
  978. var cur protocol.FileInfo
  979. hasCur := false
  980. snap := dbSnapshot(t, m, f.ID)
  981. defer snap.Release()
  982. snap.WithHave(protocol.LocalDeviceID, func(i protocol.FileIntf) bool {
  983. if hasCur {
  984. t.Fatal("got more than one file")
  985. }
  986. cur = i.(protocol.FileInfo)
  987. hasCur = true
  988. return true
  989. })
  990. if !hasCur {
  991. t.Fatal("file is missing")
  992. }
  993. scanChan := make(chan string, 1)
  994. dbUpdateChan := make(chan dbUpdateJob, 1)
  995. remote := *(&cur)
  996. remote.Version = protocol.Vector{}.Update(device1.Short())
  997. remote.Name = strings.ToUpper(cur.Name)
  998. if dir {
  999. f.handleDir(remote, snap, dbUpdateChan, scanChan)
  1000. } else {
  1001. f.handleSymlink(remote, snap, dbUpdateChan, scanChan)
  1002. }
  1003. select {
  1004. case <-dbUpdateChan: // boring case sensitive filesystem
  1005. return
  1006. case <-scanChan:
  1007. t.Error("no need to scan anything here")
  1008. default:
  1009. }
  1010. if errStr, ok := f.tempPullErrors[remote.Name]; !ok {
  1011. t.Error("missing error for", remote.Name)
  1012. } else if !strings.Contains(errStr, "differs from name") {
  1013. t.Error("unexpected error", errStr, "for", remote.Name)
  1014. }
  1015. }
  1016. func TestPullTempFileCaseConflict(t *testing.T) {
  1017. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1018. defer cleanupSRFolder(f, m, wcfgCancel)
  1019. copyChan := make(chan copyBlocksState, 1)
  1020. file := protocol.FileInfo{Name: "foo"}
  1021. confl := "Foo"
  1022. tempNameConfl := fs.TempName(confl)
  1023. if fd, err := f.mtimefs.Create(tempNameConfl); err != nil {
  1024. t.Fatal(err)
  1025. } else {
  1026. if _, err := fd.Write([]byte("data")); err != nil {
  1027. t.Fatal(err)
  1028. }
  1029. fd.Close()
  1030. }
  1031. f.handleFile(file, f.fset.Snapshot(), copyChan)
  1032. cs := <-copyChan
  1033. if _, err := cs.tempFile(); err != nil {
  1034. t.Error(err)
  1035. }
  1036. }
  1037. func TestPullCaseOnlyRename(t *testing.T) {
  1038. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1039. defer cleanupSRFolder(f, m, wcfgCancel)
  1040. // tempNameConfl := fs.TempName(confl)
  1041. name := "foo"
  1042. if fd, err := f.mtimefs.Create(name); err != nil {
  1043. t.Fatal(err)
  1044. } else {
  1045. if _, err := fd.Write([]byte("data")); err != nil {
  1046. t.Fatal(err)
  1047. }
  1048. fd.Close()
  1049. }
  1050. must(t, f.scanSubdirs(nil))
  1051. cur, ok := m.CurrentFolderFile(f.ID, name)
  1052. if !ok {
  1053. t.Fatal("file missing")
  1054. }
  1055. deleted := cur
  1056. deleted.SetDeleted(myID.Short())
  1057. confl := cur
  1058. confl.Name = "Foo"
  1059. confl.Version = confl.Version.Update(device1.Short())
  1060. dbUpdateChan := make(chan dbUpdateJob, 2)
  1061. scanChan := make(chan string, 2)
  1062. snap := f.fset.Snapshot()
  1063. defer snap.Release()
  1064. if err := f.renameFile(cur, deleted, confl, snap, dbUpdateChan, scanChan); err != nil {
  1065. t.Error(err)
  1066. }
  1067. }
  1068. func TestPullSymlinkOverExistingWindows(t *testing.T) {
  1069. if runtime.GOOS != "windows" {
  1070. t.Skip()
  1071. }
  1072. m, f, wcfgCancel := setupSendReceiveFolder(t)
  1073. defer cleanupSRFolder(f, m, wcfgCancel)
  1074. name := "foo"
  1075. if fd, err := f.mtimefs.Create(name); err != nil {
  1076. t.Fatal(err)
  1077. } else {
  1078. if _, err := fd.Write([]byte("data")); err != nil {
  1079. t.Fatal(err)
  1080. }
  1081. fd.Close()
  1082. }
  1083. must(t, f.scanSubdirs(nil))
  1084. file, ok := m.CurrentFolderFile(f.ID, name)
  1085. if !ok {
  1086. t.Fatal("file missing")
  1087. }
  1088. m.Index(device1, f.ID, []protocol.FileInfo{{Name: name, Type: protocol.FileInfoTypeSymlink, Version: file.Version.Update(device1.Short())}})
  1089. scanChan := make(chan string)
  1090. changed := f.pullerIteration(scanChan)
  1091. if changed != 1 {
  1092. t.Error("Expected one change in pull, got", changed)
  1093. }
  1094. if file, ok := m.CurrentFolderFile(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 := f.fset.Snapshot()
  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, f.fset.Snapshot(), 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. }