folder_sendrecv.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  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. "errors"
  10. "fmt"
  11. "math/rand"
  12. "path/filepath"
  13. "runtime"
  14. "sort"
  15. "strings"
  16. stdsync "sync"
  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/sha256"
  27. "github.com/syncthing/syncthing/lib/sync"
  28. "github.com/syncthing/syncthing/lib/versioner"
  29. "github.com/syncthing/syncthing/lib/weakhash"
  30. )
  31. var (
  32. blockStats = make(map[string]int)
  33. blockStatsMut = sync.NewMutex()
  34. )
  35. func init() {
  36. folderFactories[config.FolderTypeSendReceive] = newSendReceiveFolder
  37. }
  38. // A pullBlockState is passed to the puller routine for each block that needs
  39. // to be fetched.
  40. type pullBlockState struct {
  41. *sharedPullerState
  42. block protocol.BlockInfo
  43. }
  44. // A copyBlocksState is passed to copy routine if the file has blocks to be
  45. // copied.
  46. type copyBlocksState struct {
  47. *sharedPullerState
  48. blocks []protocol.BlockInfo
  49. have int
  50. }
  51. // Which filemode bits to preserve
  52. const retainBits = fs.ModeSetgid | fs.ModeSetuid | fs.ModeSticky
  53. var (
  54. activity = newDeviceActivity()
  55. errNoDevice = errors.New("peers who had this file went away, or the file has changed while syncing. will retry later")
  56. errSymlinksUnsupported = errors.New("symlinks not supported")
  57. errDirHasToBeScanned = errors.New("directory contains unexpected files, scheduling scan")
  58. errDirHasIgnored = errors.New("directory contains ignored files (see ignore documentation for (?d) prefix)")
  59. errDirNotEmpty = errors.New("directory is not empty")
  60. )
  61. const (
  62. dbUpdateHandleDir = iota
  63. dbUpdateDeleteDir
  64. dbUpdateHandleFile
  65. dbUpdateDeleteFile
  66. dbUpdateShortcutFile
  67. dbUpdateHandleSymlink
  68. dbUpdateInvalidate
  69. )
  70. const (
  71. defaultCopiers = 2
  72. defaultPullerPause = 60 * time.Second
  73. defaultPullerPendingKiB = 2 * protocol.MaxBlockSize / 1024
  74. maxPullerIterations = 3
  75. )
  76. type dbUpdateJob struct {
  77. file protocol.FileInfo
  78. jobType int
  79. }
  80. type sendReceiveFolder struct {
  81. folder
  82. prevIgnoreHash string
  83. fs fs.Filesystem
  84. versioner versioner.Versioner
  85. queue *jobQueue
  86. errors map[string]string // path -> error string
  87. errorsMut sync.Mutex
  88. }
  89. func newSendReceiveFolder(model *Model, cfg config.FolderConfiguration, ver versioner.Versioner, fs fs.Filesystem) service {
  90. f := &sendReceiveFolder{
  91. folder: newFolder(model, cfg),
  92. fs: fs,
  93. versioner: ver,
  94. queue: newJobQueue(),
  95. errorsMut: sync.NewMutex(),
  96. }
  97. f.folder.puller = f
  98. if f.Copiers == 0 {
  99. f.Copiers = defaultCopiers
  100. }
  101. // If the configured max amount of pending data is zero, we use the
  102. // default. If it's configured to something non-zero but less than the
  103. // protocol block size we adjust it upwards accordingly.
  104. if f.PullerMaxPendingKiB == 0 {
  105. f.PullerMaxPendingKiB = defaultPullerPendingKiB
  106. }
  107. if blockSizeKiB := protocol.MaxBlockSize / 1024; f.PullerMaxPendingKiB < blockSizeKiB {
  108. f.PullerMaxPendingKiB = blockSizeKiB
  109. }
  110. return f
  111. }
  112. func (f *sendReceiveFolder) pull() bool {
  113. select {
  114. case <-f.initialScanFinished:
  115. default:
  116. // Once the initial scan finished, a pull will be scheduled
  117. return true
  118. }
  119. if err := f.CheckHealth(); err != nil {
  120. l.Debugln("Skipping pull of", f.Description(), "due to folder error:", err)
  121. return true
  122. }
  123. f.model.fmut.RLock()
  124. curIgnores := f.model.folderIgnores[f.folderID]
  125. f.model.fmut.RUnlock()
  126. curIgnoreHash := curIgnores.Hash()
  127. ignoresChanged := curIgnoreHash != f.prevIgnoreHash
  128. l.Debugf("%v pulling (ignoresChanged=%v)", f, ignoresChanged)
  129. f.setState(FolderSyncing)
  130. f.clearErrors()
  131. scanChan := make(chan string)
  132. go f.pullScannerRoutine(scanChan)
  133. var changed int
  134. tries := 0
  135. for {
  136. tries++
  137. changed = f.pullerIteration(curIgnores, ignoresChanged, scanChan)
  138. l.Debugln(f, "changed", changed)
  139. if changed == 0 {
  140. // No files were changed by the puller, so we are in
  141. // sync.
  142. break
  143. }
  144. if tries == maxPullerIterations {
  145. // We've tried a bunch of times to get in sync, but
  146. // we're not making it. Probably there are write
  147. // errors preventing us. Flag this with a warning and
  148. // wait a bit longer before retrying.
  149. if folderErrors := f.PullErrors(); len(folderErrors) > 0 {
  150. events.Default.Log(events.FolderErrors, map[string]interface{}{
  151. "folder": f.folderID,
  152. "errors": folderErrors,
  153. })
  154. }
  155. break
  156. }
  157. }
  158. f.setState(FolderIdle)
  159. close(scanChan)
  160. if changed == 0 {
  161. f.prevIgnoreHash = curIgnoreHash
  162. return true
  163. }
  164. return false
  165. }
  166. // pullerIteration runs a single puller iteration for the given folder and
  167. // returns the number items that should have been synced (even those that
  168. // might have failed). One puller iteration handles all files currently
  169. // flagged as needed in the folder.
  170. func (f *sendReceiveFolder) pullerIteration(ignores *ignore.Matcher, ignoresChanged bool, scanChan chan<- string) int {
  171. pullChan := make(chan pullBlockState)
  172. copyChan := make(chan copyBlocksState)
  173. finisherChan := make(chan *sharedPullerState)
  174. dbUpdateChan := make(chan dbUpdateJob)
  175. pullWg := sync.NewWaitGroup()
  176. copyWg := sync.NewWaitGroup()
  177. doneWg := sync.NewWaitGroup()
  178. updateWg := sync.NewWaitGroup()
  179. l.Debugln(f, "copiers:", f.Copiers, "pullerPendingKiB:", f.PullerMaxPendingKiB)
  180. updateWg.Add(1)
  181. go func() {
  182. // dbUpdaterRoutine finishes when dbUpdateChan is closed
  183. f.dbUpdaterRoutine(dbUpdateChan)
  184. updateWg.Done()
  185. }()
  186. for i := 0; i < f.Copiers; i++ {
  187. copyWg.Add(1)
  188. go func() {
  189. // copierRoutine finishes when copyChan is closed
  190. f.copierRoutine(copyChan, pullChan, finisherChan)
  191. copyWg.Done()
  192. }()
  193. }
  194. pullWg.Add(1)
  195. go func() {
  196. // pullerRoutine finishes when pullChan is closed
  197. f.pullerRoutine(pullChan, finisherChan)
  198. pullWg.Done()
  199. }()
  200. doneWg.Add(1)
  201. // finisherRoutine finishes when finisherChan is closed
  202. go func() {
  203. f.finisherRoutine(ignores, finisherChan, dbUpdateChan, scanChan)
  204. doneWg.Done()
  205. }()
  206. f.model.fmut.RLock()
  207. folderFiles := f.model.folderFiles[f.folderID]
  208. f.model.fmut.RUnlock()
  209. changed := 0
  210. var processDirectly []protocol.FileInfo
  211. // Iterate the list of items that we need and sort them into piles.
  212. // Regular files to pull goes into the file queue, everything else
  213. // (directories, symlinks and deletes) goes into the "process directly"
  214. // pile.
  215. folderFiles.WithNeed(protocol.LocalDeviceID, func(intf db.FileIntf) bool {
  216. if f.IgnoreDelete && intf.IsDeleted() {
  217. l.Debugln(f, "ignore file deletion (config)", intf.FileName())
  218. return true
  219. }
  220. file := intf.(protocol.FileInfo)
  221. switch {
  222. case ignores.ShouldIgnore(file.Name):
  223. file.Invalidate(f.shortID)
  224. l.Debugln(f, "Handling ignored file", file)
  225. dbUpdateChan <- dbUpdateJob{file, dbUpdateInvalidate}
  226. changed++
  227. case runtime.GOOS == "windows" && fs.WindowsInvalidFilename(file.Name):
  228. f.newError("need", file.Name, fs.ErrInvalidFilename)
  229. changed++
  230. case file.IsDeleted():
  231. processDirectly = append(processDirectly, file)
  232. changed++
  233. case file.Type == protocol.FileInfoTypeFile:
  234. // Queue files for processing after directories and symlinks, if
  235. // it has availability.
  236. devices := folderFiles.Availability(file.Name)
  237. for _, dev := range devices {
  238. if _, ok := f.model.Connection(dev); ok {
  239. f.queue.Push(file.Name, file.Size, file.ModTime())
  240. changed++
  241. return true
  242. }
  243. }
  244. l.Debugln(f, "Needed file is unavailable", file)
  245. case runtime.GOOS == "windows" && file.IsSymlink():
  246. file.Invalidate(f.shortID)
  247. l.Debugln(f, "Invalidating symlink (unsupported)", file.Name)
  248. dbUpdateChan <- dbUpdateJob{file, dbUpdateInvalidate}
  249. changed++
  250. default:
  251. // Directories, symlinks
  252. processDirectly = append(processDirectly, file)
  253. changed++
  254. }
  255. return true
  256. })
  257. // Sort the "process directly" pile by number of path components. This
  258. // ensures that we handle parents before children.
  259. sort.Sort(byComponentCount(processDirectly))
  260. // Process the list.
  261. fileDeletions := map[string]protocol.FileInfo{}
  262. dirDeletions := []protocol.FileInfo{}
  263. buckets := map[string][]protocol.FileInfo{}
  264. for _, fi := range processDirectly {
  265. // Verify that the thing we are handling lives inside a directory,
  266. // and not a symlink or empty space.
  267. if err := osutil.TraversesSymlink(f.fs, filepath.Dir(fi.Name)); err != nil {
  268. f.newError("traverses d", fi.Name, err)
  269. continue
  270. }
  271. switch {
  272. case fi.IsDeleted():
  273. // A deleted file, directory or symlink
  274. if fi.IsDirectory() {
  275. // Perform directory deletions at the end, as we may have
  276. // files to delete inside them before we get to that point.
  277. dirDeletions = append(dirDeletions, fi)
  278. } else {
  279. fileDeletions[fi.Name] = fi
  280. df, ok := f.model.CurrentFolderFile(f.folderID, fi.Name)
  281. // Local file can be already deleted, but with a lower version
  282. // number, hence the deletion coming in again as part of
  283. // WithNeed, furthermore, the file can simply be of the wrong
  284. // type if we haven't yet managed to pull it.
  285. if ok && !df.IsDeleted() && !df.IsSymlink() && !df.IsDirectory() && !df.IsInvalid() {
  286. // Put files into buckets per first hash
  287. key := string(df.Blocks[0].Hash)
  288. buckets[key] = append(buckets[key], df)
  289. }
  290. }
  291. case fi.IsDirectory() && !fi.IsSymlink():
  292. l.Debugln(f, "Handling directory", fi.Name)
  293. f.handleDir(fi, dbUpdateChan)
  294. case fi.IsSymlink():
  295. l.Debugln("Handling symlink", fi.Name)
  296. l.Debugln(f, "Handling symlink", fi.Name)
  297. f.handleSymlink(fi, dbUpdateChan)
  298. default:
  299. l.Warnln(fi)
  300. panic("unhandleable item type, can't happen")
  301. }
  302. }
  303. // Now do the file queue. Reorder it according to configuration.
  304. switch f.Order {
  305. case config.OrderRandom:
  306. f.queue.Shuffle()
  307. case config.OrderAlphabetic:
  308. // The queue is already in alphabetic order.
  309. case config.OrderSmallestFirst:
  310. f.queue.SortSmallestFirst()
  311. case config.OrderLargestFirst:
  312. f.queue.SortLargestFirst()
  313. case config.OrderOldestFirst:
  314. f.queue.SortOldestFirst()
  315. case config.OrderNewestFirst:
  316. f.queue.SortNewestFirst()
  317. }
  318. // Process the file queue.
  319. nextFile:
  320. for {
  321. select {
  322. case <-f.ctx.Done():
  323. // Stop processing files if the puller has been told to stop.
  324. break nextFile
  325. default:
  326. }
  327. fileName, ok := f.queue.Pop()
  328. if !ok {
  329. break
  330. }
  331. fi, ok := f.model.CurrentGlobalFile(f.folderID, fileName)
  332. if !ok {
  333. // File is no longer in the index. Mark it as done and drop it.
  334. f.queue.Done(fileName)
  335. continue
  336. }
  337. if fi.IsDeleted() || fi.Type != protocol.FileInfoTypeFile {
  338. // The item has changed type or status in the index while we
  339. // were processing directories above.
  340. f.queue.Done(fileName)
  341. continue
  342. }
  343. dirName := filepath.Dir(fi.Name)
  344. // Verify that the thing we are handling lives inside a directory,
  345. // and not a symlink or empty space.
  346. if err := osutil.TraversesSymlink(f.fs, dirName); err != nil {
  347. f.newError("traverses q", fi.Name, err)
  348. continue
  349. }
  350. // issues #114 and #4475: This works around a race condition
  351. // between two devices, when one device removes a directory and the
  352. // other creates a file in it. However that happens, we end up with
  353. // a directory for "foo" with the delete bit, but a file "foo/bar"
  354. // that we want to sync. We never create the directory, and hence
  355. // fail to create the file and end up looping forever on it. This
  356. // breaks that by creating the directory and scheduling a scan,
  357. // where it will be found and the delete bit on it removed. The
  358. // user can then clean up as they like...
  359. if _, err := f.fs.Lstat(dirName); fs.IsNotExist(err) {
  360. l.Debugln("%v resurrecting parent directory of %v", f, fi.Name)
  361. if err := f.fs.MkdirAll(dirName, 0755); err != nil {
  362. f.newError("resurrecting parent dir", fi.Name, err)
  363. continue
  364. }
  365. scanChan <- dirName
  366. }
  367. // Check our list of files to be removed for a match, in which case
  368. // we can just do a rename instead.
  369. key := string(fi.Blocks[0].Hash)
  370. for i, candidate := range buckets[key] {
  371. if protocol.BlocksEqual(candidate.Blocks, fi.Blocks) {
  372. // Remove the candidate from the bucket
  373. lidx := len(buckets[key]) - 1
  374. buckets[key][i] = buckets[key][lidx]
  375. buckets[key] = buckets[key][:lidx]
  376. // candidate is our current state of the file, where as the
  377. // desired state with the delete bit set is in the deletion
  378. // map.
  379. desired := fileDeletions[candidate.Name]
  380. // Remove the pending deletion (as we perform it by renaming)
  381. delete(fileDeletions, candidate.Name)
  382. f.renameFile(desired, fi, dbUpdateChan)
  383. f.queue.Done(fileName)
  384. continue nextFile
  385. }
  386. }
  387. // Handle the file normally, by coping and pulling, etc.
  388. f.handleFile(fi, copyChan, finisherChan, dbUpdateChan)
  389. }
  390. // Signal copy and puller routines that we are done with the in data for
  391. // this iteration. Wait for them to finish.
  392. close(copyChan)
  393. copyWg.Wait()
  394. close(pullChan)
  395. pullWg.Wait()
  396. // Signal the finisher chan that there will be no more input.
  397. close(finisherChan)
  398. // Wait for the finisherChan to finish.
  399. doneWg.Wait()
  400. for _, file := range fileDeletions {
  401. l.Debugln(f, "Deleting file", file.Name)
  402. f.deleteFile(file, dbUpdateChan)
  403. }
  404. for i := range dirDeletions {
  405. dir := dirDeletions[len(dirDeletions)-i-1]
  406. l.Debugln(f, "Deleting dir", dir.Name)
  407. f.handleDeleteDir(dir, ignores, dbUpdateChan, scanChan)
  408. }
  409. // Wait for db updates and scan scheduling to complete
  410. close(dbUpdateChan)
  411. updateWg.Wait()
  412. return changed
  413. }
  414. // handleDir creates or updates the given directory
  415. func (f *sendReceiveFolder) handleDir(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob) {
  416. // Used in the defer closure below, updated by the function body. Take
  417. // care not declare another err.
  418. var err error
  419. events.Default.Log(events.ItemStarted, map[string]string{
  420. "folder": f.folderID,
  421. "item": file.Name,
  422. "type": "dir",
  423. "action": "update",
  424. })
  425. defer func() {
  426. events.Default.Log(events.ItemFinished, map[string]interface{}{
  427. "folder": f.folderID,
  428. "item": file.Name,
  429. "error": events.Error(err),
  430. "type": "dir",
  431. "action": "update",
  432. })
  433. }()
  434. mode := fs.FileMode(file.Permissions & 0777)
  435. if f.IgnorePerms || file.NoPermissions {
  436. mode = 0777
  437. }
  438. if shouldDebug() {
  439. curFile, _ := f.model.CurrentFolderFile(f.folderID, file.Name)
  440. l.Debugf("need dir\n\t%v\n\t%v", file, curFile)
  441. }
  442. info, err := f.fs.Lstat(file.Name)
  443. switch {
  444. // There is already something under that name, but it's a file/link.
  445. // Most likely a file/link is getting replaced with a directory.
  446. // Remove the file/link and fall through to directory creation.
  447. case err == nil && (!info.IsDir() || info.IsSymlink()):
  448. err = osutil.InWritableDir(f.fs.Remove, f.fs, file.Name)
  449. if err != nil {
  450. f.newError("dir replace", file.Name, err)
  451. return
  452. }
  453. fallthrough
  454. // The directory doesn't exist, so we create it with the right
  455. // mode bits from the start.
  456. case err != nil && fs.IsNotExist(err):
  457. // We declare a function that acts on only the path name, so
  458. // we can pass it to InWritableDir. We use a regular Mkdir and
  459. // not MkdirAll because the parent should already exist.
  460. mkdir := func(path string) error {
  461. err = f.fs.Mkdir(path, mode)
  462. if err != nil || f.IgnorePerms || file.NoPermissions {
  463. return err
  464. }
  465. // Stat the directory so we can check its permissions.
  466. info, err := f.fs.Lstat(path)
  467. if err != nil {
  468. return err
  469. }
  470. // Mask for the bits we want to preserve and add them in to the
  471. // directories permissions.
  472. return f.fs.Chmod(path, mode|(info.Mode()&retainBits))
  473. }
  474. if err = osutil.InWritableDir(mkdir, f.fs, file.Name); err == nil {
  475. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  476. } else {
  477. f.newError("dir mkdir", file.Name, err)
  478. }
  479. return
  480. // Weird error when stat()'ing the dir. Probably won't work to do
  481. // anything else with it if we can't even stat() it.
  482. case err != nil:
  483. f.newError("dir stat", file.Name, err)
  484. return
  485. }
  486. // The directory already exists, so we just correct the mode bits. (We
  487. // don't handle modification times on directories, because that sucks...)
  488. // It's OK to change mode bits on stuff within non-writable directories.
  489. if f.IgnorePerms || file.NoPermissions {
  490. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  491. } else if err := f.fs.Chmod(file.Name, mode|(fs.FileMode(info.Mode())&retainBits)); err == nil {
  492. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  493. } else {
  494. f.newError("dir chmod", file.Name, err)
  495. }
  496. }
  497. // handleSymlink creates or updates the given symlink
  498. func (f *sendReceiveFolder) handleSymlink(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob) {
  499. // Used in the defer closure below, updated by the function body. Take
  500. // care not declare another err.
  501. var err error
  502. events.Default.Log(events.ItemStarted, map[string]string{
  503. "folder": f.folderID,
  504. "item": file.Name,
  505. "type": "symlink",
  506. "action": "update",
  507. })
  508. defer func() {
  509. events.Default.Log(events.ItemFinished, map[string]interface{}{
  510. "folder": f.folderID,
  511. "item": file.Name,
  512. "error": events.Error(err),
  513. "type": "symlink",
  514. "action": "update",
  515. })
  516. }()
  517. if shouldDebug() {
  518. curFile, _ := f.model.CurrentFolderFile(f.folderID, file.Name)
  519. l.Debugf("need symlink\n\t%v\n\t%v", file, curFile)
  520. }
  521. if len(file.SymlinkTarget) == 0 {
  522. // Index entry from a Syncthing predating the support for including
  523. // the link target in the index entry. We log this as an error.
  524. err = errors.New("incompatible symlink entry; rescan with newer Syncthing on source")
  525. f.newError("symlink", file.Name, err)
  526. return
  527. }
  528. if _, err = f.fs.Lstat(file.Name); err == nil {
  529. // There is already something under that name. Remove it to replace
  530. // with the symlink. This also handles the "change symlink type"
  531. // path.
  532. err = osutil.InWritableDir(f.fs.Remove, f.fs, file.Name)
  533. if err != nil {
  534. f.newError("symlink remove", file.Name, err)
  535. return
  536. }
  537. }
  538. // We declare a function that acts on only the path name, so
  539. // we can pass it to InWritableDir.
  540. createLink := func(path string) error {
  541. return f.fs.CreateSymlink(file.SymlinkTarget, path)
  542. }
  543. if err = osutil.InWritableDir(createLink, f.fs, file.Name); err == nil {
  544. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleSymlink}
  545. } else {
  546. f.newError("symlink create", file.Name, err)
  547. }
  548. }
  549. // handleDeleteDir attempts to remove a directory that was deleted on a remote
  550. func (f *sendReceiveFolder) handleDeleteDir(file protocol.FileInfo, ignores *ignore.Matcher, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  551. // Used in the defer closure below, updated by the function body. Take
  552. // care not declare another err.
  553. var err error
  554. events.Default.Log(events.ItemStarted, map[string]string{
  555. "folder": f.folderID,
  556. "item": file.Name,
  557. "type": "dir",
  558. "action": "delete",
  559. })
  560. defer func() {
  561. events.Default.Log(events.ItemFinished, map[string]interface{}{
  562. "folder": f.folderID,
  563. "item": file.Name,
  564. "error": events.Error(err),
  565. "type": "dir",
  566. "action": "delete",
  567. })
  568. }()
  569. err = f.deleteDir(file.Name, ignores, scanChan)
  570. if err != nil {
  571. f.newError("delete dir", file.Name, err)
  572. return
  573. }
  574. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  575. }
  576. // deleteFile attempts to delete the given file
  577. func (f *sendReceiveFolder) deleteFile(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob) {
  578. // Used in the defer closure below, updated by the function body. Take
  579. // care not declare another err.
  580. var err error
  581. events.Default.Log(events.ItemStarted, map[string]string{
  582. "folder": f.folderID,
  583. "item": file.Name,
  584. "type": "file",
  585. "action": "delete",
  586. })
  587. defer func() {
  588. events.Default.Log(events.ItemFinished, map[string]interface{}{
  589. "folder": f.folderID,
  590. "item": file.Name,
  591. "error": events.Error(err),
  592. "type": "file",
  593. "action": "delete",
  594. })
  595. }()
  596. cur, ok := f.model.CurrentFolderFile(f.folderID, file.Name)
  597. if ok && f.inConflict(cur.Version, file.Version) {
  598. // There is a conflict here. Move the file to a conflict copy instead
  599. // of deleting. Also merge with the version vector we had, to indicate
  600. // we have resolved the conflict.
  601. file.Version = file.Version.Merge(cur.Version)
  602. err = osutil.InWritableDir(func(name string) error {
  603. return f.moveForConflict(name, file.ModifiedBy.String())
  604. }, f.fs, file.Name)
  605. } else if f.versioner != nil && !cur.IsSymlink() {
  606. err = osutil.InWritableDir(f.versioner.Archive, f.fs, file.Name)
  607. } else {
  608. err = osutil.InWritableDir(f.fs.Remove, f.fs, file.Name)
  609. }
  610. if err == nil || fs.IsNotExist(err) {
  611. // It was removed or it doesn't exist to start with
  612. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  613. } else if _, serr := f.fs.Lstat(file.Name); serr != nil && !fs.IsPermission(serr) {
  614. // We get an error just looking at the file, and it's not a permission
  615. // problem. Lets assume the error is in fact some variant of "file
  616. // does not exist" (possibly expressed as some parent being a file and
  617. // not a directory etc) and that the delete is handled.
  618. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  619. } else {
  620. f.newError("delete file", file.Name, err)
  621. }
  622. }
  623. // renameFile attempts to rename an existing file to a destination
  624. // and set the right attributes on it.
  625. func (f *sendReceiveFolder) renameFile(source, target protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob) {
  626. // Used in the defer closure below, updated by the function body. Take
  627. // care not declare another err.
  628. var err error
  629. events.Default.Log(events.ItemStarted, map[string]string{
  630. "folder": f.folderID,
  631. "item": source.Name,
  632. "type": "file",
  633. "action": "delete",
  634. })
  635. events.Default.Log(events.ItemStarted, map[string]string{
  636. "folder": f.folderID,
  637. "item": target.Name,
  638. "type": "file",
  639. "action": "update",
  640. })
  641. defer func() {
  642. events.Default.Log(events.ItemFinished, map[string]interface{}{
  643. "folder": f.folderID,
  644. "item": source.Name,
  645. "error": events.Error(err),
  646. "type": "file",
  647. "action": "delete",
  648. })
  649. events.Default.Log(events.ItemFinished, map[string]interface{}{
  650. "folder": f.folderID,
  651. "item": target.Name,
  652. "error": events.Error(err),
  653. "type": "file",
  654. "action": "update",
  655. })
  656. }()
  657. l.Debugln(f, "taking rename shortcut", source.Name, "->", target.Name)
  658. if f.versioner != nil {
  659. err = osutil.Copy(f.fs, source.Name, target.Name)
  660. if err == nil {
  661. err = osutil.InWritableDir(f.versioner.Archive, f.fs, source.Name)
  662. }
  663. } else {
  664. err = osutil.TryRename(f.fs, source.Name, target.Name)
  665. }
  666. if err == nil {
  667. blockStatsMut.Lock()
  668. blockStats["total"] += len(target.Blocks)
  669. blockStats["renamed"] += len(target.Blocks)
  670. blockStatsMut.Unlock()
  671. // The file was renamed, so we have handled both the necessary delete
  672. // of the source and the creation of the target. Fix-up the metadata,
  673. // and update the local index of the target file.
  674. dbUpdateChan <- dbUpdateJob{source, dbUpdateDeleteFile}
  675. err = f.shortcutFile(target)
  676. if err != nil {
  677. err = fmt.Errorf("from %s: %s", source.Name, err.Error())
  678. f.newError("rename shortcut", target.Name, err)
  679. return
  680. }
  681. dbUpdateChan <- dbUpdateJob{target, dbUpdateHandleFile}
  682. } else {
  683. // We failed the rename so we have a source file that we still need to
  684. // get rid of. Attempt to delete it instead so that we make *some*
  685. // progress. The target is unhandled.
  686. err = osutil.InWritableDir(f.fs.Remove, f.fs, source.Name)
  687. if err != nil {
  688. err = fmt.Errorf("from %s: %s", source.Name, err.Error())
  689. f.newError("rename delete", target.Name, err)
  690. return
  691. }
  692. dbUpdateChan <- dbUpdateJob{source, dbUpdateDeleteFile}
  693. }
  694. }
  695. // This is the flow of data and events here, I think...
  696. //
  697. // +-----------------------+
  698. // | | - - - - > ItemStarted
  699. // | handleFile | - - - - > ItemFinished (on shortcuts)
  700. // | |
  701. // +-----------------------+
  702. // |
  703. // | copyChan (copyBlocksState; unless shortcut taken)
  704. // |
  705. // | +-----------------------+
  706. // | | +-----------------------+
  707. // +--->| | |
  708. // | | copierRoutine |
  709. // +-| |
  710. // +-----------------------+
  711. // |
  712. // | pullChan (sharedPullerState)
  713. // |
  714. // | +-----------------------+
  715. // | | +-----------------------+
  716. // +-->| | |
  717. // | | pullerRoutine |
  718. // +-| |
  719. // +-----------------------+
  720. // |
  721. // | finisherChan (sharedPullerState)
  722. // |
  723. // | +-----------------------+
  724. // | | |
  725. // +-->| finisherRoutine | - - - - > ItemFinished
  726. // | |
  727. // +-----------------------+
  728. // handleFile queues the copies and pulls as necessary for a single new or
  729. // changed file.
  730. func (f *sendReceiveFolder) handleFile(file protocol.FileInfo, copyChan chan<- copyBlocksState, finisherChan chan<- *sharedPullerState, dbUpdateChan chan<- dbUpdateJob) {
  731. curFile, hasCurFile := f.model.CurrentFolderFile(f.folderID, file.Name)
  732. have, need := blockDiff(curFile.Blocks, file.Blocks)
  733. if hasCurFile && len(need) == 0 {
  734. // We are supposed to copy the entire file, and then fetch nothing. We
  735. // are only updating metadata, so we don't actually *need* to make the
  736. // copy.
  737. l.Debugln(f, "taking shortcut on", file.Name)
  738. events.Default.Log(events.ItemStarted, map[string]string{
  739. "folder": f.folderID,
  740. "item": file.Name,
  741. "type": "file",
  742. "action": "metadata",
  743. })
  744. f.queue.Done(file.Name)
  745. err := f.shortcutFile(file)
  746. events.Default.Log(events.ItemFinished, map[string]interface{}{
  747. "folder": f.folderID,
  748. "item": file.Name,
  749. "error": events.Error(err),
  750. "type": "file",
  751. "action": "metadata",
  752. })
  753. if err != nil {
  754. f.newError("shortcut", file.Name, err)
  755. } else {
  756. dbUpdateChan <- dbUpdateJob{file, dbUpdateShortcutFile}
  757. }
  758. return
  759. }
  760. tempName := fs.TempName(file.Name)
  761. populateOffsets(file.Blocks)
  762. blocks := make([]protocol.BlockInfo, 0, len(file.Blocks))
  763. var blocksSize int64
  764. reused := make([]int32, 0, len(file.Blocks))
  765. // Check for an old temporary file which might have some blocks we could
  766. // reuse.
  767. tempBlocks, err := scanner.HashFile(f.ctx, f.fs, tempName, file.BlockSize(), nil, false)
  768. if err == nil {
  769. // Check for any reusable blocks in the temp file
  770. tempCopyBlocks, _ := blockDiff(tempBlocks, file.Blocks)
  771. // block.String() returns a string unique to the block
  772. existingBlocks := make(map[string]struct{}, len(tempCopyBlocks))
  773. for _, block := range tempCopyBlocks {
  774. existingBlocks[block.String()] = struct{}{}
  775. }
  776. // Since the blocks are already there, we don't need to get them.
  777. for i, block := range file.Blocks {
  778. _, ok := existingBlocks[block.String()]
  779. if !ok {
  780. blocks = append(blocks, block)
  781. blocksSize += int64(block.Size)
  782. } else {
  783. reused = append(reused, int32(i))
  784. }
  785. }
  786. // The sharedpullerstate will know which flags to use when opening the
  787. // temp file depending if we are reusing any blocks or not.
  788. if len(reused) == 0 {
  789. // Otherwise, discard the file ourselves in order for the
  790. // sharedpuller not to panic when it fails to exclusively create a
  791. // file which already exists
  792. osutil.InWritableDir(f.fs.Remove, f.fs, tempName)
  793. }
  794. } else {
  795. // Copy the blocks, as we don't want to shuffle them on the FileInfo
  796. blocks = append(blocks, file.Blocks...)
  797. blocksSize = file.Size
  798. }
  799. if f.MinDiskFree.BaseValue() > 0 {
  800. if usage, err := f.fs.Usage("."); err == nil && usage.Free < blocksSize {
  801. l.Warnf(`Folder "%s": insufficient disk space in %s for %s: have %.2f MiB, need %.2f MiB`, f.folderID, f.fs.URI(), file.Name, float64(usage.Free)/1024/1024, float64(blocksSize)/1024/1024)
  802. f.newError("disk space", file.Name, errors.New("insufficient space"))
  803. return
  804. }
  805. }
  806. // Shuffle the blocks
  807. for i := range blocks {
  808. j := rand.Intn(i + 1)
  809. blocks[i], blocks[j] = blocks[j], blocks[i]
  810. }
  811. events.Default.Log(events.ItemStarted, map[string]string{
  812. "folder": f.folderID,
  813. "item": file.Name,
  814. "type": "file",
  815. "action": "update",
  816. })
  817. s := sharedPullerState{
  818. file: file,
  819. fs: f.fs,
  820. folder: f.folderID,
  821. tempName: tempName,
  822. realName: file.Name,
  823. copyTotal: len(blocks),
  824. copyNeeded: len(blocks),
  825. reused: len(reused),
  826. updated: time.Now(),
  827. available: reused,
  828. availableUpdated: time.Now(),
  829. ignorePerms: f.IgnorePerms || file.NoPermissions,
  830. hasCurFile: hasCurFile,
  831. curFile: curFile,
  832. mut: sync.NewRWMutex(),
  833. sparse: !f.DisableSparseFiles,
  834. created: time.Now(),
  835. }
  836. l.Debugf("%v need file %s; copy %d, reused %v", f, file.Name, len(blocks), len(reused))
  837. cs := copyBlocksState{
  838. sharedPullerState: &s,
  839. blocks: blocks,
  840. have: len(have),
  841. }
  842. copyChan <- cs
  843. }
  844. // blockDiff returns lists of common and missing (to transform src into tgt)
  845. // blocks. Both block lists must have been created with the same block size.
  846. func blockDiff(src, tgt []protocol.BlockInfo) ([]protocol.BlockInfo, []protocol.BlockInfo) {
  847. if len(tgt) == 0 {
  848. return nil, nil
  849. }
  850. if len(src) == 0 {
  851. // Copy the entire file
  852. return nil, tgt
  853. }
  854. have := make([]protocol.BlockInfo, 0, len(src))
  855. need := make([]protocol.BlockInfo, 0, len(tgt))
  856. for i := range tgt {
  857. if i >= len(src) {
  858. return have, append(need, tgt[i:]...)
  859. }
  860. if !bytes.Equal(tgt[i].Hash, src[i].Hash) {
  861. // Copy differing block
  862. need = append(need, tgt[i])
  863. } else {
  864. have = append(have, tgt[i])
  865. }
  866. }
  867. return have, need
  868. }
  869. // populateOffsets sets the Offset field on each block
  870. func populateOffsets(blocks []protocol.BlockInfo) {
  871. var offset int64
  872. for i := range blocks {
  873. blocks[i].Offset = offset
  874. offset += int64(blocks[i].Size)
  875. }
  876. }
  877. // shortcutFile sets file mode and modification time, when that's the only
  878. // thing that has changed.
  879. func (f *sendReceiveFolder) shortcutFile(file protocol.FileInfo) error {
  880. if !f.IgnorePerms && !file.NoPermissions {
  881. if err := f.fs.Chmod(file.Name, fs.FileMode(file.Permissions&0777)); err != nil {
  882. f.newError("shortcut chmod", file.Name, err)
  883. return err
  884. }
  885. }
  886. f.fs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  887. // This may have been a conflict. We should merge the version vectors so
  888. // that our clock doesn't move backwards.
  889. if cur, ok := f.model.CurrentFolderFile(f.folderID, file.Name); ok {
  890. file.Version = file.Version.Merge(cur.Version)
  891. }
  892. return nil
  893. }
  894. // copierRoutine reads copierStates until the in channel closes and performs
  895. // the relevant copies when possible, or passes it to the puller routine.
  896. func (f *sendReceiveFolder) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
  897. buf := make([]byte, protocol.MinBlockSize)
  898. for state := range in {
  899. dstFd, err := state.tempFile()
  900. if err != nil {
  901. // Nothing more to do for this failed file, since we couldn't create a temporary for it.
  902. out <- state.sharedPullerState
  903. continue
  904. }
  905. if f.model.progressEmitter != nil {
  906. f.model.progressEmitter.Register(state.sharedPullerState)
  907. }
  908. folderFilesystems := make(map[string]fs.Filesystem)
  909. var folders []string
  910. f.model.fmut.RLock()
  911. for folder, cfg := range f.model.folderCfgs {
  912. folderFilesystems[folder] = cfg.Filesystem()
  913. folders = append(folders, folder)
  914. }
  915. f.model.fmut.RUnlock()
  916. var file fs.File
  917. var weakHashFinder *weakhash.Finder
  918. blocksPercentChanged := 0
  919. if tot := len(state.file.Blocks); tot > 0 {
  920. blocksPercentChanged = (tot - state.have) * 100 / tot
  921. }
  922. if blocksPercentChanged >= f.WeakHashThresholdPct {
  923. hashesToFind := make([]uint32, 0, len(state.blocks))
  924. for _, block := range state.blocks {
  925. if block.WeakHash != 0 {
  926. hashesToFind = append(hashesToFind, block.WeakHash)
  927. }
  928. }
  929. if len(hashesToFind) > 0 {
  930. file, err = f.fs.Open(state.file.Name)
  931. if err == nil {
  932. weakHashFinder, err = weakhash.NewFinder(file, int(state.file.BlockSize()), hashesToFind)
  933. if err != nil {
  934. l.Debugln("weak hasher", err)
  935. }
  936. }
  937. } else {
  938. l.Debugf("not weak hashing %s. file did not contain any weak hashes", state.file.Name)
  939. }
  940. } else {
  941. l.Debugf("not weak hashing %s. not enough changed %.02f < %d", state.file.Name, blocksPercentChanged, f.WeakHashThresholdPct)
  942. }
  943. for _, block := range state.blocks {
  944. if !f.DisableSparseFiles && state.reused == 0 && block.IsEmpty() {
  945. // The block is a block of all zeroes, and we are not reusing
  946. // a temp file, so there is no need to do anything with it.
  947. // If we were reusing a temp file and had this block to copy,
  948. // it would be because the block in the temp file was *not* a
  949. // block of all zeroes, so then we should not skip it.
  950. // Pretend we copied it.
  951. state.copiedFromOrigin()
  952. state.copyDone(block)
  953. continue
  954. }
  955. if s := int(block.Size); s > cap(buf) {
  956. buf = make([]byte, s)
  957. } else {
  958. buf = buf[:s]
  959. }
  960. found, err := weakHashFinder.Iterate(block.WeakHash, buf, func(offset int64) bool {
  961. if verifyBuffer(buf, block) != nil {
  962. return true
  963. }
  964. _, err = dstFd.WriteAt(buf, block.Offset)
  965. if err != nil {
  966. state.fail("dst write", err)
  967. }
  968. if offset == block.Offset {
  969. state.copiedFromOrigin()
  970. } else {
  971. state.copiedFromOriginShifted()
  972. }
  973. return false
  974. })
  975. if err != nil {
  976. l.Debugln("weak hasher iter", err)
  977. }
  978. if !found {
  979. found = f.model.finder.Iterate(folders, block.Hash, func(folder, path string, index int32) bool {
  980. fs := folderFilesystems[folder]
  981. fd, err := fs.Open(path)
  982. if err != nil {
  983. return false
  984. }
  985. _, err = fd.ReadAt(buf, int64(state.file.BlockSize())*int64(index))
  986. fd.Close()
  987. if err != nil {
  988. return false
  989. }
  990. if err := verifyBuffer(buf, block); err != nil {
  991. l.Debugln("Finder failed to verify buffer", err)
  992. return false
  993. }
  994. _, err = dstFd.WriteAt(buf, block.Offset)
  995. if err != nil {
  996. state.fail("dst write", err)
  997. }
  998. if path == state.file.Name {
  999. state.copiedFromOrigin()
  1000. }
  1001. return true
  1002. })
  1003. }
  1004. if state.failed() != nil {
  1005. break
  1006. }
  1007. if !found {
  1008. state.pullStarted()
  1009. ps := pullBlockState{
  1010. sharedPullerState: state.sharedPullerState,
  1011. block: block,
  1012. }
  1013. pullChan <- ps
  1014. } else {
  1015. state.copyDone(block)
  1016. }
  1017. }
  1018. if file != nil {
  1019. // os.File used to return invalid argument if nil.
  1020. // fs.File panics as it's an interface.
  1021. file.Close()
  1022. }
  1023. out <- state.sharedPullerState
  1024. }
  1025. }
  1026. func verifyBuffer(buf []byte, block protocol.BlockInfo) error {
  1027. if len(buf) != int(block.Size) {
  1028. return fmt.Errorf("length mismatch %d != %d", len(buf), block.Size)
  1029. }
  1030. hf := sha256.New()
  1031. _, err := hf.Write(buf)
  1032. if err != nil {
  1033. return err
  1034. }
  1035. hash := hf.Sum(nil)
  1036. if !bytes.Equal(hash, block.Hash) {
  1037. return fmt.Errorf("hash mismatch %x != %x", hash, block.Hash)
  1038. }
  1039. return nil
  1040. }
  1041. func (f *sendReceiveFolder) pullerRoutine(in <-chan pullBlockState, out chan<- *sharedPullerState) {
  1042. requestLimiter := newByteSemaphore(f.PullerMaxPendingKiB * 1024)
  1043. wg := sync.NewWaitGroup()
  1044. for state := range in {
  1045. if state.failed() != nil {
  1046. out <- state.sharedPullerState
  1047. continue
  1048. }
  1049. // The requestLimiter limits how many pending block requests we have
  1050. // ongoing at any given time, based on the size of the blocks
  1051. // themselves.
  1052. state := state
  1053. bytes := int(state.block.Size)
  1054. requestLimiter.take(bytes)
  1055. wg.Add(1)
  1056. go func() {
  1057. defer wg.Done()
  1058. defer requestLimiter.give(bytes)
  1059. f.pullBlock(state, out)
  1060. }()
  1061. }
  1062. wg.Wait()
  1063. }
  1064. func (f *sendReceiveFolder) pullBlock(state pullBlockState, out chan<- *sharedPullerState) {
  1065. // Get an fd to the temporary file. Technically we don't need it until
  1066. // after fetching the block, but if we run into an error here there is
  1067. // no point in issuing the request to the network.
  1068. fd, err := state.tempFile()
  1069. if err != nil {
  1070. out <- state.sharedPullerState
  1071. return
  1072. }
  1073. if !f.DisableSparseFiles && state.reused == 0 && state.block.IsEmpty() {
  1074. // There is no need to request a block of all zeroes. Pretend we
  1075. // requested it and handled it correctly.
  1076. state.pullDone(state.block)
  1077. out <- state.sharedPullerState
  1078. return
  1079. }
  1080. var lastError error
  1081. candidates := f.model.Availability(f.folderID, state.file, state.block)
  1082. for {
  1083. // Select the least busy device to pull the block from. If we found no
  1084. // feasible device at all, fail the block (and in the long run, the
  1085. // file).
  1086. selected, found := activity.leastBusy(candidates)
  1087. if !found {
  1088. if lastError != nil {
  1089. state.fail("pull", lastError)
  1090. } else {
  1091. state.fail("pull", errNoDevice)
  1092. }
  1093. break
  1094. }
  1095. candidates = removeAvailability(candidates, selected)
  1096. // Fetch the block, while marking the selected device as in use so that
  1097. // leastBusy can select another device when someone else asks.
  1098. activity.using(selected)
  1099. buf, lastError := f.model.requestGlobal(selected.ID, f.folderID, state.file.Name, state.block.Offset, int(state.block.Size), state.block.Hash, state.block.WeakHash, selected.FromTemporary)
  1100. activity.done(selected)
  1101. if lastError != nil {
  1102. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, "returned error:", lastError)
  1103. continue
  1104. }
  1105. // Verify that the received block matches the desired hash, if not
  1106. // try pulling it from another device.
  1107. lastError = verifyBuffer(buf, state.block)
  1108. if lastError != nil {
  1109. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, "hash mismatch")
  1110. continue
  1111. }
  1112. // Save the block data we got from the cluster
  1113. _, err = fd.WriteAt(buf, state.block.Offset)
  1114. if err != nil {
  1115. state.fail("save", err)
  1116. } else {
  1117. state.pullDone(state.block)
  1118. }
  1119. break
  1120. }
  1121. out <- state.sharedPullerState
  1122. }
  1123. func (f *sendReceiveFolder) performFinish(ignores *ignore.Matcher, state *sharedPullerState, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  1124. // Set the correct permission bits on the new file
  1125. if !f.IgnorePerms && !state.file.NoPermissions {
  1126. if err := f.fs.Chmod(state.tempName, fs.FileMode(state.file.Permissions&0777)); err != nil {
  1127. return err
  1128. }
  1129. }
  1130. if stat, err := f.fs.Lstat(state.file.Name); err == nil {
  1131. // There is an old file or directory already in place. We need to
  1132. // handle that.
  1133. curMode := uint32(stat.Mode())
  1134. if runtime.GOOS == "windows" && osutil.IsWindowsExecutable(state.file.Name) {
  1135. curMode |= 0111
  1136. }
  1137. // Check that the file on disk is what we expect it to be according
  1138. // to the database. If there's a mismatch here, there might be local
  1139. // changes that we don't know about yet and we should scan before
  1140. // touching the file. There is also a case where we think the file
  1141. // should be there, but it was removed, which is a conflict, yet
  1142. // creations always wins when competing with a deletion, so no need
  1143. // to handle that specially.
  1144. changed := false
  1145. switch {
  1146. case !state.hasCurFile:
  1147. // The file appeared from nowhere
  1148. l.Debugln("file exists but not scanned; not finishing:", state.file.Name)
  1149. changed = true
  1150. case stat.IsDir() != state.curFile.IsDirectory() || stat.IsSymlink() != state.curFile.IsSymlink():
  1151. // The file changed type. IsRegular is implicitly tested in the condition above
  1152. l.Debugln("file type changed but not rescanned; not finishing:", state.curFile.Name)
  1153. changed = true
  1154. case stat.IsRegular():
  1155. if !stat.ModTime().Equal(state.curFile.ModTime()) || stat.Size() != state.curFile.Size {
  1156. l.Debugln("file modified but not rescanned; not finishing:", state.curFile.Name)
  1157. changed = true
  1158. break
  1159. }
  1160. // check permissions
  1161. fallthrough
  1162. case stat.IsDir():
  1163. // Dirs only have perm, no modetime/size
  1164. if !f.IgnorePerms && !state.curFile.NoPermissions && state.curFile.HasPermissionBits() && !protocol.PermsEqual(state.curFile.Permissions, curMode) {
  1165. l.Debugln("file permission modified but not rescanned; not finishing:", state.curFile.Name)
  1166. changed = true
  1167. }
  1168. }
  1169. if changed {
  1170. scanChan <- state.curFile.Name
  1171. return fmt.Errorf("file modified but not rescanned; will try again later")
  1172. }
  1173. switch {
  1174. case stat.IsDir() || stat.IsSymlink():
  1175. // It's a directory or a symlink. These are not versioned or
  1176. // archived for conflicts, only removed (which of course fails for
  1177. // non-empty directories).
  1178. if err = f.deleteDir(state.file.Name, ignores, scanChan); err != nil {
  1179. return err
  1180. }
  1181. case f.inConflict(state.curFile.Version, state.file.Version):
  1182. // The new file has been changed in conflict with the existing one. We
  1183. // should file it away as a conflict instead of just removing or
  1184. // archiving. Also merge with the version vector we had, to indicate
  1185. // we have resolved the conflict.
  1186. state.file.Version = state.file.Version.Merge(state.curFile.Version)
  1187. err = osutil.InWritableDir(func(name string) error {
  1188. return f.moveForConflict(name, state.file.ModifiedBy.String())
  1189. }, f.fs, state.file.Name)
  1190. if err != nil {
  1191. return err
  1192. }
  1193. case f.versioner != nil && !state.file.IsSymlink():
  1194. // If we should use versioning, let the versioner archive the old
  1195. // file before we replace it. Archiving a non-existent file is not
  1196. // an error.
  1197. if err = osutil.InWritableDir(f.versioner.Archive, f.fs, state.file.Name); err != nil {
  1198. return err
  1199. }
  1200. }
  1201. }
  1202. // Replace the original content with the new one. If it didn't work,
  1203. // leave the temp file in place for reuse.
  1204. if err := osutil.TryRename(f.fs, state.tempName, state.file.Name); err != nil {
  1205. return err
  1206. }
  1207. // Set the correct timestamp on the new file
  1208. f.fs.Chtimes(state.file.Name, state.file.ModTime(), state.file.ModTime()) // never fails
  1209. // Record the updated file in the index
  1210. dbUpdateChan <- dbUpdateJob{state.file, dbUpdateHandleFile}
  1211. return nil
  1212. }
  1213. func (f *sendReceiveFolder) finisherRoutine(ignores *ignore.Matcher, in <-chan *sharedPullerState, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  1214. for state := range in {
  1215. if closed, err := state.finalClose(); closed {
  1216. l.Debugln(f, "closing", state.file.Name)
  1217. f.queue.Done(state.file.Name)
  1218. if err == nil {
  1219. err = f.performFinish(ignores, state, dbUpdateChan, scanChan)
  1220. }
  1221. if err != nil {
  1222. f.newError("finisher", state.file.Name, err)
  1223. } else {
  1224. blockStatsMut.Lock()
  1225. blockStats["total"] += state.reused + state.copyTotal + state.pullTotal
  1226. blockStats["reused"] += state.reused
  1227. blockStats["pulled"] += state.pullTotal
  1228. // copyOriginShifted is counted towards copyOrigin due to progress bar reasons
  1229. // for reporting reasons we want to separate these.
  1230. blockStats["copyOrigin"] += state.copyOrigin - state.copyOriginShifted
  1231. blockStats["copyOriginShifted"] += state.copyOriginShifted
  1232. blockStats["copyElsewhere"] += state.copyTotal - state.copyOrigin
  1233. blockStatsMut.Unlock()
  1234. }
  1235. events.Default.Log(events.ItemFinished, map[string]interface{}{
  1236. "folder": f.folderID,
  1237. "item": state.file.Name,
  1238. "error": events.Error(err),
  1239. "type": "file",
  1240. "action": "update",
  1241. })
  1242. if f.model.progressEmitter != nil {
  1243. f.model.progressEmitter.Deregister(state)
  1244. }
  1245. }
  1246. }
  1247. }
  1248. // Moves the given filename to the front of the job queue
  1249. func (f *sendReceiveFolder) BringToFront(filename string) {
  1250. f.queue.BringToFront(filename)
  1251. }
  1252. func (f *sendReceiveFolder) Jobs() ([]string, []string) {
  1253. return f.queue.Jobs()
  1254. }
  1255. // dbUpdaterRoutine aggregates db updates and commits them in batches no
  1256. // larger than 1000 items, and no more delayed than 2 seconds.
  1257. func (f *sendReceiveFolder) dbUpdaterRoutine(dbUpdateChan <-chan dbUpdateJob) {
  1258. const maxBatchTime = 2 * time.Second
  1259. batch := make([]dbUpdateJob, 0, maxBatchSizeFiles)
  1260. files := make([]protocol.FileInfo, 0, maxBatchSizeFiles)
  1261. tick := time.NewTicker(maxBatchTime)
  1262. defer tick.Stop()
  1263. changedDirs := make(map[string]struct{})
  1264. handleBatch := func() {
  1265. found := false
  1266. var lastFile protocol.FileInfo
  1267. for _, job := range batch {
  1268. files = append(files, job.file)
  1269. switch job.jobType {
  1270. case dbUpdateHandleFile, dbUpdateShortcutFile:
  1271. changedDirs[filepath.Dir(job.file.Name)] = struct{}{}
  1272. case dbUpdateHandleDir:
  1273. changedDirs[job.file.Name] = struct{}{}
  1274. case dbUpdateHandleSymlink, dbUpdateInvalidate:
  1275. // fsyncing symlinks is only supported by MacOS
  1276. // and invalidated files are db only changes -> no sync
  1277. }
  1278. if job.file.IsInvalid() || (job.file.IsDirectory() && !job.file.IsSymlink()) {
  1279. continue
  1280. }
  1281. if job.jobType&(dbUpdateHandleFile|dbUpdateDeleteFile) == 0 {
  1282. continue
  1283. }
  1284. found = true
  1285. lastFile = job.file
  1286. }
  1287. // sync directories
  1288. for dir := range changedDirs {
  1289. delete(changedDirs, dir)
  1290. fd, err := f.fs.Open(dir)
  1291. if err != nil {
  1292. l.Debugf("fsync %q failed: %v", dir, err)
  1293. continue
  1294. }
  1295. if err := fd.Sync(); err != nil {
  1296. l.Debugf("fsync %q failed: %v", dir, err)
  1297. }
  1298. fd.Close()
  1299. }
  1300. // All updates to file/folder objects that originated remotely
  1301. // (across the network) use this call to updateLocals
  1302. f.model.updateLocalsFromPulling(f.folderID, files)
  1303. if found {
  1304. f.model.receivedFile(f.folderID, lastFile)
  1305. }
  1306. batch = batch[:0]
  1307. files = files[:0]
  1308. }
  1309. batchSizeBytes := 0
  1310. loop:
  1311. for {
  1312. select {
  1313. case job, ok := <-dbUpdateChan:
  1314. if !ok {
  1315. break loop
  1316. }
  1317. job.file.Sequence = 0
  1318. batch = append(batch, job)
  1319. batchSizeBytes += job.file.ProtoSize()
  1320. if len(batch) == maxBatchSizeFiles || batchSizeBytes > maxBatchSizeBytes {
  1321. handleBatch()
  1322. batchSizeBytes = 0
  1323. }
  1324. case <-tick.C:
  1325. if len(batch) > 0 {
  1326. handleBatch()
  1327. batchSizeBytes = 0
  1328. }
  1329. }
  1330. }
  1331. if len(batch) > 0 {
  1332. handleBatch()
  1333. }
  1334. }
  1335. // pullScannerRoutine aggregates paths to be scanned after pulling. The scan is
  1336. // scheduled once when scanChan is closed (scanning can not happen during pulling).
  1337. func (f *sendReceiveFolder) pullScannerRoutine(scanChan <-chan string) {
  1338. toBeScanned := make(map[string]struct{})
  1339. for path := range scanChan {
  1340. toBeScanned[path] = struct{}{}
  1341. }
  1342. if len(toBeScanned) != 0 {
  1343. scanList := make([]string, 0, len(toBeScanned))
  1344. for path := range toBeScanned {
  1345. l.Debugln(f, "scheduling scan after pulling for", path)
  1346. scanList = append(scanList, path)
  1347. }
  1348. f.Scan(scanList)
  1349. }
  1350. }
  1351. func (f *sendReceiveFolder) inConflict(current, replacement protocol.Vector) bool {
  1352. if current.Concurrent(replacement) {
  1353. // Obvious case
  1354. return true
  1355. }
  1356. if replacement.Counter(f.shortID) > current.Counter(f.shortID) {
  1357. // The replacement file contains a higher version for ourselves than
  1358. // what we have. This isn't supposed to be possible, since it's only
  1359. // we who can increment that counter. We take it as a sign that
  1360. // something is wrong (our index may have been corrupted or removed)
  1361. // and flag it as a conflict.
  1362. return true
  1363. }
  1364. return false
  1365. }
  1366. func removeAvailability(availabilities []Availability, availability Availability) []Availability {
  1367. for i := range availabilities {
  1368. if availabilities[i] == availability {
  1369. availabilities[i] = availabilities[len(availabilities)-1]
  1370. return availabilities[:len(availabilities)-1]
  1371. }
  1372. }
  1373. return availabilities
  1374. }
  1375. func (f *sendReceiveFolder) moveForConflict(name string, lastModBy string) error {
  1376. if strings.Contains(filepath.Base(name), ".sync-conflict-") {
  1377. l.Infoln("Conflict for", name, "which is already a conflict copy; not copying again.")
  1378. if err := f.fs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1379. return err
  1380. }
  1381. return nil
  1382. }
  1383. if f.MaxConflicts == 0 {
  1384. if err := f.fs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1385. return err
  1386. }
  1387. return nil
  1388. }
  1389. ext := filepath.Ext(name)
  1390. withoutExt := name[:len(name)-len(ext)]
  1391. newName := withoutExt + time.Now().Format(".sync-conflict-20060102-150405-") + lastModBy + ext
  1392. err := f.fs.Rename(name, newName)
  1393. if fs.IsNotExist(err) {
  1394. // We were supposed to move a file away but it does not exist. Either
  1395. // the user has already moved it away, or the conflict was between a
  1396. // remote modification and a local delete. In either way it does not
  1397. // matter, go ahead as if the move succeeded.
  1398. err = nil
  1399. }
  1400. if f.MaxConflicts > -1 {
  1401. matches, gerr := f.fs.Glob(withoutExt + ".sync-conflict-????????-??????*" + ext)
  1402. if gerr == nil && len(matches) > f.MaxConflicts {
  1403. sort.Sort(sort.Reverse(sort.StringSlice(matches)))
  1404. for _, match := range matches[f.MaxConflicts:] {
  1405. gerr = f.fs.Remove(match)
  1406. if gerr != nil {
  1407. l.Debugln(f, "removing extra conflict", gerr)
  1408. }
  1409. }
  1410. } else if gerr != nil {
  1411. l.Debugln(f, "globbing for conflicts", gerr)
  1412. }
  1413. }
  1414. return err
  1415. }
  1416. func (f *sendReceiveFolder) newError(context, path string, err error) {
  1417. f.errorsMut.Lock()
  1418. defer f.errorsMut.Unlock()
  1419. // We might get more than one error report for a file (i.e. error on
  1420. // Write() followed by Close()); we keep the first error as that is
  1421. // probably closer to the root cause.
  1422. if _, ok := f.errors[path]; ok {
  1423. return
  1424. }
  1425. l.Infof("Puller (folder %s, file %q): %s: %v", f.Description(), path, context, err)
  1426. f.errors[path] = fmt.Sprintf("%s: %s", context, err.Error())
  1427. }
  1428. func (f *sendReceiveFolder) clearErrors() {
  1429. f.errorsMut.Lock()
  1430. f.errors = make(map[string]string)
  1431. f.errorsMut.Unlock()
  1432. }
  1433. func (f *sendReceiveFolder) PullErrors() []FileError {
  1434. f.errorsMut.Lock()
  1435. errors := make([]FileError, 0, len(f.errors))
  1436. for path, err := range f.errors {
  1437. errors = append(errors, FileError{path, err})
  1438. }
  1439. sort.Sort(fileErrorList(errors))
  1440. f.errorsMut.Unlock()
  1441. return errors
  1442. }
  1443. // deleteDir attempts to delete a directory. It checks for files/dirs inside
  1444. // the directory and removes them if possible or returns an error if it fails
  1445. func (f *sendReceiveFolder) deleteDir(dir string, ignores *ignore.Matcher, scanChan chan<- string) error {
  1446. files, _ := f.fs.DirNames(dir)
  1447. toBeDeleted := make([]string, 0, len(files))
  1448. hasIgnored := false
  1449. hasKnown := false
  1450. hasToBeScanned := false
  1451. for _, dirFile := range files {
  1452. fullDirFile := filepath.Join(dir, dirFile)
  1453. if fs.IsTemporary(dirFile) || ignores.Match(fullDirFile).IsDeletable() {
  1454. toBeDeleted = append(toBeDeleted, fullDirFile)
  1455. } else if ignores != nil && ignores.Match(fullDirFile).IsIgnored() {
  1456. hasIgnored = true
  1457. } else if cf, ok := f.model.CurrentFolderFile(f.ID, fullDirFile); !ok || cf.IsDeleted() || cf.IsInvalid() {
  1458. // Something appeared in the dir that we either are not
  1459. // aware of at all, that we think should be deleted or that
  1460. // is invalid, but not currently ignored -> schedule scan
  1461. scanChan <- fullDirFile
  1462. hasToBeScanned = true
  1463. } else {
  1464. // Dir contains file that is valid according to db and
  1465. // not ignored -> something weird is going on
  1466. hasKnown = true
  1467. }
  1468. }
  1469. if hasToBeScanned {
  1470. return errDirHasToBeScanned
  1471. }
  1472. if hasIgnored {
  1473. return errDirHasIgnored
  1474. }
  1475. if hasKnown {
  1476. return errDirNotEmpty
  1477. }
  1478. for _, del := range toBeDeleted {
  1479. f.fs.RemoveAll(del)
  1480. }
  1481. err := osutil.InWritableDir(f.fs.Remove, f.fs, dir)
  1482. if err == nil || fs.IsNotExist(err) {
  1483. // It was removed or it doesn't exist to start with
  1484. return nil
  1485. }
  1486. if _, serr := f.fs.Lstat(dir); serr != nil && !fs.IsPermission(serr) {
  1487. // We get an error just looking at the directory, and it's not a
  1488. // permission problem. Lets assume the error is in fact some variant
  1489. // of "file does not exist" (possibly expressed as some parent being a
  1490. // file and not a directory etc) and that the delete is handled.
  1491. return nil
  1492. }
  1493. return err
  1494. }
  1495. // A []FileError is sent as part of an event and will be JSON serialized.
  1496. type FileError struct {
  1497. Path string `json:"path"`
  1498. Err string `json:"error"`
  1499. }
  1500. type fileErrorList []FileError
  1501. func (l fileErrorList) Len() int {
  1502. return len(l)
  1503. }
  1504. func (l fileErrorList) Less(a, b int) bool {
  1505. return l[a].Path < l[b].Path
  1506. }
  1507. func (l fileErrorList) Swap(a, b int) {
  1508. l[a], l[b] = l[b], l[a]
  1509. }
  1510. // byComponentCount sorts by the number of path components in Name, that is
  1511. // "x/y" sorts before "foo/bar/baz".
  1512. type byComponentCount []protocol.FileInfo
  1513. func (l byComponentCount) Len() int {
  1514. return len(l)
  1515. }
  1516. func (l byComponentCount) Less(a, b int) bool {
  1517. return componentCount(l[a].Name) < componentCount(l[b].Name)
  1518. }
  1519. func (l byComponentCount) Swap(a, b int) {
  1520. l[a], l[b] = l[b], l[a]
  1521. }
  1522. func componentCount(name string) int {
  1523. count := 0
  1524. for _, codepoint := range name {
  1525. if codepoint == fs.PathSeparator {
  1526. count++
  1527. }
  1528. }
  1529. return count
  1530. }
  1531. type byteSemaphore struct {
  1532. max int
  1533. available int
  1534. mut stdsync.Mutex
  1535. cond *stdsync.Cond
  1536. }
  1537. func newByteSemaphore(max int) *byteSemaphore {
  1538. s := byteSemaphore{
  1539. max: max,
  1540. available: max,
  1541. }
  1542. s.cond = stdsync.NewCond(&s.mut)
  1543. return &s
  1544. }
  1545. func (s *byteSemaphore) take(bytes int) {
  1546. if bytes > s.max {
  1547. panic("bug: more than max bytes will never be available")
  1548. }
  1549. s.mut.Lock()
  1550. for bytes > s.available {
  1551. s.cond.Wait()
  1552. }
  1553. s.available -= bytes
  1554. s.mut.Unlock()
  1555. }
  1556. func (s *byteSemaphore) give(bytes int) {
  1557. s.mut.Lock()
  1558. if s.available+bytes > s.max {
  1559. panic("bug: can never give more than max")
  1560. }
  1561. s.available += bytes
  1562. s.cond.Broadcast()
  1563. s.mut.Unlock()
  1564. }