folder_sendrecv.go 68 KB

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