folder_sendrecv.go 63 KB

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