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