folder_sendrecv.go 56 KB

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