rwfolder.go 52 KB

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