folder_sendrecv.go 65 KB

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