folder_sendrecv_test.go 36 KB

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