folder_sendrecv.go 57 KB

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