folder_sendrecv.go 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232
  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 || f.IgnorePerms || file.NoPermissions {
  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. // Stat the directory so we can check its permissions.
  540. info, err := f.mtimefs.Lstat(path)
  541. if err != nil {
  542. return err
  543. }
  544. // Mask for the bits we want to preserve and add them in to the
  545. // directories permissions.
  546. return f.mtimefs.Chmod(path, mode|(info.Mode()&retainBits))
  547. }
  548. if err = f.inWritableDir(mkdir, file.Name); err == nil {
  549. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  550. } else {
  551. f.newPullError(file.Name, fmt.Errorf("creating directory: %w", err))
  552. }
  553. return
  554. // Weird error when stat()'ing the dir. Probably won't work to do
  555. // anything else with it if we can't even stat() it.
  556. case err != nil:
  557. f.newPullError(file.Name, fmt.Errorf("checking file to be replaced: %w", err))
  558. return
  559. }
  560. // The directory already exists, so we just correct the metadata. (We
  561. // don't handle modification times on directories, because that sucks...)
  562. // It's OK to change mode bits on stuff within non-writable directories.
  563. if !f.IgnorePerms && !file.NoPermissions {
  564. if err := f.mtimefs.Chmod(file.Name, mode|(info.Mode()&retainBits)); err != nil {
  565. f.newPullError(file.Name, fmt.Errorf("handling dir (setting permissions): %w", err))
  566. return
  567. }
  568. if err := f.setPlatformData(&file, file.Name); err != nil {
  569. f.newPullError(file.Name, fmt.Errorf("handling dir (setting metadata): %w", err))
  570. return
  571. }
  572. }
  573. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleDir}
  574. }
  575. // checkParent verifies that the thing we are handling lives inside a directory,
  576. // and not a symlink or regular file. It also resurrects missing parent dirs.
  577. func (f *sendReceiveFolder) checkParent(file string, scanChan chan<- string) bool {
  578. parent := filepath.Dir(file)
  579. if err := osutil.TraversesSymlink(f.mtimefs, parent); err != nil {
  580. f.newPullError(file, fmt.Errorf("checking parent dirs: %w", err))
  581. return false
  582. }
  583. // issues #114 and #4475: This works around a race condition
  584. // between two devices, when one device removes a directory and the
  585. // other creates a file in it. However that happens, we end up with
  586. // a directory for "foo" with the delete bit, but a file "foo/bar"
  587. // that we want to sync. We never create the directory, and hence
  588. // fail to create the file and end up looping forever on it. This
  589. // breaks that by creating the directory and scheduling a scan,
  590. // where it will be found and the delete bit on it removed. The
  591. // user can then clean up as they like...
  592. // This can also occur if an entire tree structure was deleted, but only
  593. // a leave has been scanned.
  594. //
  595. // And if this is an encrypted folder:
  596. // Encrypted files have made-up filenames with two synthetic parent
  597. // directories which don't have any meaning. Create those if necessary.
  598. if _, err := f.mtimefs.Lstat(parent); !fs.IsNotExist(err) {
  599. l.Debugf("%v parent not missing %v", f, file)
  600. return true
  601. }
  602. l.Debugf("%v creating parent directory of %v", f, file)
  603. if err := f.mtimefs.MkdirAll(parent, 0755); err != nil {
  604. f.newPullError(file, fmt.Errorf("creating parent dir: %w", err))
  605. return false
  606. }
  607. if f.Type != config.FolderTypeReceiveEncrypted {
  608. scanChan <- parent
  609. }
  610. return true
  611. }
  612. // handleSymlink creates or updates the given symlink
  613. func (f *sendReceiveFolder) handleSymlink(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  614. // Used in the defer closure below, updated by the function body. Take
  615. // care not declare another err.
  616. var err error
  617. f.evLogger.Log(events.ItemStarted, map[string]string{
  618. "folder": f.folderID,
  619. "item": file.Name,
  620. "type": "symlink",
  621. "action": "update",
  622. })
  623. defer func() {
  624. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  625. "folder": f.folderID,
  626. "item": file.Name,
  627. "error": events.Error(err),
  628. "type": "symlink",
  629. "action": "update",
  630. })
  631. }()
  632. if shouldDebug() {
  633. curFile, _ := snap.Get(protocol.LocalDeviceID, file.Name)
  634. l.Debugf("need symlink\n\t%v\n\t%v", file, curFile)
  635. }
  636. if file.SymlinkTarget == "" {
  637. // Index entry from a Syncthing predating the support for including
  638. // the link target in the index entry. We log this as an error.
  639. f.newPullError(file.Name, errIncompatibleSymlink)
  640. return
  641. }
  642. if err = f.handleSymlinkCheckExisting(file, snap, scanChan); err != nil {
  643. f.newPullError(file.Name, fmt.Errorf("handling symlink: %w", err))
  644. return
  645. }
  646. // We declare a function that acts on only the path name, so
  647. // we can pass it to InWritableDir.
  648. createLink := func(path string) error {
  649. if err := f.mtimefs.CreateSymlink(file.SymlinkTarget, path); err != nil {
  650. return err
  651. }
  652. return f.setPlatformData(&file, path)
  653. }
  654. if err = f.inWritableDir(createLink, file.Name); err == nil {
  655. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleSymlink}
  656. } else {
  657. f.newPullError(file.Name, fmt.Errorf("symlink create: %w", err))
  658. }
  659. }
  660. func (f *sendReceiveFolder) handleSymlinkCheckExisting(file protocol.FileInfo, snap *db.Snapshot, scanChan chan<- string) error {
  661. // If there is already something under that name, we need to handle that.
  662. info, err := f.mtimefs.Lstat(file.Name)
  663. if err != nil {
  664. if fs.IsNotExist(err) {
  665. return nil
  666. }
  667. return err
  668. }
  669. // Check that it is what we have in the database.
  670. curFile, hasCurFile := snap.Get(protocol.LocalDeviceID, file.Name)
  671. if err := f.scanIfItemChanged(file.Name, info, curFile, hasCurFile, scanChan); err != nil {
  672. return err
  673. }
  674. // Remove it to replace with the symlink. This also handles the
  675. // "change symlink type" path.
  676. if !curFile.IsDirectory() && !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  677. // The new file has been changed in conflict with the existing one. We
  678. // should file it away as a conflict instead of just removing or
  679. // archiving.
  680. // Directories and symlinks aren't checked for conflicts.
  681. return f.inWritableDir(func(name string) error {
  682. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  683. }, curFile.Name)
  684. } else {
  685. return f.deleteItemOnDisk(curFile, snap, scanChan)
  686. }
  687. }
  688. // deleteDir attempts to remove a directory that was deleted on a remote
  689. func (f *sendReceiveFolder) deleteDir(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  690. // Used in the defer closure below, updated by the function body. Take
  691. // care not declare another err.
  692. var err error
  693. f.evLogger.Log(events.ItemStarted, map[string]string{
  694. "folder": f.folderID,
  695. "item": file.Name,
  696. "type": "dir",
  697. "action": "delete",
  698. })
  699. defer func() {
  700. if err != nil {
  701. f.newPullError(file.Name, fmt.Errorf("delete dir: %w", err))
  702. }
  703. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  704. "folder": f.folderID,
  705. "item": file.Name,
  706. "error": events.Error(err),
  707. "type": "dir",
  708. "action": "delete",
  709. })
  710. }()
  711. cur, hasCur := snap.Get(protocol.LocalDeviceID, file.Name)
  712. if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
  713. if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
  714. err = nil
  715. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  716. }
  717. return
  718. }
  719. if err = f.deleteDirOnDisk(file.Name, snap, scanChan); err != nil {
  720. return
  721. }
  722. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
  723. }
  724. // deleteFile attempts to delete the given file
  725. func (f *sendReceiveFolder) deleteFile(file protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  726. cur, hasCur := snap.Get(protocol.LocalDeviceID, file.Name)
  727. f.deleteFileWithCurrent(file, cur, hasCur, dbUpdateChan, scanChan)
  728. }
  729. func (f *sendReceiveFolder) deleteFileWithCurrent(file, cur protocol.FileInfo, hasCur bool, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  730. // Used in the defer closure below, updated by the function body. Take
  731. // care not declare another err.
  732. var err error
  733. l.Debugln(f, "Deleting file", file.Name)
  734. f.evLogger.Log(events.ItemStarted, map[string]string{
  735. "folder": f.folderID,
  736. "item": file.Name,
  737. "type": "file",
  738. "action": "delete",
  739. })
  740. defer func() {
  741. if err != nil {
  742. f.newPullError(file.Name, fmt.Errorf("delete file: %w", err))
  743. }
  744. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  745. "folder": f.folderID,
  746. "item": file.Name,
  747. "error": events.Error(err),
  748. "type": "file",
  749. "action": "delete",
  750. })
  751. }()
  752. if err = f.checkToBeDeleted(file, cur, hasCur, scanChan); err != nil {
  753. if fs.IsNotExist(err) || fs.IsErrCaseConflict(err) {
  754. err = nil
  755. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  756. }
  757. return
  758. }
  759. // We are asked to delete a file, but what we have on disk and in db
  760. // is a directory. Something is wrong here, should probably not happen.
  761. if cur.IsDirectory() {
  762. err = errUnexpectedDirOnFileDel
  763. return
  764. }
  765. if f.inConflict(cur.Version, file.Version) {
  766. // There is a conflict here, which shouldn't happen as deletions
  767. // always lose. Merge the version vector of the file we have
  768. // locally and commit it to db to resolve the conflict.
  769. cur.Version = cur.Version.Merge(file.Version)
  770. dbUpdateChan <- dbUpdateJob{cur, dbUpdateHandleFile}
  771. return
  772. }
  773. if f.versioner != nil && !cur.IsSymlink() {
  774. err = f.inWritableDir(f.versioner.Archive, file.Name)
  775. } else {
  776. err = f.inWritableDir(f.mtimefs.Remove, file.Name)
  777. }
  778. if err == nil || fs.IsNotExist(err) {
  779. // It was removed or it doesn't exist to start with
  780. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  781. return
  782. }
  783. if _, serr := f.mtimefs.Lstat(file.Name); serr != nil && !fs.IsPermission(serr) {
  784. // We get an error just looking at the file, and it's not a permission
  785. // problem. Lets assume the error is in fact some variant of "file
  786. // does not exist" (possibly expressed as some parent being a file and
  787. // not a directory etc) and that the delete is handled.
  788. err = nil
  789. dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteFile}
  790. }
  791. }
  792. // renameFile attempts to rename an existing file to a destination
  793. // and set the right attributes on it.
  794. func (f *sendReceiveFolder) renameFile(cur, source, target protocol.FileInfo, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  795. // Used in the defer closure below, updated by the function body. Take
  796. // care not declare another err.
  797. var err error
  798. f.evLogger.Log(events.ItemStarted, map[string]string{
  799. "folder": f.folderID,
  800. "item": source.Name,
  801. "type": "file",
  802. "action": "delete",
  803. })
  804. f.evLogger.Log(events.ItemStarted, map[string]string{
  805. "folder": f.folderID,
  806. "item": target.Name,
  807. "type": "file",
  808. "action": "update",
  809. })
  810. defer func() {
  811. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  812. "folder": f.folderID,
  813. "item": source.Name,
  814. "error": events.Error(err),
  815. "type": "file",
  816. "action": "delete",
  817. })
  818. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  819. "folder": f.folderID,
  820. "item": target.Name,
  821. "error": events.Error(err),
  822. "type": "file",
  823. "action": "update",
  824. })
  825. }()
  826. l.Debugln(f, "taking rename shortcut", source.Name, "->", target.Name)
  827. // Check that source is compatible with what we have in the DB
  828. if err = f.checkToBeDeleted(source, cur, true, scanChan); err != nil {
  829. return err
  830. }
  831. // Check that the target corresponds to what we have in the DB
  832. curTarget, ok := snap.Get(protocol.LocalDeviceID, target.Name)
  833. switch stat, serr := f.mtimefs.Lstat(target.Name); {
  834. case serr != nil:
  835. var caseErr *fs.ErrCaseConflict
  836. switch {
  837. case errors.As(serr, &caseErr):
  838. if caseErr.Real != source.Name {
  839. err = serr
  840. break
  841. }
  842. fallthrough // This is a case only rename
  843. case fs.IsNotExist(serr):
  844. if !ok || curTarget.IsDeleted() {
  845. break
  846. }
  847. scanChan <- target.Name
  848. err = errModified
  849. default:
  850. // We can't check whether the file changed as compared to the db,
  851. // do not delete.
  852. err = serr
  853. }
  854. case !ok:
  855. // Target appeared from nowhere
  856. scanChan <- target.Name
  857. err = errModified
  858. default:
  859. var fi protocol.FileInfo
  860. if fi, err = scanner.CreateFileInfo(stat, target.Name, f.mtimefs, f.SyncOwnership, f.SyncXattrs, f.XattrFilter); err == nil {
  861. if !fi.IsEquivalentOptional(curTarget, protocol.FileInfoComparison{
  862. ModTimeWindow: f.modTimeWindow,
  863. IgnorePerms: f.IgnorePerms,
  864. IgnoreBlocks: true,
  865. IgnoreFlags: protocol.LocalAllFlags,
  866. IgnoreOwnership: !f.SyncOwnership,
  867. IgnoreXattrs: !f.SyncXattrs,
  868. }) {
  869. // Target changed
  870. scanChan <- target.Name
  871. err = errModified
  872. }
  873. }
  874. }
  875. if err != nil {
  876. return err
  877. }
  878. tempName := fs.TempName(target.Name)
  879. if f.versioner != nil {
  880. err = f.CheckAvailableSpace(uint64(source.Size))
  881. if err == nil {
  882. err = osutil.Copy(f.CopyRangeMethod, f.mtimefs, f.mtimefs, source.Name, tempName)
  883. if err == nil {
  884. err = f.inWritableDir(f.versioner.Archive, source.Name)
  885. }
  886. }
  887. } else {
  888. err = osutil.RenameOrCopy(f.CopyRangeMethod, f.mtimefs, f.mtimefs, source.Name, tempName)
  889. }
  890. if err != nil {
  891. return err
  892. }
  893. blockStatsMut.Lock()
  894. minBlocksPerBlock := target.BlockSize() / protocol.MinBlockSize
  895. blockStats["total"] += len(target.Blocks) * minBlocksPerBlock
  896. blockStats["renamed"] += len(target.Blocks) * minBlocksPerBlock
  897. blockStatsMut.Unlock()
  898. // The file was renamed, so we have handled both the necessary delete
  899. // of the source and the creation of the target temp file. Fix-up the metadata,
  900. // update the local index of the target file and rename from temp to real name.
  901. if err = f.performFinish(target, curTarget, true, tempName, snap, dbUpdateChan, scanChan); err != nil {
  902. return err
  903. }
  904. dbUpdateChan <- dbUpdateJob{source, dbUpdateDeleteFile}
  905. return nil
  906. }
  907. // This is the flow of data and events here, I think...
  908. //
  909. // +-----------------------+
  910. // | | - - - - > ItemStarted
  911. // | handleFile | - - - - > ItemFinished (on shortcuts)
  912. // | |
  913. // +-----------------------+
  914. // |
  915. // | copyChan (copyBlocksState; unless shortcut taken)
  916. // |
  917. // | +-----------------------+
  918. // | | +-----------------------+
  919. // +--->| | |
  920. // | | copierRoutine |
  921. // +-| |
  922. // +-----------------------+
  923. // |
  924. // | pullChan (sharedPullerState)
  925. // |
  926. // | +-----------------------+
  927. // | | +-----------------------+
  928. // +-->| | |
  929. // | | pullerRoutine |
  930. // +-| |
  931. // +-----------------------+
  932. // |
  933. // | finisherChan (sharedPullerState)
  934. // |
  935. // | +-----------------------+
  936. // | | |
  937. // +-->| finisherRoutine | - - - - > ItemFinished
  938. // | |
  939. // +-----------------------+
  940. // handleFile queues the copies and pulls as necessary for a single new or
  941. // changed file.
  942. func (f *sendReceiveFolder) handleFile(file protocol.FileInfo, snap *db.Snapshot, copyChan chan<- copyBlocksState) {
  943. curFile, hasCurFile := snap.Get(protocol.LocalDeviceID, file.Name)
  944. have, _ := blockDiff(curFile.Blocks, file.Blocks)
  945. tempName := fs.TempName(file.Name)
  946. populateOffsets(file.Blocks)
  947. blocks := append([]protocol.BlockInfo{}, file.Blocks...)
  948. reused := make([]int, 0, len(file.Blocks))
  949. if f.Type != config.FolderTypeReceiveEncrypted {
  950. blocks, reused = f.reuseBlocks(blocks, reused, file, tempName)
  951. }
  952. // The sharedpullerstate will know which flags to use when opening the
  953. // temp file depending if we are reusing any blocks or not.
  954. if len(reused) == 0 {
  955. // Otherwise, discard the file ourselves in order for the
  956. // sharedpuller not to panic when it fails to exclusively create a
  957. // file which already exists
  958. f.inWritableDir(f.mtimefs.Remove, tempName)
  959. }
  960. // Reorder blocks
  961. blocks = f.blockPullReorderer.Reorder(blocks)
  962. f.evLogger.Log(events.ItemStarted, map[string]string{
  963. "folder": f.folderID,
  964. "item": file.Name,
  965. "type": "file",
  966. "action": "update",
  967. })
  968. s := newSharedPullerState(file, f.mtimefs, f.folderID, tempName, blocks, reused, f.IgnorePerms || file.NoPermissions, hasCurFile, curFile, !f.DisableSparseFiles, !f.DisableFsync)
  969. l.Debugf("%v need file %s; copy %d, reused %v", f, file.Name, len(blocks), len(reused))
  970. cs := copyBlocksState{
  971. sharedPullerState: s,
  972. blocks: blocks,
  973. have: len(have),
  974. }
  975. copyChan <- cs
  976. }
  977. func (f *sendReceiveFolder) reuseBlocks(blocks []protocol.BlockInfo, reused []int, file protocol.FileInfo, tempName string) ([]protocol.BlockInfo, []int) {
  978. // Check for an old temporary file which might have some blocks we could
  979. // reuse.
  980. tempBlocks, err := scanner.HashFile(f.ctx, f.mtimefs, tempName, file.BlockSize(), nil, false)
  981. if err != nil {
  982. var caseErr *fs.ErrCaseConflict
  983. if errors.As(err, &caseErr) {
  984. if rerr := f.mtimefs.Rename(caseErr.Real, tempName); rerr == nil {
  985. tempBlocks, err = scanner.HashFile(f.ctx, f.mtimefs, tempName, file.BlockSize(), nil, false)
  986. }
  987. }
  988. }
  989. if err != nil {
  990. return blocks, reused
  991. }
  992. // Check for any reusable blocks in the temp file
  993. tempCopyBlocks, _ := blockDiff(tempBlocks, file.Blocks)
  994. // block.String() returns a string unique to the block
  995. existingBlocks := make(map[string]struct{}, len(tempCopyBlocks))
  996. for _, block := range tempCopyBlocks {
  997. existingBlocks[block.String()] = struct{}{}
  998. }
  999. // Since the blocks are already there, we don't need to get them.
  1000. blocks = blocks[:0]
  1001. for i, block := range file.Blocks {
  1002. _, ok := existingBlocks[block.String()]
  1003. if !ok {
  1004. blocks = append(blocks, block)
  1005. } else {
  1006. reused = append(reused, i)
  1007. }
  1008. }
  1009. return blocks, reused
  1010. }
  1011. // blockDiff returns lists of common and missing (to transform src into tgt)
  1012. // blocks. Both block lists must have been created with the same block size.
  1013. func blockDiff(src, tgt []protocol.BlockInfo) ([]protocol.BlockInfo, []protocol.BlockInfo) {
  1014. if len(tgt) == 0 {
  1015. return nil, nil
  1016. }
  1017. if len(src) == 0 {
  1018. // Copy the entire file
  1019. return nil, tgt
  1020. }
  1021. have := make([]protocol.BlockInfo, 0, len(src))
  1022. need := make([]protocol.BlockInfo, 0, len(tgt))
  1023. for i := range tgt {
  1024. if i >= len(src) {
  1025. return have, append(need, tgt[i:]...)
  1026. }
  1027. if !bytes.Equal(tgt[i].Hash, src[i].Hash) {
  1028. // Copy differing block
  1029. need = append(need, tgt[i])
  1030. } else {
  1031. have = append(have, tgt[i])
  1032. }
  1033. }
  1034. return have, need
  1035. }
  1036. // populateOffsets sets the Offset field on each block
  1037. func populateOffsets(blocks []protocol.BlockInfo) {
  1038. var offset int64
  1039. for i := range blocks {
  1040. blocks[i].Offset = offset
  1041. offset += int64(blocks[i].Size)
  1042. }
  1043. }
  1044. // shortcutFile sets file metadata, when that's the only thing that has
  1045. // changed.
  1046. func (f *sendReceiveFolder) shortcutFile(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob) {
  1047. l.Debugln(f, "taking shortcut on", file.Name)
  1048. f.evLogger.Log(events.ItemStarted, map[string]string{
  1049. "folder": f.folderID,
  1050. "item": file.Name,
  1051. "type": "file",
  1052. "action": "metadata",
  1053. })
  1054. var err error
  1055. defer f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  1056. "folder": f.folderID,
  1057. "item": file.Name,
  1058. "error": events.Error(err),
  1059. "type": "file",
  1060. "action": "metadata",
  1061. })
  1062. f.queue.Done(file.Name)
  1063. if !f.IgnorePerms && !file.NoPermissions {
  1064. if err = f.mtimefs.Chmod(file.Name, fs.FileMode(file.Permissions&0777)); err != nil {
  1065. f.newPullError(file.Name, fmt.Errorf("shortcut file (setting permissions): %w", err))
  1066. return
  1067. }
  1068. }
  1069. if err := f.setPlatformData(&file, file.Name); err != nil {
  1070. f.newPullError(file.Name, fmt.Errorf("shortcut file (setting metadata): %w", err))
  1071. return
  1072. }
  1073. // Still need to re-write the trailer with the new encrypted fileinfo.
  1074. if f.Type == config.FolderTypeReceiveEncrypted {
  1075. err = inWritableDir(func(path string) error {
  1076. fd, err := f.mtimefs.OpenFile(path, fs.OptReadWrite, 0666)
  1077. if err != nil {
  1078. return err
  1079. }
  1080. defer fd.Close()
  1081. trailerSize, err := writeEncryptionTrailer(file, fd)
  1082. if err != nil {
  1083. return err
  1084. }
  1085. return fd.Truncate(file.Size + trailerSize)
  1086. }, f.mtimefs, file.Name, true)
  1087. if err != nil {
  1088. f.newPullError(file.Name, fmt.Errorf("writing encrypted file trailer: %w", err))
  1089. return
  1090. }
  1091. }
  1092. f.mtimefs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  1093. dbUpdateChan <- dbUpdateJob{file, dbUpdateShortcutFile}
  1094. }
  1095. // copierRoutine reads copierStates until the in channel closes and performs
  1096. // the relevant copies when possible, or passes it to the puller routine.
  1097. func (f *sendReceiveFolder) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
  1098. buf := protocol.BufferPool.Get(protocol.MinBlockSize)
  1099. defer func() {
  1100. protocol.BufferPool.Put(buf)
  1101. }()
  1102. folderFilesystems := make(map[string]fs.Filesystem)
  1103. // Hope that it's usually in the same folder, so start with that one.
  1104. folders := []string{f.folderID}
  1105. for folder, cfg := range f.model.cfg.Folders() {
  1106. folderFilesystems[folder] = cfg.Filesystem(nil)
  1107. if folder != f.folderID {
  1108. folders = append(folders, folder)
  1109. }
  1110. }
  1111. for state := range in {
  1112. if err := f.CheckAvailableSpace(uint64(state.file.Size)); err != nil {
  1113. state.fail(err)
  1114. // Nothing more to do for this failed file, since it would use to much disk space
  1115. out <- state.sharedPullerState
  1116. continue
  1117. }
  1118. dstFd, err := state.tempFile()
  1119. if err != nil {
  1120. // Nothing more to do for this failed file, since we couldn't create a temporary for it.
  1121. out <- state.sharedPullerState
  1122. continue
  1123. }
  1124. if f.Type != config.FolderTypeReceiveEncrypted {
  1125. f.model.progressEmitter.Register(state.sharedPullerState)
  1126. }
  1127. weakHashFinder, file := f.initWeakHashFinder(state)
  1128. blocks:
  1129. for _, block := range state.blocks {
  1130. select {
  1131. case <-f.ctx.Done():
  1132. state.fail(fmt.Errorf("folder stopped: %w", f.ctx.Err()))
  1133. break blocks
  1134. default:
  1135. }
  1136. if !f.DisableSparseFiles && state.reused == 0 && block.IsEmpty() {
  1137. // The block is a block of all zeroes, and we are not reusing
  1138. // a temp file, so there is no need to do anything with it.
  1139. // If we were reusing a temp file and had this block to copy,
  1140. // it would be because the block in the temp file was *not* a
  1141. // block of all zeroes, so then we should not skip it.
  1142. // Pretend we copied it.
  1143. state.copiedFromOrigin()
  1144. state.copyDone(block)
  1145. continue
  1146. }
  1147. buf = protocol.BufferPool.Upgrade(buf, int(block.Size))
  1148. var found bool
  1149. if f.Type != config.FolderTypeReceiveEncrypted {
  1150. found, err = weakHashFinder.Iterate(block.WeakHash, buf, func(offset int64) bool {
  1151. if f.verifyBuffer(buf, block) != nil {
  1152. return true
  1153. }
  1154. err = f.limitedWriteAt(dstFd, buf, block.Offset)
  1155. if err != nil {
  1156. state.fail(fmt.Errorf("dst write: %w", err))
  1157. }
  1158. if offset == block.Offset {
  1159. state.copiedFromOrigin()
  1160. } else {
  1161. state.copiedFromOriginShifted()
  1162. }
  1163. return false
  1164. })
  1165. if err != nil {
  1166. l.Debugln("weak hasher iter", err)
  1167. }
  1168. }
  1169. if !found {
  1170. found = f.model.finder.Iterate(folders, block.Hash, func(folder, path string, index int32) bool {
  1171. ffs := folderFilesystems[folder]
  1172. fd, err := ffs.Open(path)
  1173. if err != nil {
  1174. return false
  1175. }
  1176. defer fd.Close()
  1177. srcOffset := int64(state.file.BlockSize()) * int64(index)
  1178. _, err = fd.ReadAt(buf, srcOffset)
  1179. if err != nil {
  1180. return false
  1181. }
  1182. // Hash is not SHA256 as it's an encrypted hash token. In that
  1183. // case we can't verify the block integrity so we'll take it on
  1184. // trust. (The other side can and will verify.)
  1185. if f.Type != config.FolderTypeReceiveEncrypted {
  1186. if err := f.verifyBuffer(buf, block); err != nil {
  1187. l.Debugln("Finder failed to verify buffer", err)
  1188. return false
  1189. }
  1190. }
  1191. if f.CopyRangeMethod != fs.CopyRangeMethodStandard {
  1192. err = f.withLimiter(func() error {
  1193. dstFd.mut.Lock()
  1194. defer dstFd.mut.Unlock()
  1195. return fs.CopyRange(f.CopyRangeMethod, fd, dstFd.fd, srcOffset, block.Offset, int64(block.Size))
  1196. })
  1197. } else {
  1198. err = f.limitedWriteAt(dstFd, buf, block.Offset)
  1199. }
  1200. if err != nil {
  1201. state.fail(fmt.Errorf("dst write: %w", err))
  1202. }
  1203. if path == state.file.Name {
  1204. state.copiedFromOrigin()
  1205. }
  1206. return true
  1207. })
  1208. }
  1209. if state.failed() != nil {
  1210. break
  1211. }
  1212. if !found {
  1213. state.pullStarted()
  1214. ps := pullBlockState{
  1215. sharedPullerState: state.sharedPullerState,
  1216. block: block,
  1217. }
  1218. pullChan <- ps
  1219. } else {
  1220. state.copyDone(block)
  1221. }
  1222. }
  1223. if file != nil {
  1224. // os.File used to return invalid argument if nil.
  1225. // fs.File panics as it's an interface.
  1226. file.Close()
  1227. }
  1228. out <- state.sharedPullerState
  1229. }
  1230. }
  1231. func (f *sendReceiveFolder) initWeakHashFinder(state copyBlocksState) (*weakhash.Finder, fs.File) {
  1232. if f.Type == config.FolderTypeReceiveEncrypted {
  1233. l.Debugln("not weak hashing due to folder type", f.Type)
  1234. return nil, nil
  1235. }
  1236. blocksPercentChanged := 0
  1237. if tot := len(state.file.Blocks); tot > 0 {
  1238. blocksPercentChanged = (tot - state.have) * 100 / tot
  1239. }
  1240. if blocksPercentChanged < f.WeakHashThresholdPct {
  1241. l.Debugf("not weak hashing %s. not enough changed %.02f < %d", state.file.Name, blocksPercentChanged, f.WeakHashThresholdPct)
  1242. return nil, nil
  1243. }
  1244. hashesToFind := make([]uint32, 0, len(state.blocks))
  1245. for _, block := range state.blocks {
  1246. if block.WeakHash != 0 {
  1247. hashesToFind = append(hashesToFind, block.WeakHash)
  1248. }
  1249. }
  1250. if len(hashesToFind) == 0 {
  1251. l.Debugf("not weak hashing %s. file did not contain any weak hashes", state.file.Name)
  1252. return nil, nil
  1253. }
  1254. file, err := f.mtimefs.Open(state.file.Name)
  1255. if err != nil {
  1256. l.Debugln("weak hasher", err)
  1257. return nil, nil
  1258. }
  1259. weakHashFinder, err := weakhash.NewFinder(f.ctx, file, state.file.BlockSize(), hashesToFind)
  1260. if err != nil {
  1261. l.Debugln("weak hasher", err)
  1262. return nil, file
  1263. }
  1264. return weakHashFinder, file
  1265. }
  1266. func (*sendReceiveFolder) verifyBuffer(buf []byte, block protocol.BlockInfo) error {
  1267. if len(buf) != int(block.Size) {
  1268. return fmt.Errorf("length mismatch %d != %d", len(buf), block.Size)
  1269. }
  1270. hash := sha256.Sum256(buf)
  1271. if !bytes.Equal(hash[:], block.Hash) {
  1272. return fmt.Errorf("hash mismatch %x != %x", hash, block.Hash)
  1273. }
  1274. return nil
  1275. }
  1276. func (f *sendReceiveFolder) pullerRoutine(snap *db.Snapshot, in <-chan pullBlockState, out chan<- *sharedPullerState) {
  1277. requestLimiter := util.NewSemaphore(f.PullerMaxPendingKiB * 1024)
  1278. wg := sync.NewWaitGroup()
  1279. for state := range in {
  1280. if state.failed() != nil {
  1281. out <- state.sharedPullerState
  1282. continue
  1283. }
  1284. f.setState(FolderSyncing) // Does nothing if already FolderSyncing
  1285. // The requestLimiter limits how many pending block requests we have
  1286. // ongoing at any given time, based on the size of the blocks
  1287. // themselves.
  1288. state := state
  1289. bytes := int(state.block.Size)
  1290. if err := requestLimiter.TakeWithContext(f.ctx, bytes); err != nil {
  1291. state.fail(err)
  1292. out <- state.sharedPullerState
  1293. continue
  1294. }
  1295. wg.Add(1)
  1296. go func() {
  1297. defer wg.Done()
  1298. defer requestLimiter.Give(bytes)
  1299. f.pullBlock(state, snap, out)
  1300. }()
  1301. }
  1302. wg.Wait()
  1303. }
  1304. func (f *sendReceiveFolder) pullBlock(state pullBlockState, snap *db.Snapshot, out chan<- *sharedPullerState) {
  1305. // Get an fd to the temporary file. Technically we don't need it until
  1306. // after fetching the block, but if we run into an error here there is
  1307. // no point in issuing the request to the network.
  1308. fd, err := state.tempFile()
  1309. if err != nil {
  1310. out <- state.sharedPullerState
  1311. return
  1312. }
  1313. if !f.DisableSparseFiles && state.reused == 0 && state.block.IsEmpty() {
  1314. // There is no need to request a block of all zeroes. Pretend we
  1315. // requested it and handled it correctly.
  1316. state.pullDone(state.block)
  1317. out <- state.sharedPullerState
  1318. return
  1319. }
  1320. var lastError error
  1321. candidates := f.model.availabilityInSnapshot(f.FolderConfiguration, snap, state.file, state.block)
  1322. loop:
  1323. for {
  1324. select {
  1325. case <-f.ctx.Done():
  1326. state.fail(fmt.Errorf("folder stopped: %w", f.ctx.Err()))
  1327. break loop
  1328. default:
  1329. }
  1330. // Select the least busy device to pull the block from. If we found no
  1331. // feasible device at all, fail the block (and in the long run, the
  1332. // file).
  1333. found := activity.leastBusy(candidates)
  1334. if found == -1 {
  1335. if lastError != nil {
  1336. state.fail(fmt.Errorf("pull: %w", lastError))
  1337. } else {
  1338. state.fail(fmt.Errorf("pull: %w", errNoDevice))
  1339. }
  1340. break
  1341. }
  1342. selected := candidates[found]
  1343. candidates[found] = candidates[len(candidates)-1]
  1344. candidates = candidates[:len(candidates)-1]
  1345. // Fetch the block, while marking the selected device as in use so that
  1346. // leastBusy can select another device when someone else asks.
  1347. activity.using(selected)
  1348. var buf []byte
  1349. blockNo := int(state.block.Offset / int64(state.file.BlockSize()))
  1350. 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)
  1351. activity.done(selected)
  1352. if lastError != nil {
  1353. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, selected.ID.Short(), "returned error:", lastError)
  1354. continue
  1355. }
  1356. // Verify that the received block matches the desired hash, if not
  1357. // try pulling it from another device.
  1358. // For receive-only folders, the hash is not SHA256 as it's an
  1359. // encrypted hash token. In that case we can't verify the block
  1360. // integrity so we'll take it on trust. (The other side can and
  1361. // will verify.)
  1362. if f.Type != config.FolderTypeReceiveEncrypted {
  1363. lastError = f.verifyBuffer(buf, state.block)
  1364. }
  1365. if lastError != nil {
  1366. l.Debugln("request:", f.folderID, state.file.Name, state.block.Offset, state.block.Size, "hash mismatch")
  1367. continue
  1368. }
  1369. // Save the block data we got from the cluster
  1370. err = f.limitedWriteAt(fd, buf, state.block.Offset)
  1371. if err != nil {
  1372. state.fail(fmt.Errorf("save: %w", err))
  1373. } else {
  1374. state.pullDone(state.block)
  1375. }
  1376. break
  1377. }
  1378. out <- state.sharedPullerState
  1379. }
  1380. func (f *sendReceiveFolder) performFinish(file, curFile protocol.FileInfo, hasCurFile bool, tempName string, snap *db.Snapshot, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) error {
  1381. // Set the correct permission bits on the new file
  1382. if !f.IgnorePerms && !file.NoPermissions {
  1383. if err := f.mtimefs.Chmod(tempName, fs.FileMode(file.Permissions&0777)); err != nil {
  1384. return fmt.Errorf("setting permissions: %w", err)
  1385. }
  1386. }
  1387. // Set file xattrs and ownership.
  1388. if err := f.setPlatformData(&file, tempName); err != nil {
  1389. return fmt.Errorf("setting metadata: %w", err)
  1390. }
  1391. if stat, err := f.mtimefs.Lstat(file.Name); err == nil {
  1392. // There is an old file or directory already in place. We need to
  1393. // handle that.
  1394. if err := f.scanIfItemChanged(file.Name, stat, curFile, hasCurFile, scanChan); err != nil {
  1395. return fmt.Errorf("checking existing file: %w", err)
  1396. }
  1397. if !curFile.IsDirectory() && !curFile.IsSymlink() && f.inConflict(curFile.Version, file.Version) {
  1398. // The new file has been changed in conflict with the existing one. We
  1399. // should file it away as a conflict instead of just removing or
  1400. // archiving.
  1401. // Directories and symlinks aren't checked for conflicts.
  1402. err = f.inWritableDir(func(name string) error {
  1403. return f.moveForConflict(name, file.ModifiedBy.String(), scanChan)
  1404. }, curFile.Name)
  1405. } else {
  1406. err = f.deleteItemOnDisk(curFile, snap, scanChan)
  1407. }
  1408. if err != nil {
  1409. return fmt.Errorf("moving for conflict: %w", err)
  1410. }
  1411. } else if !fs.IsNotExist(err) {
  1412. return fmt.Errorf("checking existing file: %w", err)
  1413. }
  1414. // Replace the original content with the new one. If it didn't work,
  1415. // leave the temp file in place for reuse.
  1416. if err := osutil.RenameOrCopy(f.CopyRangeMethod, f.mtimefs, f.mtimefs, tempName, file.Name); err != nil {
  1417. return fmt.Errorf("replacing file: %w", err)
  1418. }
  1419. // Set the correct timestamp on the new file
  1420. f.mtimefs.Chtimes(file.Name, file.ModTime(), file.ModTime()) // never fails
  1421. // Record the updated file in the index
  1422. dbUpdateChan <- dbUpdateJob{file, dbUpdateHandleFile}
  1423. return nil
  1424. }
  1425. func (f *sendReceiveFolder) finisherRoutine(snap *db.Snapshot, in <-chan *sharedPullerState, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
  1426. for state := range in {
  1427. if closed, err := state.finalClose(); closed {
  1428. l.Debugln(f, "closing", state.file.Name)
  1429. f.queue.Done(state.file.Name)
  1430. if err == nil {
  1431. err = f.performFinish(state.file, state.curFile, state.hasCurFile, state.tempName, snap, dbUpdateChan, scanChan)
  1432. }
  1433. if err != nil {
  1434. f.newPullError(state.file.Name, fmt.Errorf("finishing: %w", err))
  1435. } else {
  1436. minBlocksPerBlock := state.file.BlockSize() / protocol.MinBlockSize
  1437. blockStatsMut.Lock()
  1438. blockStats["total"] += (state.reused + state.copyTotal + state.pullTotal) * minBlocksPerBlock
  1439. blockStats["reused"] += state.reused * minBlocksPerBlock
  1440. blockStats["pulled"] += state.pullTotal * minBlocksPerBlock
  1441. // copyOriginShifted is counted towards copyOrigin due to progress bar reasons
  1442. // for reporting reasons we want to separate these.
  1443. blockStats["copyOrigin"] += (state.copyOrigin - state.copyOriginShifted) * minBlocksPerBlock
  1444. blockStats["copyOriginShifted"] += state.copyOriginShifted * minBlocksPerBlock
  1445. blockStats["copyElsewhere"] += (state.copyTotal - state.copyOrigin) * minBlocksPerBlock
  1446. blockStatsMut.Unlock()
  1447. }
  1448. if f.Type != config.FolderTypeReceiveEncrypted {
  1449. f.model.progressEmitter.Deregister(state)
  1450. }
  1451. f.evLogger.Log(events.ItemFinished, map[string]interface{}{
  1452. "folder": f.folderID,
  1453. "item": state.file.Name,
  1454. "error": events.Error(err),
  1455. "type": "file",
  1456. "action": "update",
  1457. })
  1458. }
  1459. }
  1460. }
  1461. // Moves the given filename to the front of the job queue
  1462. func (f *sendReceiveFolder) BringToFront(filename string) {
  1463. f.queue.BringToFront(filename)
  1464. }
  1465. func (f *sendReceiveFolder) Jobs(page, perpage int) ([]string, []string, int) {
  1466. return f.queue.Jobs(page, perpage)
  1467. }
  1468. // dbUpdaterRoutine aggregates db updates and commits them in batches no
  1469. // larger than 1000 items, and no more delayed than 2 seconds.
  1470. func (f *sendReceiveFolder) dbUpdaterRoutine(dbUpdateChan <-chan dbUpdateJob) {
  1471. const maxBatchTime = 2 * time.Second
  1472. changedDirs := make(map[string]struct{})
  1473. found := false
  1474. var lastFile protocol.FileInfo
  1475. tick := time.NewTicker(maxBatchTime)
  1476. defer tick.Stop()
  1477. batch := db.NewFileInfoBatch(func(files []protocol.FileInfo) error {
  1478. // sync directories
  1479. for dir := range changedDirs {
  1480. delete(changedDirs, dir)
  1481. if !f.FolderConfiguration.DisableFsync {
  1482. fd, err := f.mtimefs.Open(dir)
  1483. if err != nil {
  1484. l.Debugf("fsync %q failed: %v", dir, err)
  1485. continue
  1486. }
  1487. if err := fd.Sync(); err != nil {
  1488. l.Debugf("fsync %q failed: %v", dir, err)
  1489. }
  1490. fd.Close()
  1491. }
  1492. }
  1493. // All updates to file/folder objects that originated remotely
  1494. // (across the network) use this call to updateLocals
  1495. f.updateLocalsFromPulling(files)
  1496. if found {
  1497. f.ReceivedFile(lastFile.Name, lastFile.IsDeleted())
  1498. found = false
  1499. }
  1500. return nil
  1501. })
  1502. recvEnc := f.Type == config.FolderTypeReceiveEncrypted
  1503. loop:
  1504. for {
  1505. select {
  1506. case job, ok := <-dbUpdateChan:
  1507. if !ok {
  1508. break loop
  1509. }
  1510. switch job.jobType {
  1511. case dbUpdateHandleFile, dbUpdateShortcutFile:
  1512. changedDirs[filepath.Dir(job.file.Name)] = struct{}{}
  1513. if recvEnc {
  1514. job.file.Size += encryptionTrailerSize(job.file)
  1515. }
  1516. case dbUpdateHandleDir:
  1517. changedDirs[job.file.Name] = struct{}{}
  1518. case dbUpdateHandleSymlink, dbUpdateInvalidate:
  1519. // fsyncing symlinks is only supported by MacOS
  1520. // and invalidated files are db only changes -> no sync
  1521. }
  1522. // For some reason we seem to care about file deletions and
  1523. // content modification, but not about metadata and dirs/symlinks.
  1524. if !job.file.IsInvalid() && job.jobType&(dbUpdateHandleFile|dbUpdateDeleteFile) != 0 {
  1525. found = true
  1526. lastFile = job.file
  1527. }
  1528. if !job.file.IsDeleted() && !job.file.IsInvalid() {
  1529. // Now that the file is finalized, grab possibly updated
  1530. // inode change time from disk into the local FileInfo. We
  1531. // use this change time to check for changes to xattrs etc
  1532. // on next scan.
  1533. if err := f.updateFileInfoChangeTime(&job.file); err != nil {
  1534. l.Warnf("Error updating metadata for %v at database commit: %v", job.file.Name, err)
  1535. }
  1536. }
  1537. job.file.Sequence = 0
  1538. batch.Append(job.file)
  1539. batch.FlushIfFull()
  1540. case <-tick.C:
  1541. batch.Flush()
  1542. }
  1543. }
  1544. batch.Flush()
  1545. }
  1546. // pullScannerRoutine aggregates paths to be scanned after pulling. The scan is
  1547. // scheduled once when scanChan is closed (scanning can not happen during pulling).
  1548. func (f *sendReceiveFolder) pullScannerRoutine(scanChan <-chan string) {
  1549. toBeScanned := make(map[string]struct{})
  1550. for path := range scanChan {
  1551. toBeScanned[path] = struct{}{}
  1552. }
  1553. if len(toBeScanned) != 0 {
  1554. scanList := make([]string, 0, len(toBeScanned))
  1555. for path := range toBeScanned {
  1556. l.Debugln(f, "scheduling scan after pulling for", path)
  1557. scanList = append(scanList, path)
  1558. }
  1559. f.Scan(scanList)
  1560. }
  1561. }
  1562. func (f *sendReceiveFolder) inConflict(current, replacement protocol.Vector) bool {
  1563. if current.Concurrent(replacement) {
  1564. // Obvious case
  1565. return true
  1566. }
  1567. if replacement.Counter(f.shortID) > current.Counter(f.shortID) {
  1568. // The replacement file contains a higher version for ourselves than
  1569. // what we have. This isn't supposed to be possible, since it's only
  1570. // we who can increment that counter. We take it as a sign that
  1571. // something is wrong (our index may have been corrupted or removed)
  1572. // and flag it as a conflict.
  1573. return true
  1574. }
  1575. return false
  1576. }
  1577. func (f *sendReceiveFolder) moveForConflict(name, lastModBy string, scanChan chan<- string) error {
  1578. if isConflict(name) {
  1579. l.Infoln("Conflict for", name, "which is already a conflict copy; not copying again.")
  1580. if err := f.mtimefs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1581. return fmt.Errorf("%s: %w", contextRemovingOldItem, err)
  1582. }
  1583. return nil
  1584. }
  1585. if f.MaxConflicts == 0 {
  1586. if err := f.mtimefs.Remove(name); err != nil && !fs.IsNotExist(err) {
  1587. return fmt.Errorf("%s: %w", contextRemovingOldItem, err)
  1588. }
  1589. return nil
  1590. }
  1591. newName := conflictName(name, lastModBy)
  1592. err := f.mtimefs.Rename(name, newName)
  1593. if fs.IsNotExist(err) {
  1594. // We were supposed to move a file away but it does not exist. Either
  1595. // the user has already moved it away, or the conflict was between a
  1596. // remote modification and a local delete. In either way it does not
  1597. // matter, go ahead as if the move succeeded.
  1598. err = nil
  1599. }
  1600. if f.MaxConflicts > -1 {
  1601. matches := existingConflicts(name, f.mtimefs)
  1602. if len(matches) > f.MaxConflicts {
  1603. sort.Sort(sort.Reverse(sort.StringSlice(matches)))
  1604. for _, match := range matches[f.MaxConflicts:] {
  1605. if gerr := f.mtimefs.Remove(match); gerr != nil {
  1606. l.Debugln(f, "removing extra conflict", gerr)
  1607. }
  1608. }
  1609. }
  1610. }
  1611. if err == nil {
  1612. scanChan <- newName
  1613. }
  1614. return err
  1615. }
  1616. func (f *sendReceiveFolder) newPullError(path string, err error) {
  1617. if errors.Is(err, f.ctx.Err()) {
  1618. // Error because the folder stopped - no point logging/tracking
  1619. return
  1620. }
  1621. f.errorsMut.Lock()
  1622. defer f.errorsMut.Unlock()
  1623. // We might get more than one error report for a file (i.e. error on
  1624. // Write() followed by Close()); we keep the first error as that is
  1625. // probably closer to the root cause.
  1626. if _, ok := f.tempPullErrors[path]; ok {
  1627. return
  1628. }
  1629. // Establish context to differentiate from errors while scanning.
  1630. // Use "syncing" as opposed to "pulling" as the latter might be used
  1631. // for errors occurring specifically in the puller routine.
  1632. errStr := fmt.Sprintf("syncing: %s", err)
  1633. f.tempPullErrors[path] = errStr
  1634. l.Debugf("%v new error for %v: %v", f, path, err)
  1635. }
  1636. // deleteItemOnDisk deletes the file represented by old that is about to be replaced by new.
  1637. func (f *sendReceiveFolder) deleteItemOnDisk(item protocol.FileInfo, snap *db.Snapshot, scanChan chan<- string) (err error) {
  1638. defer func() {
  1639. if err != nil {
  1640. err = fmt.Errorf("%s: %w", contextRemovingOldItem, err)
  1641. }
  1642. }()
  1643. switch {
  1644. case item.IsDirectory():
  1645. // Directories aren't archived and need special treatment due
  1646. // to potential children.
  1647. return f.deleteDirOnDisk(item.Name, snap, scanChan)
  1648. case !item.IsSymlink() && f.versioner != nil:
  1649. // If we should use versioning, let the versioner archive the
  1650. // file before we replace it. Archiving a non-existent file is not
  1651. // an error.
  1652. // Symlinks aren't archived.
  1653. return f.inWritableDir(f.versioner.Archive, item.Name)
  1654. }
  1655. return f.inWritableDir(f.mtimefs.Remove, item.Name)
  1656. }
  1657. // deleteDirOnDisk attempts to delete a directory. It checks for files/dirs inside
  1658. // the directory and removes them if possible or returns an error if it fails
  1659. func (f *sendReceiveFolder) deleteDirOnDisk(dir string, snap *db.Snapshot, scanChan chan<- string) error {
  1660. if err := osutil.TraversesSymlink(f.mtimefs, filepath.Dir(dir)); err != nil {
  1661. return err
  1662. }
  1663. if err := f.deleteDirOnDiskHandleChildren(dir, snap, scanChan); err != nil {
  1664. return err
  1665. }
  1666. err := f.inWritableDir(f.mtimefs.Remove, dir)
  1667. if err == nil || fs.IsNotExist(err) {
  1668. // It was removed or it doesn't exist to start with
  1669. return nil
  1670. }
  1671. if _, serr := f.mtimefs.Lstat(dir); serr != nil && !fs.IsPermission(serr) {
  1672. // We get an error just looking at the directory, and it's not a
  1673. // permission problem. Lets assume the error is in fact some variant
  1674. // of "file does not exist" (possibly expressed as some parent being a
  1675. // file and not a directory etc) and that the delete is handled.
  1676. return nil
  1677. }
  1678. return err
  1679. }
  1680. func (f *sendReceiveFolder) deleteDirOnDiskHandleChildren(dir string, snap *db.Snapshot, scanChan chan<- string) error {
  1681. var dirsToDelete []string
  1682. var hasIgnored, hasKnown, hasToBeScanned, hasReceiveOnlyChanged bool
  1683. var delErr error
  1684. err := f.mtimefs.Walk(dir, func(path string, info fs.FileInfo, err error) error {
  1685. if path == dir {
  1686. return nil
  1687. }
  1688. if err != nil {
  1689. return err
  1690. }
  1691. switch match := f.ignores.Match(path); {
  1692. case match.IsDeletable():
  1693. if info.IsDir() {
  1694. dirsToDelete = append(dirsToDelete, path)
  1695. return nil
  1696. }
  1697. fallthrough
  1698. case fs.IsTemporary(path):
  1699. if err := f.mtimefs.Remove(path); err != nil && delErr == nil {
  1700. delErr = err
  1701. }
  1702. return nil
  1703. case match.IsIgnored():
  1704. hasIgnored = true
  1705. return nil
  1706. }
  1707. cf, ok := snap.Get(protocol.LocalDeviceID, path)
  1708. switch {
  1709. case !ok || cf.IsDeleted():
  1710. // Something appeared in the dir that we either are not
  1711. // aware of at all or that we think should be deleted
  1712. // -> schedule scan.
  1713. scanChan <- path
  1714. hasToBeScanned = true
  1715. return nil
  1716. case ok && f.Type == config.FolderTypeReceiveOnly && cf.IsReceiveOnlyChanged():
  1717. hasReceiveOnlyChanged = true
  1718. return nil
  1719. }
  1720. diskFile, err := scanner.CreateFileInfo(info, path, f.mtimefs, f.SyncOwnership, f.SyncXattrs, f.XattrFilter)
  1721. if err != nil {
  1722. // Lets just assume the file has changed.
  1723. scanChan <- path
  1724. hasToBeScanned = true
  1725. return nil
  1726. }
  1727. if !cf.IsEquivalentOptional(diskFile, protocol.FileInfoComparison{
  1728. ModTimeWindow: f.modTimeWindow,
  1729. IgnorePerms: f.IgnorePerms,
  1730. IgnoreBlocks: true,
  1731. IgnoreFlags: protocol.LocalAllFlags,
  1732. IgnoreOwnership: !f.SyncOwnership,
  1733. IgnoreXattrs: !f.SyncXattrs,
  1734. }) {
  1735. // File on disk changed compared to what we have in db
  1736. // -> schedule scan.
  1737. scanChan <- path
  1738. hasToBeScanned = true
  1739. return nil
  1740. }
  1741. // Dir contains file that is valid according to db and
  1742. // not ignored -> something weird is going on
  1743. hasKnown = true
  1744. return nil
  1745. })
  1746. if err != nil {
  1747. return err
  1748. }
  1749. for i := range dirsToDelete {
  1750. if err := f.mtimefs.Remove(dirsToDelete[len(dirsToDelete)-1-i]); err != nil && delErr == nil {
  1751. delErr = err
  1752. }
  1753. }
  1754. // "Error precedence":
  1755. // Something changed on disk, check that and maybe all else gets resolved
  1756. if hasToBeScanned {
  1757. return errDirHasToBeScanned
  1758. }
  1759. // Ignored files will never be touched, i.e. this will keep failing until
  1760. // user acts.
  1761. if hasIgnored {
  1762. return errDirHasIgnored
  1763. }
  1764. if hasReceiveOnlyChanged {
  1765. // Pretend we deleted the directory. It will be resurrected as a
  1766. // receive-only changed item on scan.
  1767. scanChan <- dir
  1768. return nil
  1769. }
  1770. if hasKnown {
  1771. return errDirNotEmpty
  1772. }
  1773. // All good, except maybe failing to remove a (?d) ignored item
  1774. return delErr
  1775. }
  1776. // scanIfItemChanged schedules the given file for scanning and returns errModified
  1777. // if it differs from the information in the database. Returns nil if the file has
  1778. // not changed.
  1779. func (f *sendReceiveFolder) scanIfItemChanged(name string, stat fs.FileInfo, item protocol.FileInfo, hasItem bool, scanChan chan<- string) (err error) {
  1780. defer func() {
  1781. if err == errModified {
  1782. scanChan <- name
  1783. }
  1784. }()
  1785. if !hasItem || item.Deleted {
  1786. // The item appeared from nowhere
  1787. return errModified
  1788. }
  1789. // Check that the item on disk is what we expect it to be according
  1790. // to the database. If there's a mismatch here, there might be local
  1791. // changes that we don't know about yet and we should scan before
  1792. // touching the item.
  1793. statItem, err := scanner.CreateFileInfo(stat, item.Name, f.mtimefs, f.SyncOwnership, f.SyncXattrs, f.XattrFilter)
  1794. if err != nil {
  1795. return fmt.Errorf("comparing item on disk to db: %w", err)
  1796. }
  1797. if !statItem.IsEquivalentOptional(item, protocol.FileInfoComparison{
  1798. ModTimeWindow: f.modTimeWindow,
  1799. IgnorePerms: f.IgnorePerms,
  1800. IgnoreBlocks: true,
  1801. IgnoreFlags: protocol.LocalAllFlags,
  1802. IgnoreOwnership: !f.SyncOwnership,
  1803. IgnoreXattrs: !f.SyncXattrs,
  1804. }) {
  1805. return errModified
  1806. }
  1807. return nil
  1808. }
  1809. // checkToBeDeleted makes sure the file on disk is compatible with what there is
  1810. // in the DB before the caller proceeds with actually deleting it.
  1811. // I.e. non-nil error status means "Do not delete!" or "is already deleted".
  1812. func (f *sendReceiveFolder) checkToBeDeleted(file, cur protocol.FileInfo, hasCur bool, scanChan chan<- string) error {
  1813. if err := osutil.TraversesSymlink(f.mtimefs, filepath.Dir(file.Name)); err != nil {
  1814. l.Debugln(f, "not deleting item behind symlink on disk, but update db", file.Name)
  1815. return fs.ErrNotExist
  1816. }
  1817. stat, err := f.mtimefs.Lstat(file.Name)
  1818. deleted := fs.IsNotExist(err) || fs.IsErrCaseConflict(err)
  1819. if !deleted && err != nil {
  1820. return err
  1821. }
  1822. if deleted {
  1823. if hasCur && !cur.Deleted && !cur.IsUnsupported() {
  1824. scanChan <- file.Name
  1825. return errModified
  1826. }
  1827. l.Debugln(f, "not deleting item we don't have, but update db", file.Name)
  1828. return err
  1829. }
  1830. return f.scanIfItemChanged(file.Name, stat, cur, hasCur, scanChan)
  1831. }
  1832. // setPlatformData makes adjustments to the metadata that should happen for
  1833. // all types (files, directories, symlinks). This should be one of the last
  1834. // things we do to a file when syncing changes to it.
  1835. func (f *sendReceiveFolder) setPlatformData(file *protocol.FileInfo, name string) error {
  1836. if f.SyncXattrs {
  1837. // Set extended attributes.
  1838. if err := f.mtimefs.SetXattr(name, file.Platform.Xattrs(), f.XattrFilter); errors.Is(err, fs.ErrXattrsNotSupported) {
  1839. l.Debugf("Cannot set xattrs on %q: %v", file.Name, err)
  1840. } else if err != nil {
  1841. return err
  1842. }
  1843. }
  1844. if f.SyncOwnership {
  1845. // Set ownership based on file metadata.
  1846. if err := f.syncOwnership(file, name); err != nil {
  1847. return err
  1848. }
  1849. } else if f.CopyOwnershipFromParent {
  1850. // Copy the parent owner and group.
  1851. if err := f.copyOwnershipFromParent(name); err != nil {
  1852. return err
  1853. }
  1854. }
  1855. return nil
  1856. }
  1857. func (f *sendReceiveFolder) copyOwnershipFromParent(path string) error {
  1858. if build.IsWindows {
  1859. // Can't do anything.
  1860. return nil
  1861. }
  1862. info, err := f.mtimefs.Lstat(filepath.Dir(path))
  1863. if err != nil {
  1864. return fmt.Errorf("copy owner from parent: %w", err)
  1865. }
  1866. if err := f.mtimefs.Lchown(path, strconv.Itoa(info.Owner()), strconv.Itoa(info.Group())); err != nil {
  1867. return fmt.Errorf("copy owner from parent: %w", err)
  1868. }
  1869. return nil
  1870. }
  1871. func (f *sendReceiveFolder) inWritableDir(fn func(string) error, path string) error {
  1872. return inWritableDir(fn, f.mtimefs, path, f.IgnorePerms)
  1873. }
  1874. func (f *sendReceiveFolder) limitedWriteAt(fd io.WriterAt, data []byte, offset int64) error {
  1875. return f.withLimiter(func() error {
  1876. _, err := fd.WriteAt(data, offset)
  1877. return err
  1878. })
  1879. }
  1880. func (f *sendReceiveFolder) withLimiter(fn func() error) error {
  1881. if err := f.writeLimiter.TakeWithContext(f.ctx, 1); err != nil {
  1882. return err
  1883. }
  1884. defer f.writeLimiter.Give(1)
  1885. return fn()
  1886. }
  1887. // updateFileInfoChangeTime updates the inode change time in the FileInfo,
  1888. // because that depends on the current, new, state of the file on disk.
  1889. func (f *sendReceiveFolder) updateFileInfoChangeTime(file *protocol.FileInfo) error {
  1890. info, err := f.mtimefs.Lstat(file.Name)
  1891. if err != nil {
  1892. return err
  1893. }
  1894. if ct := info.InodeChangeTime(); !ct.IsZero() {
  1895. file.InodeChangeNs = ct.UnixNano()
  1896. } else {
  1897. file.InodeChangeNs = 0
  1898. }
  1899. return nil
  1900. }
  1901. // A []FileError is sent as part of an event and will be JSON serialized.
  1902. type FileError struct {
  1903. Path string `json:"path"`
  1904. Err string `json:"error"`
  1905. }
  1906. type fileErrorList []FileError
  1907. func (l fileErrorList) Len() int {
  1908. return len(l)
  1909. }
  1910. func (l fileErrorList) Less(a, b int) bool {
  1911. return l[a].Path < l[b].Path
  1912. }
  1913. func (l fileErrorList) Swap(a, b int) {
  1914. l[a], l[b] = l[b], l[a]
  1915. }
  1916. func conflictName(name, lastModBy string) string {
  1917. ext := filepath.Ext(name)
  1918. return name[:len(name)-len(ext)] + time.Now().Format(".sync-conflict-20060102-150405-") + lastModBy + ext
  1919. }
  1920. func isConflict(name string) bool {
  1921. return strings.Contains(filepath.Base(name), ".sync-conflict-")
  1922. }
  1923. func existingConflicts(name string, fs fs.Filesystem) []string {
  1924. ext := filepath.Ext(name)
  1925. matches, err := fs.Glob(name[:len(name)-len(ext)] + ".sync-conflict-????????-??????*" + ext)
  1926. if err != nil {
  1927. l.Debugln("globbing for conflicts", err)
  1928. }
  1929. return matches
  1930. }