folder_sendrecv.go 55 KB

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