folder_sendrecv_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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. "io"
  12. "io/ioutil"
  13. "os"
  14. "path/filepath"
  15. "runtime"
  16. "testing"
  17. "time"
  18. "github.com/syncthing/syncthing/lib/config"
  19. "github.com/syncthing/syncthing/lib/db"
  20. "github.com/syncthing/syncthing/lib/events"
  21. "github.com/syncthing/syncthing/lib/fs"
  22. "github.com/syncthing/syncthing/lib/ignore"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. "github.com/syncthing/syncthing/lib/scanner"
  25. "github.com/syncthing/syncthing/lib/sync"
  26. )
  27. var blocks = []protocol.BlockInfo{
  28. {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
  29. {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}},
  30. {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}},
  31. {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}},
  32. {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}},
  33. {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}},
  34. {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}},
  35. {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}},
  36. {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}},
  37. }
  38. var folders = []string{"default"}
  39. var diffTestData = []struct {
  40. a string
  41. b string
  42. s int
  43. d []protocol.BlockInfo
  44. }{
  45. {"contents", "contents", 1024, []protocol.BlockInfo{}},
  46. {"", "", 1024, []protocol.BlockInfo{}},
  47. {"contents", "contents", 3, []protocol.BlockInfo{}},
  48. {"contents", "cantents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}}},
  49. {"contents", "contants", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}}},
  50. {"contents", "cantants", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}}},
  51. {"contents", "", 3, []protocol.BlockInfo{{Offset: 0, Size: 0}}},
  52. {"", "contents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  53. {"con", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  54. {"contents", "con", 3, nil},
  55. {"contents", "cont", 3, []protocol.BlockInfo{{Offset: 3, Size: 1}}},
  56. {"cont", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  57. }
  58. func setupFile(filename string, blockNumbers []int) protocol.FileInfo {
  59. // Create existing file
  60. existingBlocks := make([]protocol.BlockInfo, len(blockNumbers))
  61. for i := range blockNumbers {
  62. existingBlocks[i] = blocks[blockNumbers[i]]
  63. }
  64. return protocol.FileInfo{
  65. Name: filename,
  66. Blocks: existingBlocks,
  67. }
  68. }
  69. func createFile(t *testing.T, name string, fs fs.Filesystem) protocol.FileInfo {
  70. t.Helper()
  71. f, err := fs.Create(name)
  72. must(t, err)
  73. f.Close()
  74. fi, err := fs.Stat(name)
  75. must(t, err)
  76. file, err := scanner.CreateFileInfo(fi, name, fs)
  77. must(t, err)
  78. return file
  79. }
  80. func setupSendReceiveFolder(files ...protocol.FileInfo) (*model, *sendReceiveFolder) {
  81. w := createTmpWrapper(defaultCfg)
  82. model := newModel(w, myID, "syncthing", "dev", db.OpenMemory(), nil)
  83. fcfg := testFolderConfigTmp()
  84. model.AddFolder(fcfg)
  85. f := &sendReceiveFolder{
  86. folder: folder{
  87. stateTracker: newStateTracker("default"),
  88. model: model,
  89. fset: model.folderFiles[fcfg.ID],
  90. initialScanFinished: make(chan struct{}),
  91. ctx: context.TODO(),
  92. FolderConfiguration: fcfg,
  93. },
  94. queue: newJobQueue(),
  95. pullErrors: make(map[string]string),
  96. pullErrorsMut: sync.NewMutex(),
  97. }
  98. f.fs = fs.NewMtimeFS(f.Filesystem(), db.NewNamespacedKV(model.db, "mtime"))
  99. // Update index
  100. if files != nil {
  101. f.updateLocalsFromScanning(files)
  102. }
  103. // Folders are never actually started, so no initial scan will be done
  104. close(f.initialScanFinished)
  105. return model, f
  106. }
  107. // Layout of the files: (indexes from the above array)
  108. // 12345678 - Required file
  109. // 02005008 - Existing file (currently in the index)
  110. // 02340070 - Temp file on the disk
  111. func TestHandleFile(t *testing.T) {
  112. // After the diff between required and existing we should:
  113. // Copy: 2, 5, 8
  114. // Pull: 1, 3, 4, 6, 7
  115. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  116. existingFile := setupFile("filex", existingBlocks)
  117. requiredFile := existingFile
  118. requiredFile.Blocks = blocks[1:]
  119. m, f := setupSendReceiveFolder(existingFile)
  120. defer func() {
  121. os.Remove(m.cfg.ConfigPath())
  122. os.Remove(f.Filesystem().URI())
  123. }()
  124. copyChan := make(chan copyBlocksState, 1)
  125. dbUpdateChan := make(chan dbUpdateJob, 1)
  126. f.handleFile(requiredFile, copyChan, dbUpdateChan)
  127. // Receive the results
  128. toCopy := <-copyChan
  129. if len(toCopy.blocks) != 8 {
  130. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  131. }
  132. for _, block := range blocks[1:] {
  133. found := false
  134. for _, toCopyBlock := range toCopy.blocks {
  135. if string(toCopyBlock.Hash) == string(block.Hash) {
  136. found = true
  137. break
  138. }
  139. }
  140. if !found {
  141. t.Errorf("Did not find block %s", block.String())
  142. }
  143. }
  144. }
  145. func TestHandleFileWithTemp(t *testing.T) {
  146. // After diff between required and existing we should:
  147. // Copy: 2, 5, 8
  148. // Pull: 1, 3, 4, 6, 7
  149. // After dropping out blocks already on the temp file we should:
  150. // Copy: 5, 8
  151. // Pull: 1, 6
  152. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  153. existingFile := setupFile("file", existingBlocks)
  154. requiredFile := existingFile
  155. requiredFile.Blocks = blocks[1:]
  156. m, f := setupSendReceiveFolder(existingFile)
  157. defer func() {
  158. os.Remove(m.cfg.ConfigPath())
  159. os.Remove(f.Filesystem().URI())
  160. }()
  161. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  162. t.Fatal(err)
  163. }
  164. copyChan := make(chan copyBlocksState, 1)
  165. dbUpdateChan := make(chan dbUpdateJob, 1)
  166. f.handleFile(requiredFile, copyChan, dbUpdateChan)
  167. // Receive the results
  168. toCopy := <-copyChan
  169. if len(toCopy.blocks) != 4 {
  170. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  171. }
  172. for _, idx := range []int{1, 5, 6, 8} {
  173. found := false
  174. block := blocks[idx]
  175. for _, toCopyBlock := range toCopy.blocks {
  176. if string(toCopyBlock.Hash) == string(block.Hash) {
  177. found = true
  178. break
  179. }
  180. }
  181. if !found {
  182. t.Errorf("Did not find block %s", block.String())
  183. }
  184. }
  185. }
  186. func TestCopierFinder(t *testing.T) {
  187. // After diff between required and existing we should:
  188. // Copy: 1, 2, 3, 4, 6, 7, 8
  189. // Since there is no existing file, nor a temp file
  190. // After dropping out blocks found locally:
  191. // Pull: 1, 5, 6, 8
  192. tempFile := fs.TempName("file2")
  193. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  194. existingFile := setupFile(fs.TempName("file"), existingBlocks)
  195. requiredFile := existingFile
  196. requiredFile.Blocks = blocks[1:]
  197. requiredFile.Name = "file2"
  198. m, f := setupSendReceiveFolder(existingFile)
  199. defer func() {
  200. os.Remove(m.cfg.ConfigPath())
  201. os.Remove(f.Filesystem().URI())
  202. }()
  203. if _, err := prepareTmpFile(f.Filesystem()); 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. dbUpdateChan := make(chan dbUpdateJob, 1)
  210. // Run a single fetcher routine
  211. go f.copierRoutine(copyChan, pullChan, finisherChan)
  212. f.handleFile(requiredFile, copyChan, dbUpdateChan)
  213. pulls := []pullBlockState{<-pullChan, <-pullChan, <-pullChan, <-pullChan}
  214. finish := <-finisherChan
  215. select {
  216. case <-pullChan:
  217. t.Fatal("Pull channel has data to be read")
  218. case <-finisherChan:
  219. t.Fatal("Finisher channel has data to be read")
  220. default:
  221. }
  222. // Verify that the right blocks went into the pull list.
  223. // They are pulled in random order.
  224. for _, idx := range []int{1, 5, 6, 8} {
  225. found := false
  226. block := blocks[idx]
  227. for _, pulledBlock := range pulls {
  228. if string(pulledBlock.block.Hash) == string(block.Hash) {
  229. found = true
  230. break
  231. }
  232. }
  233. if !found {
  234. t.Errorf("Did not find block %s", block.String())
  235. }
  236. if string(finish.file.Blocks[idx-1].Hash) != string(blocks[idx].Hash) {
  237. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  238. }
  239. }
  240. // Verify that the fetched blocks have actually been written to the temp file
  241. blks, err := scanner.HashFile(context.TODO(), f.Filesystem(), tempFile, protocol.MinBlockSize, nil, false)
  242. if err != nil {
  243. t.Log(err)
  244. }
  245. for _, eq := range []int{2, 3, 4, 7} {
  246. if string(blks[eq-1].Hash) != string(blocks[eq].Hash) {
  247. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  248. }
  249. }
  250. finish.fd.Close()
  251. }
  252. func TestWeakHash(t *testing.T) {
  253. // Setup the model/pull environment
  254. model, fo := setupSendReceiveFolder()
  255. ffs := fo.Filesystem()
  256. defer func() {
  257. os.Remove(model.cfg.ConfigPath())
  258. os.Remove(ffs.URI())
  259. }()
  260. tempFile := fs.TempName("weakhash")
  261. var shift int64 = 10
  262. var size int64 = 1 << 20
  263. expectBlocks := int(size / protocol.MinBlockSize)
  264. expectPulls := int(shift / protocol.MinBlockSize)
  265. if shift > 0 {
  266. expectPulls++
  267. }
  268. f, err := ffs.Create("weakhash")
  269. must(t, err)
  270. defer f.Close()
  271. _, err = io.CopyN(f, rand.Reader, size)
  272. if err != nil {
  273. t.Error(err)
  274. }
  275. info, err := f.Stat()
  276. if err != nil {
  277. t.Error(err)
  278. }
  279. // Create two files, second file has `shifted` bytes random prefix, yet
  280. // both are of the same length, for example:
  281. // File 1: abcdefgh
  282. // File 2: xyabcdef
  283. f.Seek(0, os.SEEK_SET)
  284. existing, err := scanner.Blocks(context.TODO(), f, protocol.MinBlockSize, size, nil, true)
  285. if err != nil {
  286. t.Error(err)
  287. }
  288. f.Seek(0, os.SEEK_SET)
  289. remainder := io.LimitReader(f, size-shift)
  290. prefix := io.LimitReader(rand.Reader, shift)
  291. nf := io.MultiReader(prefix, remainder)
  292. desired, err := scanner.Blocks(context.TODO(), nf, protocol.MinBlockSize, size, nil, true)
  293. if err != nil {
  294. t.Error(err)
  295. }
  296. existingFile := protocol.FileInfo{
  297. Name: "weakhash",
  298. Blocks: existing,
  299. Size: size,
  300. ModifiedS: info.ModTime().Unix(),
  301. ModifiedNs: int32(info.ModTime().Nanosecond()),
  302. }
  303. desiredFile := protocol.FileInfo{
  304. Name: "weakhash",
  305. Size: size,
  306. Blocks: desired,
  307. ModifiedS: info.ModTime().Unix() + 1,
  308. }
  309. fo.updateLocalsFromScanning([]protocol.FileInfo{existingFile})
  310. copyChan := make(chan copyBlocksState)
  311. pullChan := make(chan pullBlockState, expectBlocks)
  312. finisherChan := make(chan *sharedPullerState, 1)
  313. dbUpdateChan := make(chan dbUpdateJob, 1)
  314. // Run a single fetcher routine
  315. go fo.copierRoutine(copyChan, pullChan, finisherChan)
  316. // Test 1 - no weak hashing, file gets fully repulled (`expectBlocks` pulls).
  317. fo.WeakHashThresholdPct = 101
  318. fo.handleFile(desiredFile, copyChan, dbUpdateChan)
  319. var pulls []pullBlockState
  320. for len(pulls) < expectBlocks {
  321. select {
  322. case pull := <-pullChan:
  323. pulls = append(pulls, pull)
  324. case <-time.After(10 * time.Second):
  325. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  326. }
  327. }
  328. finish := <-finisherChan
  329. select {
  330. case <-pullChan:
  331. t.Fatal("Pull channel has data to be read")
  332. case <-finisherChan:
  333. t.Fatal("Finisher channel has data to be read")
  334. default:
  335. }
  336. finish.fd.Close()
  337. if err := ffs.Remove(tempFile); err != nil {
  338. t.Fatal(err)
  339. }
  340. // Test 2 - using weak hash, expectPulls blocks pulled.
  341. fo.WeakHashThresholdPct = -1
  342. fo.handleFile(desiredFile, copyChan, dbUpdateChan)
  343. pulls = pulls[:0]
  344. for len(pulls) < expectPulls {
  345. select {
  346. case pull := <-pullChan:
  347. pulls = append(pulls, pull)
  348. case <-time.After(10 * time.Second):
  349. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  350. }
  351. }
  352. finish = <-finisherChan
  353. finish.fd.Close()
  354. expectShifted := expectBlocks - expectPulls
  355. if finish.copyOriginShifted != expectShifted {
  356. t.Errorf("did not copy %d shifted", expectShifted)
  357. }
  358. }
  359. // Test that updating a file removes its old blocks from the blockmap
  360. func TestCopierCleanup(t *testing.T) {
  361. iterFn := func(folder, file string, index int32) bool {
  362. return true
  363. }
  364. // Create a file
  365. file := setupFile("test", []int{0})
  366. m, f := setupSendReceiveFolder(file)
  367. defer func() {
  368. os.Remove(m.cfg.ConfigPath())
  369. os.Remove(f.Filesystem().URI())
  370. }()
  371. file.Blocks = []protocol.BlockInfo{blocks[1]}
  372. file.Version = file.Version.Update(myID.Short())
  373. // Update index (removing old blocks)
  374. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  375. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  376. t.Error("Unexpected block found")
  377. }
  378. if !m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  379. t.Error("Expected block not found")
  380. }
  381. file.Blocks = []protocol.BlockInfo{blocks[0]}
  382. file.Version = file.Version.Update(myID.Short())
  383. // Update index (removing old blocks)
  384. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  385. if !m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  386. t.Error("Unexpected block found")
  387. }
  388. if m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  389. t.Error("Expected block not found")
  390. }
  391. }
  392. func TestDeregisterOnFailInCopy(t *testing.T) {
  393. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  394. m, f := setupSendReceiveFolder()
  395. defer func() {
  396. os.Remove(m.cfg.ConfigPath())
  397. os.Remove(f.Filesystem().URI())
  398. }()
  399. // Set up our evet subscription early
  400. s := events.Default.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. copyChan := make(chan copyBlocksState)
  408. pullChan := make(chan pullBlockState)
  409. finisherBufferChan := make(chan *sharedPullerState)
  410. finisherChan := make(chan *sharedPullerState)
  411. dbUpdateChan := make(chan dbUpdateJob, 1)
  412. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  413. go f.finisherRoutine(finisherChan, dbUpdateChan, make(chan string))
  414. f.handleFile(file, copyChan, dbUpdateChan)
  415. // Receive a block at puller, to indicate that at least a single copier
  416. // loop has been performed.
  417. toPull := <-pullChan
  418. // Close the file, causing errors on further access
  419. toPull.sharedPullerState.fail(os.ErrNotExist)
  420. // Unblock copier
  421. go func() {
  422. for range pullChan {
  423. }
  424. }()
  425. select {
  426. case state := <-finisherBufferChan:
  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. stateFd := state.fd
  443. state.mut.Unlock()
  444. if stateFd != 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. case <-time.After(time.Second):
  459. t.Fatal("Didn't get anything to the finisher")
  460. }
  461. }
  462. func TestDeregisterOnFailInPull(t *testing.T) {
  463. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  464. m, f := setupSendReceiveFolder()
  465. defer func() {
  466. os.Remove(m.cfg.ConfigPath())
  467. os.Remove(f.Filesystem().URI())
  468. }()
  469. // Set up our evet subscription early
  470. s := events.Default.Subscribe(events.ItemFinished)
  471. // queue.Done should be called by the finisher routine
  472. f.queue.Push("filex", 0, time.Time{})
  473. f.queue.Pop()
  474. if f.queue.lenProgress() != 1 {
  475. t.Fatal("Expected file in progress")
  476. }
  477. copyChan := make(chan copyBlocksState)
  478. pullChan := make(chan pullBlockState)
  479. finisherBufferChan := make(chan *sharedPullerState)
  480. finisherChan := make(chan *sharedPullerState)
  481. dbUpdateChan := make(chan dbUpdateJob, 1)
  482. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  483. go f.pullerRoutine(pullChan, finisherBufferChan)
  484. go f.finisherRoutine(finisherChan, dbUpdateChan, make(chan string))
  485. f.handleFile(file, copyChan, dbUpdateChan)
  486. // Receive at finisher, we should error out as puller has nowhere to pull
  487. // from.
  488. timeout = time.Second
  489. select {
  490. case state := <-finisherBufferChan:
  491. // At this point the file should still be registered with both the job
  492. // queue, and the progress emitter. Verify this.
  493. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  494. t.Fatal("Could not find file")
  495. }
  496. // Pass the file down the real finisher, and give it time to consume
  497. finisherChan <- state
  498. t0 := time.Now()
  499. if ev, err := s.Poll(time.Minute); err != nil {
  500. t.Fatal("Got error waiting for ItemFinished event:", err)
  501. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  502. t.Fatal("Got ItemFinished event for wrong file:", n)
  503. }
  504. t.Log("event took", time.Since(t0))
  505. state.mut.Lock()
  506. stateFd := state.fd
  507. state.mut.Unlock()
  508. if stateFd != nil {
  509. t.Fatal("File not closed?")
  510. }
  511. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  512. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  513. }
  514. // Doing it again should have no effect
  515. finisherChan <- state
  516. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  517. t.Fatal("Expected timeout, not another event", err)
  518. }
  519. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  520. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  521. }
  522. case <-time.After(time.Second):
  523. t.Fatal("Didn't get anything to the finisher")
  524. }
  525. }
  526. func TestIssue3164(t *testing.T) {
  527. m, f := setupSendReceiveFolder()
  528. ffs := f.Filesystem()
  529. tmpDir := ffs.URI()
  530. defer func() {
  531. os.Remove(m.cfg.ConfigPath())
  532. os.Remove(tmpDir)
  533. }()
  534. ignDir := filepath.Join("issue3164", "oktodelete")
  535. subDir := filepath.Join(ignDir, "foobar")
  536. must(t, ffs.MkdirAll(subDir, 0777))
  537. must(t, ioutil.WriteFile(filepath.Join(tmpDir, subDir, "file"), []byte("Hello"), 0644))
  538. must(t, ioutil.WriteFile(filepath.Join(tmpDir, ignDir, "file"), []byte("Hello"), 0644))
  539. file := protocol.FileInfo{
  540. Name: "issue3164",
  541. }
  542. matcher := ignore.New(ffs)
  543. must(t, matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""))
  544. f.ignores = matcher
  545. dbUpdateChan := make(chan dbUpdateJob, 1)
  546. f.deleteDir(file, dbUpdateChan, make(chan string))
  547. if _, err := ffs.Stat("issue3164"); !fs.IsNotExist(err) {
  548. t.Fatal(err)
  549. }
  550. }
  551. func TestDiff(t *testing.T) {
  552. for i, test := range diffTestData {
  553. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  554. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  555. _, d := blockDiff(a, b)
  556. if len(d) != len(test.d) {
  557. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  558. } else {
  559. for j := range test.d {
  560. if d[j].Offset != test.d[j].Offset {
  561. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  562. }
  563. if d[j].Size != test.d[j].Size {
  564. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  565. }
  566. }
  567. }
  568. }
  569. }
  570. func BenchmarkDiff(b *testing.B) {
  571. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  572. for _, test := range diffTestData {
  573. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  574. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  575. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{a, b})
  576. }
  577. b.ReportAllocs()
  578. b.ResetTimer()
  579. for i := 0; i < b.N; i++ {
  580. for _, tc := range testCases {
  581. blockDiff(tc.a, tc.b)
  582. }
  583. }
  584. }
  585. func TestDiffEmpty(t *testing.T) {
  586. emptyCases := []struct {
  587. a []protocol.BlockInfo
  588. b []protocol.BlockInfo
  589. need int
  590. have int
  591. }{
  592. {nil, nil, 0, 0},
  593. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  594. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  595. }
  596. for _, emptyCase := range emptyCases {
  597. h, n := blockDiff(emptyCase.a, emptyCase.b)
  598. if len(h) != emptyCase.have {
  599. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  600. }
  601. if len(n) != emptyCase.need {
  602. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  603. }
  604. }
  605. }
  606. // TestDeleteIgnorePerms checks, that a file gets deleted when the IgnorePerms
  607. // option is true and the permissions do not match between the file on disk and
  608. // in the db.
  609. func TestDeleteIgnorePerms(t *testing.T) {
  610. m, f := setupSendReceiveFolder()
  611. ffs := f.Filesystem()
  612. defer func() {
  613. os.Remove(m.cfg.ConfigPath())
  614. os.Remove(ffs.URI())
  615. }()
  616. f.IgnorePerms = true
  617. name := "deleteIgnorePerms"
  618. file, err := ffs.Create(name)
  619. if err != nil {
  620. t.Error(err)
  621. }
  622. defer file.Close()
  623. stat, err := file.Stat()
  624. must(t, err)
  625. fi, err := scanner.CreateFileInfo(stat, name, ffs)
  626. must(t, err)
  627. ffs.Chmod(name, 0600)
  628. scanChan := make(chan string)
  629. finished := make(chan struct{})
  630. go func() {
  631. err = f.checkToBeDeleted(fi, scanChan)
  632. close(finished)
  633. }()
  634. select {
  635. case <-scanChan:
  636. <-finished
  637. case <-finished:
  638. }
  639. must(t, err)
  640. }
  641. func TestCopyOwner(t *testing.T) {
  642. // Verifies that owner and group are copied from the parent, for both
  643. // files and directories.
  644. if runtime.GOOS == "windows" {
  645. t.Skip("copying owner not supported on Windows")
  646. }
  647. const (
  648. expOwner = 1234
  649. expGroup = 5678
  650. )
  651. // Set up a folder with the CopyParentOwner bit and backed by a fake
  652. // filesystem.
  653. m, f := setupSendReceiveFolder()
  654. defer os.Remove(m.cfg.ConfigPath())
  655. f.folder.FolderConfiguration = config.NewFolderConfiguration(m.id, f.ID, f.Label, fs.FilesystemTypeFake, "/TestCopyOwner")
  656. f.folder.FolderConfiguration.CopyOwnershipFromParent = true
  657. f.fs = f.Filesystem()
  658. // Create a parent dir with a certain owner/group.
  659. f.fs.Mkdir("foo", 0755)
  660. f.fs.Lchown("foo", expOwner, expGroup)
  661. dir := protocol.FileInfo{
  662. Name: "foo/bar",
  663. Type: protocol.FileInfoTypeDirectory,
  664. Permissions: 0755,
  665. }
  666. // Have the folder create a subdirectory, verify that it's the correct
  667. // owner/group.
  668. dbUpdateChan := make(chan dbUpdateJob, 1)
  669. defer close(dbUpdateChan)
  670. f.handleDir(dir, dbUpdateChan, nil)
  671. <-dbUpdateChan // empty the channel for later
  672. info, err := f.fs.Lstat("foo/bar")
  673. if err != nil {
  674. t.Fatal("Unexpected error (dir):", err)
  675. }
  676. if info.Owner() != expOwner || info.Group() != expGroup {
  677. t.Fatalf("Expected dir owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  678. }
  679. // Have the folder create a file, verify it's the correct owner/group.
  680. // File is zero sized to avoid having to handle copies/pulls.
  681. file := protocol.FileInfo{
  682. Name: "foo/bar/baz",
  683. Type: protocol.FileInfoTypeFile,
  684. Permissions: 0644,
  685. }
  686. // Wire some stuff. The flow here is handleFile() -[copierChan]->
  687. // copierRoutine() -[finisherChan]-> finisherRoutine() -[dbUpdateChan]->
  688. // back to us and we're done. The copier routine doesn't do anything,
  689. // but it's the way data is passed around. When the database update
  690. // comes the finisher is done.
  691. finisherChan := make(chan *sharedPullerState)
  692. defer close(finisherChan)
  693. copierChan := make(chan copyBlocksState)
  694. defer close(copierChan)
  695. go f.copierRoutine(copierChan, nil, finisherChan)
  696. go f.finisherRoutine(finisherChan, dbUpdateChan, nil)
  697. f.handleFile(file, copierChan, nil)
  698. <-dbUpdateChan
  699. info, err = f.fs.Lstat("foo/bar/baz")
  700. if err != nil {
  701. t.Fatal("Unexpected error (file):", err)
  702. }
  703. if info.Owner() != expOwner || info.Group() != expGroup {
  704. t.Fatalf("Expected file owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  705. }
  706. // Have the folder create a symlink. Verify it accordingly.
  707. symlink := protocol.FileInfo{
  708. Name: "foo/bar/sym",
  709. Type: protocol.FileInfoTypeSymlink,
  710. Permissions: 0644,
  711. SymlinkTarget: "over the rainbow",
  712. }
  713. f.handleSymlink(symlink, dbUpdateChan, nil)
  714. <-dbUpdateChan
  715. info, err = f.fs.Lstat("foo/bar/sym")
  716. if err != nil {
  717. t.Fatal("Unexpected error (file):", err)
  718. }
  719. if info.Owner() != expOwner || info.Group() != expGroup {
  720. t.Fatalf("Expected symlink owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  721. }
  722. }
  723. // TestSRConflictReplaceFileByDir checks that a conflict is created when an existing file
  724. // is replaced with a directory and versions are conflicting
  725. func TestSRConflictReplaceFileByDir(t *testing.T) {
  726. m, f := setupSendReceiveFolder()
  727. ffs := f.Filesystem()
  728. defer func() {
  729. os.Remove(m.cfg.ConfigPath())
  730. os.Remove(ffs.URI())
  731. }()
  732. name := "foo"
  733. // create local file
  734. file := createFile(t, name, ffs)
  735. file.Version = protocol.Vector{}.Update(myID.Short())
  736. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  737. // Simulate remote creating a dir with the same name
  738. file.Type = protocol.FileInfoTypeDirectory
  739. rem := device1.Short()
  740. file.Version = protocol.Vector{}.Update(rem)
  741. file.ModifiedBy = rem
  742. dbUpdateChan := make(chan dbUpdateJob, 1)
  743. scanChan := make(chan string, 1)
  744. f.handleDir(file, dbUpdateChan, scanChan)
  745. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  746. t.Fatal("Expected one conflict, got", len(confls))
  747. } else if scan := <-scanChan; confls[0] != scan {
  748. t.Fatal("Expected request to scan", confls[0], "got", scan)
  749. }
  750. }
  751. // TestSRConflictReplaceFileByLink checks that a conflict is created when an existing file
  752. // is replaced with a link and versions are conflicting
  753. func TestSRConflictReplaceFileByLink(t *testing.T) {
  754. m, f := setupSendReceiveFolder()
  755. ffs := f.Filesystem()
  756. defer func() {
  757. os.Remove(m.cfg.ConfigPath())
  758. os.Remove(ffs.URI())
  759. }()
  760. name := "foo"
  761. // create local file
  762. file := createFile(t, name, ffs)
  763. file.Version = protocol.Vector{}.Update(myID.Short())
  764. f.updateLocalsFromScanning([]protocol.FileInfo{file})
  765. // Simulate remote creating a symlink with the same name
  766. file.Type = protocol.FileInfoTypeSymlink
  767. file.SymlinkTarget = "bar"
  768. rem := device1.Short()
  769. file.Version = protocol.Vector{}.Update(rem)
  770. file.ModifiedBy = rem
  771. dbUpdateChan := make(chan dbUpdateJob, 1)
  772. scanChan := make(chan string, 1)
  773. f.handleSymlink(file, dbUpdateChan, scanChan)
  774. if confls := existingConflicts(name, ffs); len(confls) != 1 {
  775. t.Fatal("Expected one conflict, got", len(confls))
  776. } else if scan := <-scanChan; confls[0] != scan {
  777. t.Fatal("Expected request to scan", confls[0], "got", scan)
  778. }
  779. }