folder_sendrecv.go 68 KB

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