rwfolder.go 51 KB

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