folder_sendrecv.go 55 KB

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