folder_sendrecv_test.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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/internal/itererr"
  20. "github.com/syncthing/syncthing/lib/build"
  21. "github.com/syncthing/syncthing/lib/config"
  22. "github.com/syncthing/syncthing/lib/events"
  23. "github.com/syncthing/syncthing/lib/fs"
  24. "github.com/syncthing/syncthing/lib/ignore"
  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. 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. r, _ := model.folderRunners.Get(fcfg.ID)
  109. f := r.(*sendReceiveFolder)
  110. f.tempPullErrors = make(map[string]string)
  111. f.ctx = context.Background()
  112. // Update index
  113. if files != nil {
  114. f.updateLocalsFromScanning(files)
  115. }
  116. return model, f, wCancel
  117. }
  118. // Layout of the files: (indexes from the above array)
  119. // 12345678 - Required file
  120. // 02005008 - Existing file (currently in the index)
  121. // 02340070 - Temp file on the disk
  122. func TestHandleFile(t *testing.T) {
  123. // After the diff between required and existing we should:
  124. // Copy: 2, 5, 8
  125. // Pull: 1, 3, 4, 6, 7
  126. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  127. existingFile := setupFile("filex", existingBlocks)
  128. requiredFile := existingFile
  129. requiredFile.Blocks = blocks[1:]
  130. _, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  131. defer wcfgCancel()
  132. copyChan := make(chan copyBlocksState, 1)
  133. f.handleFile(requiredFile, copyChan)
  134. // Receive the results
  135. toCopy := <-copyChan
  136. if len(toCopy.blocks) != 8 {
  137. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  138. }
  139. for _, block := range blocks[1:] {
  140. found := false
  141. for _, toCopyBlock := range toCopy.blocks {
  142. if bytes.Equal(toCopyBlock.Hash, block.Hash) {
  143. found = true
  144. break
  145. }
  146. }
  147. if !found {
  148. t.Errorf("Did not find block %s", block.String())
  149. }
  150. }
  151. }
  152. func TestHandleFileWithTemp(t *testing.T) {
  153. // After diff between required and existing we should:
  154. // Copy: 2, 5, 8
  155. // Pull: 1, 3, 4, 6, 7
  156. // After dropping out blocks already on the temp file we should:
  157. // Copy: 5, 8
  158. // Pull: 1, 6
  159. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  160. existingFile := setupFile("file", existingBlocks)
  161. requiredFile := existingFile
  162. requiredFile.Blocks = blocks[1:]
  163. _, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  164. defer wcfgCancel()
  165. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  166. t.Fatal(err)
  167. }
  168. copyChan := make(chan copyBlocksState, 1)
  169. f.handleFile(requiredFile, copyChan)
  170. // Receive the results
  171. toCopy := <-copyChan
  172. if len(toCopy.blocks) != 4 {
  173. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  174. }
  175. for _, idx := range []int{1, 5, 6, 8} {
  176. found := false
  177. block := blocks[idx]
  178. for _, toCopyBlock := range toCopy.blocks {
  179. if bytes.Equal(toCopyBlock.Hash, block.Hash) {
  180. found = true
  181. break
  182. }
  183. }
  184. if !found {
  185. t.Errorf("Did not find block %s", block.String())
  186. }
  187. }
  188. }
  189. func TestCopierFinder(t *testing.T) {
  190. // After diff between required and existing we should:
  191. // Copy: 1, 2, 3, 4, 6, 7, 8
  192. // Since there is no existing file, nor a temp file
  193. // After dropping out blocks found locally:
  194. // Pull: 1, 5, 6, 8
  195. tempFile := fs.TempName("file2")
  196. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  197. existingFile := setupFile(fs.TempName("file"), existingBlocks)
  198. existingFile.Size = 1
  199. requiredFile := existingFile
  200. requiredFile.Blocks = blocks[1:]
  201. requiredFile.Name = "file2"
  202. _, f, wcfgCancel := setupSendReceiveFolder(t, existingFile)
  203. defer wcfgCancel()
  204. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  205. t.Fatal(err)
  206. }
  207. copyChan := make(chan copyBlocksState)
  208. pullChan := make(chan pullBlockState, 4)
  209. finisherChan := make(chan *sharedPullerState, 1)
  210. // Run a single fetcher routine
  211. go f.copierRoutine(copyChan, pullChan, finisherChan)
  212. defer close(copyChan)
  213. f.handleFile(requiredFile, copyChan)
  214. timeout := time.After(10 * time.Second)
  215. pulls := make([]pullBlockState, 4)
  216. for i := 0; i < 4; i++ {
  217. select {
  218. case pulls[i] = <-pullChan:
  219. case <-timeout:
  220. t.Fatalf("Timed out before receiving all 4 states on pullChan (already got %v)", i)
  221. }
  222. }
  223. var finish *sharedPullerState
  224. select {
  225. case finish = <-finisherChan:
  226. case <-timeout:
  227. t.Fatal("Timed out before receiving 4 states on pullChan")
  228. }
  229. defer cleanupSharedPullerState(finish)
  230. select {
  231. case v := <-pullChan:
  232. t.Logf("%+v\n", v)
  233. t.Fatal("Pull channel had data to be read")
  234. case <-finisherChan:
  235. t.Fatal("Finisher channel has data to be read")
  236. default:
  237. }
  238. // Verify that the right blocks went into the pull list.
  239. // They are pulled in random order.
  240. for _, idx := range []int{1, 5, 6, 8} {
  241. found := false
  242. block := blocks[idx]
  243. for _, pulledBlock := range pulls {
  244. if bytes.Equal(pulledBlock.block.Hash, block.Hash) {
  245. found = true
  246. break
  247. }
  248. }
  249. if !found {
  250. t.Errorf("Did not find block %s", block.String())
  251. }
  252. if !bytes.Equal(finish.file.Blocks[idx-1].Hash, blocks[idx].Hash) {
  253. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  254. }
  255. }
  256. // Verify that the fetched blocks have actually been written to the temp file
  257. blks, err := scanner.HashFile(context.TODO(), f.ID, f.Filesystem(), tempFile, protocol.MinBlockSize, nil)
  258. if err != nil {
  259. t.Log(err)
  260. }
  261. for _, eq := range []int{2, 3, 4, 7} {
  262. if !bytes.Equal(blks[eq-1].Hash, blocks[eq].Hash) {
  263. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  264. }
  265. }
  266. }
  267. // Test that updating a file removes its old blocks from the blockmap
  268. func TestCopierCleanup(t *testing.T) {
  269. // Create a file
  270. file := setupFile("test", []int{0})
  271. file.Size = 1
  272. m, f, wcfgCancel := setupSendReceiveFolder(t, file)
  273. defer wcfgCancel()
  274. file.Blocks = []protocol.BlockInfo{blocks[1]}
  275. file.Version = file.Version.Update(myID.Short())
  276. // Update index (removing old blocks)
  277. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  278. if vals, err := itererr.Collect(m.sdb.AllLocalBlocksWithHash(blocks[0].Hash)); err != nil || len(vals) > 0 {
  279. t.Error("Unexpected block found")
  280. }
  281. if vals, err := itererr.Collect(m.sdb.AllLocalBlocksWithHash(blocks[1].Hash)); err != nil || len(vals) == 0 {
  282. t.Error("Expected block not found")
  283. }
  284. file.Blocks = []protocol.BlockInfo{blocks[0]}
  285. file.Version = file.Version.Update(myID.Short())
  286. // Update index (removing old blocks)
  287. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  288. if vals, err := itererr.Collect(m.sdb.AllLocalBlocksWithHash(blocks[0].Hash)); err != nil || len(vals) == 0 {
  289. t.Error("Unexpected block found")
  290. }
  291. if vals, err := itererr.Collect(m.sdb.AllLocalBlocksWithHash(blocks[1].Hash)); err != nil || len(vals) > 0 {
  292. t.Error("Expected block not found")
  293. }
  294. }
  295. func TestDeregisterOnFailInCopy(t *testing.T) {
  296. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  297. m, f, wcfgCancel := setupSendReceiveFolder(t)
  298. defer wcfgCancel()
  299. // Set up our evet subscription early
  300. s := m.evLogger.Subscribe(events.ItemFinished)
  301. // queue.Done should be called by the finisher routine
  302. f.queue.Push("filex", 0, time.Time{})
  303. f.queue.Pop()
  304. if f.queue.lenProgress() != 1 {
  305. t.Fatal("Expected file in progress")
  306. }
  307. pullChan := make(chan pullBlockState)
  308. finisherBufferChan := make(chan *sharedPullerState, 1)
  309. finisherChan := make(chan *sharedPullerState)
  310. dbUpdateChan := make(chan dbUpdateJob, 1)
  311. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  312. go f.finisherRoutine(finisherChan, dbUpdateChan, make(chan string))
  313. defer func() {
  314. close(copyChan)
  315. copyWg.Wait()
  316. close(pullChan)
  317. close(finisherBufferChan)
  318. close(finisherChan)
  319. }()
  320. f.handleFile(file, copyChan)
  321. // Receive a block at puller, to indicate that at least a single copier
  322. // loop has been performed.
  323. var toPull pullBlockState
  324. select {
  325. case toPull = <-pullChan:
  326. case <-time.After(10 * time.Second):
  327. t.Fatal("timed out")
  328. }
  329. // Unblock copier
  330. go func() {
  331. for range pullChan {
  332. }
  333. }()
  334. // Close the file, causing errors on further access
  335. toPull.sharedPullerState.fail(os.ErrNotExist)
  336. select {
  337. case state := <-finisherBufferChan:
  338. // At this point the file should still be registered with both the job
  339. // queue, and the progress emitter. Verify this.
  340. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  341. t.Fatal("Could not find file")
  342. }
  343. // Pass the file down the real finisher, and give it time to consume
  344. finisherChan <- state
  345. t0 := time.Now()
  346. if ev, err := s.Poll(time.Minute); err != nil {
  347. t.Fatal("Got error waiting for ItemFinished event:", err)
  348. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  349. t.Fatal("Got ItemFinished event for wrong file:", n)
  350. }
  351. t.Log("event took", time.Since(t0))
  352. state.mut.Lock()
  353. stateWriter := state.writer
  354. state.mut.Unlock()
  355. if stateWriter != nil {
  356. t.Fatal("File not closed?")
  357. }
  358. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  359. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  360. }
  361. // Doing it again should have no effect
  362. finisherChan <- state
  363. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  364. t.Fatal("Expected timeout, not another event", err)
  365. }
  366. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  367. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  368. }
  369. case <-time.After(5 * time.Second):
  370. t.Fatal("Didn't get anything to the finisher")
  371. }
  372. }
  373. func TestDeregisterOnFailInPull(t *testing.T) {
  374. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  375. m, f, wcfgCancel := setupSendReceiveFolder(t)
  376. defer wcfgCancel()
  377. // Set up our evet subscription early
  378. s := m.evLogger.Subscribe(events.ItemFinished)
  379. // queue.Done should be called by the finisher routine
  380. f.queue.Push("filex", 0, time.Time{})
  381. f.queue.Pop()
  382. if f.queue.lenProgress() != 1 {
  383. t.Fatal("Expected file in progress")
  384. }
  385. pullChan := make(chan pullBlockState)
  386. finisherBufferChan := make(chan *sharedPullerState)
  387. finisherChan := make(chan *sharedPullerState)
  388. dbUpdateChan := make(chan dbUpdateJob, 1)
  389. copyChan, copyWg := startCopier(f, pullChan, finisherBufferChan)
  390. pullWg := sync.NewWaitGroup()
  391. pullWg.Add(1)
  392. go func() {
  393. f.pullerRoutine(pullChan, finisherBufferChan)
  394. pullWg.Done()
  395. }()
  396. go f.finisherRoutine(finisherChan, dbUpdateChan, make(chan string))
  397. defer func() {
  398. // Unblock copier and puller
  399. go func() {
  400. for range finisherBufferChan {
  401. }
  402. }()
  403. close(copyChan)
  404. copyWg.Wait()
  405. close(pullChan)
  406. pullWg.Wait()
  407. close(finisherBufferChan)
  408. close(finisherChan)
  409. }()
  410. f.handleFile(file, copyChan)
  411. // Receive at finisher, we should error out as puller has nowhere to pull
  412. // from.
  413. timeout = time.Second
  414. // Both the puller and copier may send to the finisherBufferChan.
  415. var state *sharedPullerState
  416. after := time.After(5 * time.Second)
  417. for {
  418. select {
  419. case state = <-finisherBufferChan:
  420. case <-after:
  421. t.Fatal("Didn't get failed state to the finisher")
  422. }
  423. if state.failed() != nil {
  424. break
  425. }
  426. }
  427. // At this point the file should still be registered with both the job
  428. // queue, and the progress emitter. Verify this.
  429. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  430. t.Fatal("Could not find file")
  431. }
  432. // Pass the file down the real finisher, and give it time to consume
  433. finisherChan <- state
  434. t0 := time.Now()
  435. if ev, err := s.Poll(time.Minute); err != nil {
  436. t.Fatal("Got error waiting for ItemFinished event:", err)
  437. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  438. t.Fatal("Got ItemFinished event for wrong file:", n)
  439. }
  440. t.Log("event took", time.Since(t0))
  441. state.mut.Lock()
  442. stateWriter := state.writer
  443. state.mut.Unlock()
  444. if stateWriter != nil {
  445. t.Fatal("File not closed?")
  446. }
  447. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  448. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  449. }
  450. // Doing it again should have no effect
  451. finisherChan <- state
  452. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  453. t.Fatal("Expected timeout, not another event", err)
  454. }
  455. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  456. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  457. }
  458. }
  459. func TestIssue3164(t *testing.T) {
  460. _, f, wcfgCancel := setupSendReceiveFolder(t)
  461. defer wcfgCancel()
  462. ffs := f.Filesystem()
  463. ignDir := filepath.Join("issue3164", "oktodelete")
  464. subDir := filepath.Join(ignDir, "foobar")
  465. must(t, ffs.MkdirAll(subDir, 0o777))
  466. must(t, fs.WriteFile(ffs, filepath.Join(subDir, "file"), []byte("Hello"), 0o644))
  467. must(t, fs.WriteFile(ffs, filepath.Join(ignDir, "file"), []byte("Hello"), 0o644))
  468. file := protocol.FileInfo{
  469. Name: "issue3164",
  470. }
  471. must(t, f.scanSubdirs(nil))
  472. matcher := ignore.New(ffs)
  473. must(t, matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""))
  474. f.ignores = matcher
  475. dbUpdateChan := make(chan dbUpdateJob, 1)
  476. f.deleteDir(file, dbUpdateChan, make(chan string))
  477. if _, err := ffs.Stat("issue3164"); !fs.IsNotExist(err) {
  478. t.Fatal(err)
  479. }
  480. }
  481. func TestDiff(t *testing.T) {
  482. for i, test := range diffTestData {
  483. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil)
  484. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil)
  485. _, d := blockDiff(a, b)
  486. if len(d) != len(test.d) {
  487. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  488. } else {
  489. for j := range test.d {
  490. if d[j].Offset != test.d[j].Offset {
  491. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  492. }
  493. if d[j].Size != test.d[j].Size {
  494. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  495. }
  496. }
  497. }
  498. }
  499. }
  500. func BenchmarkDiff(b *testing.B) {
  501. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  502. for _, test := range diffTestData {
  503. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil)
  504. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil)
  505. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{a, b})
  506. }
  507. b.ReportAllocs()
  508. b.ResetTimer()
  509. for i := 0; i < b.N; i++ {
  510. for _, tc := range testCases {
  511. blockDiff(tc.a, tc.b)
  512. }
  513. }
  514. }
  515. func TestDiffEmpty(t *testing.T) {
  516. emptyCases := []struct {
  517. a []protocol.BlockInfo
  518. b []protocol.BlockInfo
  519. need int
  520. have int
  521. }{
  522. {nil, nil, 0, 0},
  523. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  524. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  525. }
  526. for _, emptyCase := range emptyCases {
  527. h, n := blockDiff(emptyCase.a, emptyCase.b)
  528. if len(h) != emptyCase.have {
  529. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  530. }
  531. if len(n) != emptyCase.need {
  532. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  533. }
  534. }
  535. }
  536. // TestDeleteIgnorePerms checks, that a file gets deleted when the IgnorePerms
  537. // option is true and the permissions do not match between the file on disk and
  538. // in the db.
  539. func TestDeleteIgnorePerms(t *testing.T) {
  540. _, f, wcfgCancel := setupSendReceiveFolder(t)
  541. defer wcfgCancel()
  542. ffs := f.Filesystem()
  543. f.IgnorePerms = true
  544. name := "deleteIgnorePerms"
  545. file, err := ffs.Create(name)
  546. if err != nil {
  547. t.Error(err)
  548. }
  549. defer file.Close()
  550. stat, err := file.Stat()
  551. must(t, err)
  552. fi, err := scanner.CreateFileInfo(stat, name, ffs, false, false, config.XattrFilter{})
  553. must(t, err)
  554. ffs.Chmod(name, 0o600)
  555. if info, err := ffs.Stat(name); err == nil {
  556. fi.InodeChangeNs = info.InodeChangeTime().UnixNano()
  557. }
  558. scanChan := make(chan string, 1)
  559. err = f.checkToBeDeleted(fi, fi, true, scanChan)
  560. must(t, err)
  561. }
  562. func TestCopyOwner(t *testing.T) {
  563. // Verifies that owner and group are copied from the parent, for both
  564. // files and directories.
  565. if build.IsWindows {
  566. t.Skip("copying owner not supported on Windows")
  567. }
  568. const (
  569. expOwner = 1234
  570. expGroup = 5678
  571. )
  572. // Set up a folder with the CopyParentOwner bit and backed by a fake
  573. // filesystem.
  574. m, f, wcfgCancel := setupSendReceiveFolder(t)
  575. defer wcfgCancel()
  576. f.folder.FolderConfiguration = newFolderConfiguration(m.cfg, f.ID, f.Label, config.FilesystemTypeFake, "/TestCopyOwner")
  577. f.folder.FolderConfiguration.CopyOwnershipFromParent = true
  578. // Create a parent dir with a certain owner/group.
  579. f.mtimefs.Mkdir("foo", 0o755)
  580. f.mtimefs.Lchown("foo", strconv.Itoa(expOwner), strconv.Itoa(expGroup))
  581. dir := protocol.FileInfo{
  582. Name: "foo/bar",
  583. Type: protocol.FileInfoTypeDirectory,
  584. Permissions: 0o755,
  585. }
  586. // Have the folder create a subdirectory, verify that it's the correct
  587. // owner/group.
  588. dbUpdateChan := make(chan dbUpdateJob, 1)
  589. scanChan := make(chan string)
  590. defer close(dbUpdateChan)
  591. f.handleDir(dir, dbUpdateChan, scanChan)
  592. select {
  593. case <-dbUpdateChan: // empty the channel for later
  594. case toScan := <-scanChan:
  595. t.Fatal("Unexpected receive on scanChan:", toScan)
  596. }
  597. info, err := f.mtimefs.Lstat("foo/bar")
  598. if err != nil {
  599. t.Fatal("Unexpected error (dir):", err)
  600. }
  601. if info.Owner() != expOwner || info.Group() != expGroup {
  602. t.Fatalf("Expected dir owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  603. }
  604. // Have the folder create a file, verify it's the correct owner/group.
  605. // File is zero sized to avoid having to handle copies/pulls.
  606. file := protocol.FileInfo{
  607. Name: "foo/bar/baz",
  608. Type: protocol.FileInfoTypeFile,
  609. Permissions: 0o644,
  610. }
  611. // Wire some stuff. The flow here is handleFile() -[copierChan]->
  612. // copierRoutine() -[finisherChan]-> finisherRoutine() -[dbUpdateChan]->
  613. // back to us and we're done. The copier routine doesn't do anything,
  614. // but it's the way data is passed around. When the database update
  615. // comes the finisher is done.
  616. finisherChan := make(chan *sharedPullerState)
  617. copierChan, copyWg := startCopier(f, nil, finisherChan)
  618. go f.finisherRoutine(finisherChan, dbUpdateChan, nil)
  619. defer func() {
  620. close(copierChan)
  621. copyWg.Wait()
  622. close(finisherChan)
  623. }()
  624. f.handleFile(file, copierChan)
  625. <-dbUpdateChan
  626. info, err = f.mtimefs.Lstat("foo/bar/baz")
  627. if err != nil {
  628. t.Fatal("Unexpected error (file):", err)
  629. }
  630. if info.Owner() != expOwner || info.Group() != expGroup {
  631. t.Fatalf("Expected file owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  632. }
  633. // Have the folder create a symlink. Verify it accordingly.
  634. symlink := protocol.FileInfo{
  635. Name: "foo/bar/sym",
  636. Type: protocol.FileInfoTypeSymlink,
  637. Permissions: 0o644,
  638. SymlinkTarget: []byte("over the rainbow"),
  639. }
  640. f.handleSymlink(symlink, dbUpdateChan, scanChan)
  641. select {
  642. case <-dbUpdateChan:
  643. case toScan := <-scanChan:
  644. t.Fatal("Unexpected receive on scanChan:", toScan)
  645. }
  646. info, err = f.mtimefs.Lstat("foo/bar/sym")
  647. if err != nil {
  648. t.Fatal("Unexpected error (file):", err)
  649. }
  650. if info.Owner() != expOwner || info.Group() != expGroup {
  651. t.Fatalf("Expected symlink owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  652. }
  653. }
  654. // TestSRConflictReplaceFileByDir checks that a conflict is created when an existing file
  655. // is replaced with a directory and versions are conflicting
  656. func TestSRConflictReplaceFileByDir(t *testing.T) {
  657. _, f, wcfgCancel := setupSendReceiveFolder(t)
  658. defer wcfgCancel()
  659. ffs := f.Filesystem()
  660. name := "foo"
  661. // create local file
  662. file := createEmptyFileInfo(t, name, ffs)
  663. file.Version = protocol.Vector{}.Update(myID.Short())
  664. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  665. // Simulate remote creating a dir with the same name
  666. file.Type = protocol.FileInfoTypeDirectory
  667. rem := device1.Short()
  668. file.Version = protocol.Vector{}.Update(rem)
  669. file.ModifiedBy = rem
  670. dbUpdateChan := make(chan dbUpdateJob, 1)
  671. scanChan := make(chan string, 1)
  672. f.handleDir(file, dbUpdateChan, scanChan)
  673. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  674. t.Fatal("Expected one conflict, got", len(confls))
  675. } else if scan := <-scanChan; confls[0] != scan {
  676. t.Fatal("Expected request to scan", confls[0], "got", scan)
  677. }
  678. }
  679. // TestSRConflictReplaceFileByLink checks that a conflict is created when an existing file
  680. // is replaced with a link and versions are conflicting
  681. func TestSRConflictReplaceFileByLink(t *testing.T) {
  682. _, f, wcfgCancel := setupSendReceiveFolder(t)
  683. defer wcfgCancel()
  684. ffs := f.Filesystem()
  685. name := "foo"
  686. // create local file
  687. file := createEmptyFileInfo(t, name, ffs)
  688. file.Version = protocol.Vector{}.Update(myID.Short())
  689. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  690. // Simulate remote creating a symlink with the same name
  691. file.Type = protocol.FileInfoTypeSymlink
  692. file.SymlinkTarget = []byte("bar")
  693. rem := device1.Short()
  694. file.Version = protocol.Vector{}.Update(rem)
  695. file.ModifiedBy = rem
  696. dbUpdateChan := make(chan dbUpdateJob, 1)
  697. scanChan := make(chan string, 1)
  698. f.handleSymlink(file, dbUpdateChan, scanChan)
  699. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  700. t.Fatal("Expected one conflict, got", len(confls))
  701. } else if scan := <-scanChan; confls[0] != scan {
  702. t.Fatal("Expected request to scan", confls[0], "got", scan)
  703. }
  704. }
  705. // TestDeleteBehindSymlink checks that we don't delete or schedule a scan
  706. // when trying to delete a file behind a symlink.
  707. func TestDeleteBehindSymlink(t *testing.T) {
  708. _, f, wcfgCancel := setupSendReceiveFolder(t)
  709. defer wcfgCancel()
  710. ffs := f.Filesystem()
  711. link := "link"
  712. linkFile := filepath.Join(link, "file")
  713. must(t, ffs.MkdirAll(link, 0o755))
  714. fi := createEmptyFileInfo(t, linkFile, ffs)
  715. f.updateLocalsFromScanning([]protocol.FileInfo{fi})
  716. must(t, ffs.Rename(linkFile, "file"))
  717. must(t, ffs.RemoveAll(link))
  718. must(t, ffs.CreateSymlink("/", link))
  719. fi.Deleted = true
  720. fi.Version = fi.Version.Update(device1.Short())
  721. scanChan := make(chan string, 1)
  722. dbUpdateChan := make(chan dbUpdateJob, 1)
  723. f.deleteFile(fi, dbUpdateChan, scanChan)
  724. select {
  725. case f := <-scanChan:
  726. t.Fatalf("Received %v on scanChan", f)
  727. case u := <-dbUpdateChan:
  728. if u.jobType != dbUpdateDeleteFile {
  729. t.Errorf("Expected jobType %v, got %v", dbUpdateDeleteFile, u.jobType)
  730. }
  731. if u.file.Name != fi.Name {
  732. t.Errorf("Expected update for %v, got %v", fi.Name, u.file.Name)
  733. }
  734. default:
  735. t.Fatalf("No db update received")
  736. }
  737. if _, err := ffs.Stat("file"); err != nil {
  738. t.Errorf("Expected no error when stating file behind symlink, got %v", err)
  739. }
  740. }
  741. // Reproduces https://github.com/syncthing/syncthing/issues/6559
  742. func TestPullCtxCancel(t *testing.T) {
  743. _, f, wcfgCancel := setupSendReceiveFolder(t)
  744. defer wcfgCancel()
  745. pullChan := make(chan pullBlockState)
  746. finisherChan := make(chan *sharedPullerState)
  747. var cancel context.CancelFunc
  748. f.ctx, cancel = context.WithCancel(context.Background())
  749. go f.pullerRoutine(pullChan, finisherChan)
  750. defer close(pullChan)
  751. emptyState := func() pullBlockState {
  752. return pullBlockState{
  753. sharedPullerState: newSharedPullerState(protocol.FileInfo{}, nil, f.folderID, "", nil, nil, false, false, protocol.FileInfo{}, false, false),
  754. block: protocol.BlockInfo{},
  755. }
  756. }
  757. cancel()
  758. done := make(chan struct{})
  759. defer close(done)
  760. for i := 0; i < 2; i++ {
  761. go func() {
  762. select {
  763. case pullChan <- emptyState():
  764. case <-done:
  765. }
  766. }()
  767. select {
  768. case s := <-finisherChan:
  769. if s.failed() == nil {
  770. t.Errorf("state %v not failed", i)
  771. }
  772. case <-time.After(5 * time.Second):
  773. t.Fatalf("timed out before receiving state %v on finisherChan", i)
  774. }
  775. }
  776. }
  777. func TestPullDeleteUnscannedDir(t *testing.T) {
  778. _, f, wcfgCancel := setupSendReceiveFolder(t)
  779. defer wcfgCancel()
  780. ffs := f.Filesystem()
  781. dir := "foobar"
  782. must(t, ffs.MkdirAll(dir, 0o777))
  783. fi := protocol.FileInfo{
  784. Name: dir,
  785. }
  786. scanChan := make(chan string, 1)
  787. dbUpdateChan := make(chan dbUpdateJob, 1)
  788. f.deleteDir(fi, dbUpdateChan, scanChan)
  789. if _, err := ffs.Stat(dir); fs.IsNotExist(err) {
  790. t.Error("directory has been deleted")
  791. }
  792. select {
  793. case toScan := <-scanChan:
  794. if toScan != dir {
  795. t.Errorf("expected %v to be scanned, got %v", dir, toScan)
  796. }
  797. default:
  798. t.Error("nothing was scheduled for scanning")
  799. }
  800. }
  801. func TestPullCaseOnlyPerformFinish(t *testing.T) {
  802. m, f, wcfgCancel := setupSendReceiveFolder(t)
  803. defer wcfgCancel()
  804. ffs := f.Filesystem()
  805. name := "foo"
  806. contents := []byte("contents")
  807. writeFile(t, ffs, name, contents)
  808. must(t, f.scanSubdirs(nil))
  809. var cur protocol.FileInfo
  810. hasCur := false
  811. it, errFn := m.LocalFiles(f.ID, protocol.LocalDeviceID)
  812. for i := range it {
  813. if hasCur {
  814. t.Fatal("got more than one file")
  815. }
  816. cur = i
  817. hasCur = true
  818. }
  819. if err := errFn(); err != nil {
  820. t.Fatal(err)
  821. }
  822. if !hasCur {
  823. t.Fatal("file is missing")
  824. }
  825. remote := cur
  826. remote.Version = protocol.Vector{}.Update(device1.Short())
  827. remote.Name = strings.ToUpper(cur.Name)
  828. temp := fs.TempName(remote.Name)
  829. writeFile(t, ffs, temp, contents)
  830. scanChan := make(chan string, 1)
  831. dbUpdateChan := make(chan dbUpdateJob, 1)
  832. err := f.performFinish(remote, cur, hasCur, temp, dbUpdateChan, scanChan)
  833. select {
  834. case <-dbUpdateChan: // boring case sensitive filesystem
  835. return
  836. case <-scanChan:
  837. t.Error("no need to scan anything here")
  838. default:
  839. }
  840. var caseErr *fs.ErrCaseConflict
  841. if !errors.As(err, &caseErr) {
  842. t.Error("Expected case conflict error, got", err)
  843. }
  844. }
  845. func TestPullCaseOnlyDir(t *testing.T) {
  846. testPullCaseOnlyDirOrSymlink(t, true)
  847. }
  848. func TestPullCaseOnlySymlink(t *testing.T) {
  849. if build.IsWindows {
  850. t.Skip("symlinks not supported on windows")
  851. }
  852. testPullCaseOnlyDirOrSymlink(t, false)
  853. }
  854. func testPullCaseOnlyDirOrSymlink(t *testing.T, dir bool) {
  855. m, f, wcfgCancel := setupSendReceiveFolder(t)
  856. defer wcfgCancel()
  857. ffs := f.Filesystem()
  858. name := "foo"
  859. if dir {
  860. must(t, ffs.Mkdir(name, 0o777))
  861. } else {
  862. must(t, ffs.CreateSymlink("target", name))
  863. }
  864. must(t, f.scanSubdirs(nil))
  865. var cur protocol.FileInfo
  866. hasCur := false
  867. it, errFn := m.LocalFiles(f.ID, protocol.LocalDeviceID)
  868. for i := range it {
  869. if hasCur {
  870. t.Fatal("got more than one file")
  871. }
  872. cur = i
  873. hasCur = true
  874. }
  875. if err := errFn(); err != nil {
  876. t.Fatal(err)
  877. }
  878. if !hasCur {
  879. t.Fatal("file is missing")
  880. }
  881. scanChan := make(chan string, 1)
  882. dbUpdateChan := make(chan dbUpdateJob, 1)
  883. remote := cur
  884. remote.Version = protocol.Vector{}.Update(device1.Short())
  885. remote.Name = strings.ToUpper(cur.Name)
  886. if dir {
  887. f.handleDir(remote, dbUpdateChan, scanChan)
  888. } else {
  889. f.handleSymlink(remote, dbUpdateChan, scanChan)
  890. }
  891. select {
  892. case <-dbUpdateChan: // boring case sensitive filesystem
  893. return
  894. case <-scanChan:
  895. t.Error("no need to scan anything here")
  896. default:
  897. }
  898. if errStr, ok := f.tempPullErrors[remote.Name]; !ok {
  899. t.Error("missing error for", remote.Name)
  900. } else if !strings.Contains(errStr, "uses different upper or lowercase") {
  901. t.Error("unexpected error", errStr, "for", remote.Name)
  902. }
  903. }
  904. func TestPullTempFileCaseConflict(t *testing.T) {
  905. _, f, wcfgCancel := setupSendReceiveFolder(t)
  906. defer wcfgCancel()
  907. copyChan := make(chan copyBlocksState, 1)
  908. file := protocol.FileInfo{Name: "foo"}
  909. confl := "Foo"
  910. tempNameConfl := fs.TempName(confl)
  911. if fd, err := f.mtimefs.Create(tempNameConfl); err != nil {
  912. t.Fatal(err)
  913. } else {
  914. if _, err := fd.Write([]byte("data")); err != nil {
  915. t.Fatal(err)
  916. }
  917. fd.Close()
  918. }
  919. f.handleFile(file, copyChan)
  920. cs := <-copyChan
  921. if _, err := cs.tempFile(); err != nil {
  922. t.Error(err)
  923. } else {
  924. cs.finalClose()
  925. }
  926. }
  927. func TestPullCaseOnlyRename(t *testing.T) {
  928. m, f, wcfgCancel := setupSendReceiveFolder(t)
  929. defer wcfgCancel()
  930. // tempNameConfl := fs.TempName(confl)
  931. name := "foo"
  932. if fd, err := f.mtimefs.Create(name); err != nil {
  933. t.Fatal(err)
  934. } else {
  935. if _, err := fd.Write([]byte("data")); err != nil {
  936. t.Fatal(err)
  937. }
  938. fd.Close()
  939. }
  940. must(t, f.scanSubdirs(nil))
  941. cur, ok := m.testCurrentFolderFile(f.ID, name)
  942. if !ok {
  943. t.Fatal("file missing")
  944. }
  945. deleted := cur
  946. deleted.SetDeleted(myID.Short())
  947. confl := cur
  948. confl.Name = "Foo"
  949. confl.Version = confl.Version.Update(device1.Short())
  950. dbUpdateChan := make(chan dbUpdateJob, 2)
  951. scanChan := make(chan string, 2)
  952. if err := f.renameFile(cur, deleted, confl, dbUpdateChan, scanChan); err != nil {
  953. t.Error(err)
  954. }
  955. }
  956. func TestPullSymlinkOverExistingWindows(t *testing.T) {
  957. if !build.IsWindows {
  958. t.Skip()
  959. }
  960. m, f, wcfgCancel := setupSendReceiveFolder(t)
  961. defer wcfgCancel()
  962. conn := addFakeConn(m, device1, f.ID)
  963. name := "foo"
  964. if fd, err := f.mtimefs.Create(name); err != nil {
  965. t.Fatal(err)
  966. } else {
  967. if _, err := fd.Write([]byte("data")); err != nil {
  968. t.Fatal(err)
  969. }
  970. fd.Close()
  971. }
  972. must(t, f.scanSubdirs(nil))
  973. file, ok := m.testCurrentFolderFile(f.ID, name)
  974. if !ok {
  975. t.Fatal("file missing")
  976. }
  977. must(t, m.Index(conn, &protocol.Index{Folder: f.ID, Files: []protocol.FileInfo{{Name: name, Type: protocol.FileInfoTypeSymlink, Version: file.Version.Update(device1.Short())}}}))
  978. scanChan := make(chan string)
  979. changed, err := f.pullerIteration(scanChan)
  980. must(t, err)
  981. if changed != 1 {
  982. t.Error("Expected one change in pull, got", changed)
  983. }
  984. if file, ok := m.testCurrentFolderFile(f.ID, name); !ok {
  985. t.Error("symlink entry missing")
  986. } else if !file.IsUnsupported() {
  987. t.Error("symlink entry isn't marked as unsupported")
  988. }
  989. if _, err := f.mtimefs.Lstat(name); err == nil {
  990. t.Error("old file still exists on disk")
  991. } else if !fs.IsNotExist(err) {
  992. t.Error(err)
  993. }
  994. }
  995. func TestPullDeleteCaseConflict(t *testing.T) {
  996. _, f, wcfgCancel := setupSendReceiveFolder(t)
  997. defer wcfgCancel()
  998. name := "foo"
  999. fi := protocol.FileInfo{Name: "Foo"}
  1000. dbUpdateChan := make(chan dbUpdateJob, 1)
  1001. scanChan := make(chan string)
  1002. if fd, err := f.mtimefs.Create(name); err != nil {
  1003. t.Fatal(err)
  1004. } else {
  1005. if _, err := fd.Write([]byte("data")); err != nil {
  1006. t.Fatal(err)
  1007. }
  1008. fd.Close()
  1009. }
  1010. f.deleteFileWithCurrent(fi, protocol.FileInfo{}, false, dbUpdateChan, scanChan)
  1011. select {
  1012. case <-dbUpdateChan:
  1013. default:
  1014. t.Error("Missing db update for file")
  1015. }
  1016. f.deleteDir(fi, dbUpdateChan, scanChan)
  1017. select {
  1018. case <-dbUpdateChan:
  1019. default:
  1020. t.Error("Missing db update for dir")
  1021. }
  1022. }
  1023. func TestPullDeleteIgnoreChildDir(t *testing.T) {
  1024. _, f, wcfgCancel := setupSendReceiveFolder(t)
  1025. defer wcfgCancel()
  1026. parent := "parent"
  1027. del := "ignored"
  1028. child := "keep"
  1029. matcher := ignore.New(f.mtimefs)
  1030. must(t, matcher.Parse(bytes.NewBufferString(fmt.Sprintf(`
  1031. !%v
  1032. (?d)%v
  1033. `, child, del)), ""))
  1034. f.ignores = matcher
  1035. must(t, f.mtimefs.Mkdir(parent, 0o777))
  1036. must(t, f.mtimefs.Mkdir(filepath.Join(parent, del), 0o777))
  1037. must(t, f.mtimefs.Mkdir(filepath.Join(parent, del, child), 0o777))
  1038. scanChan := make(chan string, 2)
  1039. err := f.deleteDirOnDisk(parent, scanChan)
  1040. if err == nil {
  1041. t.Error("no error")
  1042. }
  1043. }
  1044. func cleanupSharedPullerState(s *sharedPullerState) {
  1045. s.mut.Lock()
  1046. defer s.mut.Unlock()
  1047. if s.writer == nil {
  1048. return
  1049. }
  1050. s.writer.mut.Lock()
  1051. s.writer.fd.Close()
  1052. s.writer.mut.Unlock()
  1053. }
  1054. func startCopier(f *sendReceiveFolder, pullChan chan<- pullBlockState, finisherChan chan<- *sharedPullerState) (chan copyBlocksState, sync.WaitGroup) {
  1055. copyChan := make(chan copyBlocksState)
  1056. wg := sync.NewWaitGroup()
  1057. wg.Add(1)
  1058. go func() {
  1059. f.copierRoutine(copyChan, pullChan, finisherChan)
  1060. wg.Done()
  1061. }()
  1062. return copyChan, wg
  1063. }