rwfolder.go 56 KB

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