folder_sendrecv_test.go 28 KB

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