folder_sendrecv_test.go 29 KB

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