rwfolder.go 52 KB

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