model.go 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759
  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. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "net"
  13. "path/filepath"
  14. "reflect"
  15. "regexp"
  16. "runtime"
  17. "strings"
  18. stdsync "sync"
  19. "time"
  20. "github.com/syncthing/syncthing/lib/config"
  21. "github.com/syncthing/syncthing/lib/connections"
  22. "github.com/syncthing/syncthing/lib/db"
  23. "github.com/syncthing/syncthing/lib/events"
  24. "github.com/syncthing/syncthing/lib/fs"
  25. "github.com/syncthing/syncthing/lib/ignore"
  26. "github.com/syncthing/syncthing/lib/osutil"
  27. "github.com/syncthing/syncthing/lib/protocol"
  28. "github.com/syncthing/syncthing/lib/scanner"
  29. "github.com/syncthing/syncthing/lib/stats"
  30. "github.com/syncthing/syncthing/lib/sync"
  31. "github.com/syncthing/syncthing/lib/upgrade"
  32. "github.com/syncthing/syncthing/lib/versioner"
  33. "github.com/thejerf/suture"
  34. )
  35. // How many files to send in each Index/IndexUpdate message.
  36. const (
  37. maxBatchSizeBytes = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  38. maxBatchSizeFiles = 1000 // Either way, don't include more files than this
  39. )
  40. type service interface {
  41. BringToFront(string)
  42. Override()
  43. Revert()
  44. DelayScan(d time.Duration)
  45. SchedulePull() // something relevant changed, we should try a pull
  46. Jobs() ([]string, []string) // In progress, Queued
  47. Scan(subs []string) error
  48. Serve()
  49. Stop()
  50. CheckHealth() error
  51. Errors() []FileError
  52. WatchError() error
  53. ForceRescan(file protocol.FileInfo) error
  54. GetStatistics() stats.FolderStatistics
  55. getState() (folderState, time.Time, error)
  56. }
  57. type Availability struct {
  58. ID protocol.DeviceID `json:"id"`
  59. FromTemporary bool `json:"fromTemporary"`
  60. }
  61. type Model interface {
  62. suture.Service
  63. connections.Model
  64. AddFolder(cfg config.FolderConfiguration)
  65. RestartFolder(from, to config.FolderConfiguration)
  66. StartFolder(folder string)
  67. ResetFolder(folder string)
  68. DelayScan(folder string, next time.Duration)
  69. ScanFolder(folder string) error
  70. ScanFolders() map[string]error
  71. ScanFolderSubdirs(folder string, subs []string) error
  72. State(folder string) (string, time.Time, error)
  73. FolderErrors(folder string) ([]FileError, error)
  74. WatchError(folder string) error
  75. Override(folder string)
  76. Revert(folder string)
  77. BringToFront(folder, file string)
  78. GetIgnores(folder string) ([]string, []string, error)
  79. SetIgnores(folder string, content []string) error
  80. GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error)
  81. RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]string, error)
  82. LocalChangedFiles(folder string, page, perpage int) []db.FileInfoTruncated
  83. NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated)
  84. RemoteNeedFolderFiles(device protocol.DeviceID, folder string, page, perpage int) ([]db.FileInfoTruncated, error)
  85. CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool)
  86. CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool)
  87. Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) []Availability
  88. GlobalSize(folder string) db.Counts
  89. LocalSize(folder string) db.Counts
  90. NeedSize(folder string) db.Counts
  91. ReceiveOnlyChangedSize(folder string) db.Counts
  92. CurrentSequence(folder string) (int64, bool)
  93. RemoteSequence(folder string) (int64, bool)
  94. Completion(device protocol.DeviceID, folder string) FolderCompletion
  95. ConnectionStats() map[string]interface{}
  96. DeviceStatistics() map[string]stats.DeviceStatistics
  97. FolderStatistics() map[string]stats.FolderStatistics
  98. UsageReportingStats(version int, preview bool) map[string]interface{}
  99. StartDeadlockDetector(timeout time.Duration)
  100. GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{}
  101. }
  102. type model struct {
  103. *suture.Supervisor
  104. cfg config.Wrapper
  105. db *db.Lowlevel
  106. finder *db.BlockFinder
  107. progressEmitter *ProgressEmitter
  108. id protocol.DeviceID
  109. shortID protocol.ShortID
  110. cacheIgnoredFiles bool
  111. protectedFiles []string
  112. clientName string
  113. clientVersion string
  114. fmut sync.RWMutex // protects the below
  115. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  116. folderFiles map[string]*db.FileSet // folder -> files
  117. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  118. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  119. folderRunners map[string]service // folder -> puller or scanner
  120. folderRunnerTokens map[string][]suture.ServiceToken // folder -> tokens for puller or scanner
  121. folderRestartMuts syncMutexMap // folder -> restart mutex
  122. pmut sync.RWMutex // protects the below
  123. conn map[protocol.DeviceID]connections.Connection
  124. connRequestLimiters map[protocol.DeviceID]*byteSemaphore
  125. closed map[protocol.DeviceID]chan struct{}
  126. helloMessages map[protocol.DeviceID]protocol.HelloResult
  127. deviceDownloads map[protocol.DeviceID]*deviceDownloadState
  128. remotePausedFolders map[protocol.DeviceID][]string // deviceID -> folders
  129. foldersRunning int32 // for testing only
  130. }
  131. type folderFactory func(*model, *db.FileSet, *ignore.Matcher, config.FolderConfiguration, versioner.Versioner, fs.Filesystem) service
  132. var (
  133. folderFactories = make(map[config.FolderType]folderFactory)
  134. )
  135. var (
  136. errDeviceUnknown = errors.New("unknown device")
  137. errDevicePaused = errors.New("device is paused")
  138. errDeviceIgnored = errors.New("device is ignored")
  139. ErrFolderPaused = errors.New("folder is paused")
  140. errFolderNotRunning = errors.New("folder is not running")
  141. errFolderMissing = errors.New("no such folder")
  142. errNetworkNotAllowed = errors.New("network not allowed")
  143. // errors about why a connection is closed
  144. errIgnoredFolderRemoved = errors.New("folder no longer ignored")
  145. errReplacingConnection = errors.New("replacing connection")
  146. errStopped = errors.New("Syncthing is being stopped")
  147. )
  148. // NewModel creates and starts a new model. The model starts in read-only mode,
  149. // where it sends index information to connected peers and responds to requests
  150. // for file data without altering the local folder in any way.
  151. func NewModel(cfg config.Wrapper, id protocol.DeviceID, clientName, clientVersion string, ldb *db.Lowlevel, protectedFiles []string) Model {
  152. m := &model{
  153. Supervisor: suture.New("model", suture.Spec{
  154. Log: func(line string) {
  155. l.Debugln(line)
  156. },
  157. PassThroughPanics: true,
  158. }),
  159. cfg: cfg,
  160. db: ldb,
  161. finder: db.NewBlockFinder(ldb),
  162. progressEmitter: NewProgressEmitter(cfg),
  163. id: id,
  164. shortID: id.Short(),
  165. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  166. protectedFiles: protectedFiles,
  167. clientName: clientName,
  168. clientVersion: clientVersion,
  169. folderCfgs: make(map[string]config.FolderConfiguration),
  170. folderFiles: make(map[string]*db.FileSet),
  171. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  172. folderIgnores: make(map[string]*ignore.Matcher),
  173. folderRunners: make(map[string]service),
  174. folderRunnerTokens: make(map[string][]suture.ServiceToken),
  175. conn: make(map[protocol.DeviceID]connections.Connection),
  176. connRequestLimiters: make(map[protocol.DeviceID]*byteSemaphore),
  177. closed: make(map[protocol.DeviceID]chan struct{}),
  178. helloMessages: make(map[protocol.DeviceID]protocol.HelloResult),
  179. deviceDownloads: make(map[protocol.DeviceID]*deviceDownloadState),
  180. remotePausedFolders: make(map[protocol.DeviceID][]string),
  181. fmut: sync.NewRWMutex(),
  182. pmut: sync.NewRWMutex(),
  183. }
  184. m.Add(m.progressEmitter)
  185. scanLimiter.setCapacity(cfg.Options().MaxConcurrentScans)
  186. cfg.Subscribe(m)
  187. return m
  188. }
  189. func (m *model) Stop() {
  190. m.Supervisor.Stop()
  191. devs := m.cfg.Devices()
  192. ids := make([]protocol.DeviceID, 0, len(devs))
  193. for id := range devs {
  194. ids = append(ids, id)
  195. }
  196. m.pmut.RLock()
  197. closed := make([]chan struct{}, 0, len(m.closed))
  198. for _, c := range m.closed {
  199. closed = append(closed, c)
  200. }
  201. m.pmut.RUnlock()
  202. m.closeConns(ids, errStopped)
  203. for _, c := range closed {
  204. <-c
  205. }
  206. }
  207. // StartDeadlockDetector starts a deadlock detector on the models locks which
  208. // causes panics in case the locks cannot be acquired in the given timeout
  209. // period.
  210. func (m *model) StartDeadlockDetector(timeout time.Duration) {
  211. l.Infof("Starting deadlock detector with %v timeout", timeout)
  212. detector := newDeadlockDetector(timeout)
  213. detector.Watch("fmut", m.fmut)
  214. detector.Watch("pmut", m.pmut)
  215. }
  216. // StartFolder constructs the folder service and starts it.
  217. func (m *model) StartFolder(folder string) {
  218. m.fmut.Lock()
  219. defer m.fmut.Unlock()
  220. folderCfg := m.folderCfgs[folder]
  221. m.startFolderLocked(folderCfg)
  222. l.Infof("Ready to synchronize %s (%s)", folderCfg.Description(), folderCfg.Type)
  223. }
  224. // Need to hold lock on m.fmut when calling this.
  225. func (m *model) startFolderLocked(cfg config.FolderConfiguration) {
  226. if err := m.checkFolderRunningLocked(cfg.ID); err == errFolderMissing {
  227. panic("cannot start nonexistent folder " + cfg.Description())
  228. } else if err == nil {
  229. panic("cannot start already running folder " + cfg.Description())
  230. }
  231. folderFactory, ok := folderFactories[cfg.Type]
  232. if !ok {
  233. panic(fmt.Sprintf("unknown folder type 0x%x", cfg.Type))
  234. }
  235. folder := cfg.ID
  236. fset := m.folderFiles[folder]
  237. // Find any devices for which we hold the index in the db, but the folder
  238. // is not shared, and drop it.
  239. expected := mapDevices(cfg.DeviceIDs())
  240. for _, available := range fset.ListDevices() {
  241. if _, ok := expected[available]; !ok {
  242. l.Debugln("dropping", folder, "state for", available)
  243. fset.Drop(available)
  244. }
  245. }
  246. // Close connections to affected devices
  247. m.fmut.Unlock()
  248. m.closeConns(cfg.DeviceIDs(), fmt.Errorf("started folder %v", cfg.Description()))
  249. m.fmut.Lock()
  250. v, ok := fset.Sequence(protocol.LocalDeviceID), true
  251. indexHasFiles := ok && v > 0
  252. if !indexHasFiles {
  253. // It's a blank folder, so this may the first time we're looking at
  254. // it. Attempt to create and tag with our marker as appropriate. We
  255. // don't really do anything with errors at this point except warn -
  256. // if these things don't work, we still want to start the folder and
  257. // it'll show up as errored later.
  258. if err := cfg.CreateRoot(); err != nil {
  259. l.Warnln("Failed to create folder root directory", err)
  260. } else if err = cfg.CreateMarker(); err != nil {
  261. l.Warnln("Failed to create folder marker:", err)
  262. }
  263. }
  264. ver := cfg.Versioner()
  265. if service, ok := ver.(suture.Service); ok {
  266. // The versioner implements the suture.Service interface, so
  267. // expects to be run in the background in addition to being called
  268. // when files are going to be archived.
  269. token := m.Add(service)
  270. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  271. }
  272. ffs := fset.MtimeFS()
  273. // These are our metadata files, and they should always be hidden.
  274. ffs.Hide(config.DefaultMarkerName)
  275. ffs.Hide(".stversions")
  276. ffs.Hide(".stignore")
  277. p := folderFactory(m, fset, m.folderIgnores[folder], cfg, ver, ffs)
  278. m.folderRunners[folder] = p
  279. m.warnAboutOverwritingProtectedFiles(folder)
  280. token := m.Add(p)
  281. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  282. }
  283. func (m *model) warnAboutOverwritingProtectedFiles(folder string) {
  284. if m.folderCfgs[folder].Type == config.FolderTypeSendOnly {
  285. return
  286. }
  287. // This is a bit of a hack.
  288. ffs := m.folderCfgs[folder].Filesystem()
  289. if ffs.Type() != fs.FilesystemTypeBasic {
  290. return
  291. }
  292. folderLocation := ffs.URI()
  293. ignores := m.folderIgnores[folder]
  294. var filesAtRisk []string
  295. for _, protectedFilePath := range m.protectedFiles {
  296. // check if file is synced in this folder
  297. if protectedFilePath != folderLocation && !fs.IsParent(protectedFilePath, folderLocation) {
  298. continue
  299. }
  300. // check if file is ignored
  301. relPath, _ := filepath.Rel(folderLocation, protectedFilePath)
  302. if ignores.Match(relPath).IsIgnored() {
  303. continue
  304. }
  305. filesAtRisk = append(filesAtRisk, protectedFilePath)
  306. }
  307. if len(filesAtRisk) > 0 {
  308. l.Warnln("Some protected files may be overwritten and cause issues. See https://docs.syncthing.net/users/config.html#syncing-configuration-files for more information. The at risk files are:", strings.Join(filesAtRisk, ", "))
  309. }
  310. }
  311. func (m *model) AddFolder(cfg config.FolderConfiguration) {
  312. if len(cfg.ID) == 0 {
  313. panic("cannot add empty folder id")
  314. }
  315. if len(cfg.Path) == 0 {
  316. panic("cannot add empty folder path")
  317. }
  318. m.fmut.Lock()
  319. defer m.fmut.Unlock()
  320. m.addFolderLocked(cfg)
  321. }
  322. func (m *model) addFolderLocked(cfg config.FolderConfiguration) {
  323. m.folderCfgs[cfg.ID] = cfg
  324. folderFs := cfg.Filesystem()
  325. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, folderFs, m.db)
  326. ignores := ignore.New(folderFs, ignore.WithCache(m.cacheIgnoredFiles))
  327. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  328. l.Warnln("Loading ignores:", err)
  329. }
  330. m.folderIgnores[cfg.ID] = ignores
  331. }
  332. func (m *model) RemoveFolder(cfg config.FolderConfiguration) {
  333. m.fmut.Lock()
  334. defer m.fmut.Unlock()
  335. // Delete syncthing specific files
  336. cfg.Filesystem().RemoveAll(config.DefaultMarkerName)
  337. m.tearDownFolderLocked(cfg, fmt.Errorf("removing folder %v", cfg.Description()))
  338. // Remove it from the database
  339. db.DropFolder(m.db, cfg.ID)
  340. }
  341. // Need to hold lock on m.fmut when calling this.
  342. func (m *model) tearDownFolderLocked(cfg config.FolderConfiguration, err error) {
  343. // Stop the services running for this folder and wait for them to finish
  344. // stopping to prevent races on restart.
  345. tokens := m.folderRunnerTokens[cfg.ID]
  346. m.fmut.Unlock()
  347. // Close connections to affected devices
  348. // Must happen before stopping the folder service to abort ongoing
  349. // transmissions and thus allow timely service termination.
  350. m.closeConns(cfg.DeviceIDs(), err)
  351. for _, id := range tokens {
  352. m.RemoveAndWait(id, 0)
  353. }
  354. m.fmut.Lock()
  355. // Clean up our config maps
  356. delete(m.folderCfgs, cfg.ID)
  357. delete(m.folderFiles, cfg.ID)
  358. delete(m.folderIgnores, cfg.ID)
  359. delete(m.folderRunners, cfg.ID)
  360. delete(m.folderRunnerTokens, cfg.ID)
  361. }
  362. func (m *model) RestartFolder(from, to config.FolderConfiguration) {
  363. if len(to.ID) == 0 {
  364. panic("bug: cannot restart empty folder ID")
  365. }
  366. if to.ID != from.ID {
  367. panic(fmt.Sprintf("bug: folder restart cannot change ID %q -> %q", from.ID, to.ID))
  368. }
  369. // This mutex protects the entirety of the restart operation, preventing
  370. // there from being more than one folder restart operation in progress
  371. // at any given time. The usual fmut/pmut stuff doesn't cover this,
  372. // because those locks are released while we are waiting for the folder
  373. // to shut down (and must be so because the folder might need them as
  374. // part of its operations before shutting down).
  375. restartMut := m.folderRestartMuts.Get(to.ID)
  376. restartMut.Lock()
  377. defer restartMut.Unlock()
  378. var infoMsg string
  379. var errMsg string
  380. switch {
  381. case to.Paused:
  382. infoMsg = "Paused"
  383. errMsg = "pausing"
  384. case from.Paused:
  385. infoMsg = "Unpaused"
  386. errMsg = "unpausing"
  387. default:
  388. infoMsg = "Restarted"
  389. errMsg = "restarting"
  390. }
  391. m.fmut.Lock()
  392. defer m.fmut.Unlock()
  393. m.tearDownFolderLocked(from, fmt.Errorf("%v folder %v", errMsg, to.Description()))
  394. if !to.Paused {
  395. m.addFolderLocked(to)
  396. m.startFolderLocked(to)
  397. }
  398. l.Infof("%v folder %v (%v)", infoMsg, to.Description(), to.Type)
  399. }
  400. func (m *model) UsageReportingStats(version int, preview bool) map[string]interface{} {
  401. stats := make(map[string]interface{})
  402. if version >= 3 {
  403. // Block stats
  404. blockStatsMut.Lock()
  405. copyBlockStats := make(map[string]int)
  406. for k, v := range blockStats {
  407. copyBlockStats[k] = v
  408. if !preview {
  409. blockStats[k] = 0
  410. }
  411. }
  412. blockStatsMut.Unlock()
  413. stats["blockStats"] = copyBlockStats
  414. // Transport stats
  415. m.pmut.RLock()
  416. transportStats := make(map[string]int)
  417. for _, conn := range m.conn {
  418. transportStats[conn.Transport()]++
  419. }
  420. m.pmut.RUnlock()
  421. stats["transportStats"] = transportStats
  422. // Ignore stats
  423. ignoreStats := map[string]int{
  424. "lines": 0,
  425. "inverts": 0,
  426. "folded": 0,
  427. "deletable": 0,
  428. "rooted": 0,
  429. "includes": 0,
  430. "escapedIncludes": 0,
  431. "doubleStars": 0,
  432. "stars": 0,
  433. }
  434. var seenPrefix [3]bool
  435. for folder := range m.cfg.Folders() {
  436. lines, _, err := m.GetIgnores(folder)
  437. if err != nil {
  438. continue
  439. }
  440. ignoreStats["lines"] += len(lines)
  441. for _, line := range lines {
  442. // Allow prefixes to be specified in any order, but only once.
  443. for {
  444. if strings.HasPrefix(line, "!") && !seenPrefix[0] {
  445. seenPrefix[0] = true
  446. line = line[1:]
  447. ignoreStats["inverts"] += 1
  448. } else if strings.HasPrefix(line, "(?i)") && !seenPrefix[1] {
  449. seenPrefix[1] = true
  450. line = line[4:]
  451. ignoreStats["folded"] += 1
  452. } else if strings.HasPrefix(line, "(?d)") && !seenPrefix[2] {
  453. seenPrefix[2] = true
  454. line = line[4:]
  455. ignoreStats["deletable"] += 1
  456. } else {
  457. seenPrefix[0] = false
  458. seenPrefix[1] = false
  459. seenPrefix[2] = false
  460. break
  461. }
  462. }
  463. // Noops, remove
  464. line = strings.TrimSuffix(line, "**")
  465. line = strings.TrimPrefix(line, "**/")
  466. if strings.HasPrefix(line, "/") {
  467. ignoreStats["rooted"] += 1
  468. } else if strings.HasPrefix(line, "#include ") {
  469. ignoreStats["includes"] += 1
  470. if strings.Contains(line, "..") {
  471. ignoreStats["escapedIncludes"] += 1
  472. }
  473. }
  474. if strings.Contains(line, "**") {
  475. ignoreStats["doubleStars"] += 1
  476. // Remove not to trip up star checks.
  477. line = strings.Replace(line, "**", "", -1)
  478. }
  479. if strings.Contains(line, "*") {
  480. ignoreStats["stars"] += 1
  481. }
  482. }
  483. }
  484. stats["ignoreStats"] = ignoreStats
  485. }
  486. return stats
  487. }
  488. type ConnectionInfo struct {
  489. protocol.Statistics
  490. Connected bool
  491. Paused bool
  492. Address string
  493. ClientVersion string
  494. Type string
  495. Crypto string
  496. }
  497. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  498. return json.Marshal(map[string]interface{}{
  499. "at": info.At,
  500. "inBytesTotal": info.InBytesTotal,
  501. "outBytesTotal": info.OutBytesTotal,
  502. "connected": info.Connected,
  503. "paused": info.Paused,
  504. "address": info.Address,
  505. "clientVersion": info.ClientVersion,
  506. "type": info.Type,
  507. "crypto": info.Crypto,
  508. })
  509. }
  510. // ConnectionStats returns a map with connection statistics for each device.
  511. func (m *model) ConnectionStats() map[string]interface{} {
  512. m.fmut.RLock()
  513. m.pmut.RLock()
  514. defer m.pmut.RUnlock()
  515. defer m.fmut.RUnlock()
  516. res := make(map[string]interface{})
  517. devs := m.cfg.Devices()
  518. conns := make(map[string]ConnectionInfo, len(devs))
  519. for device, deviceCfg := range devs {
  520. hello := m.helloMessages[device]
  521. versionString := hello.ClientVersion
  522. if hello.ClientName != "syncthing" {
  523. versionString = hello.ClientName + " " + hello.ClientVersion
  524. }
  525. ci := ConnectionInfo{
  526. ClientVersion: strings.TrimSpace(versionString),
  527. Paused: deviceCfg.Paused,
  528. }
  529. if conn, ok := m.conn[device]; ok {
  530. ci.Type = conn.Type()
  531. ci.Crypto = conn.Crypto()
  532. ci.Connected = ok
  533. ci.Statistics = conn.Statistics()
  534. if addr := conn.RemoteAddr(); addr != nil {
  535. ci.Address = addr.String()
  536. }
  537. }
  538. conns[device.String()] = ci
  539. }
  540. res["connections"] = conns
  541. in, out := protocol.TotalInOut()
  542. res["total"] = ConnectionInfo{
  543. Statistics: protocol.Statistics{
  544. At: time.Now(),
  545. InBytesTotal: in,
  546. OutBytesTotal: out,
  547. },
  548. }
  549. return res
  550. }
  551. // DeviceStatistics returns statistics about each device
  552. func (m *model) DeviceStatistics() map[string]stats.DeviceStatistics {
  553. res := make(map[string]stats.DeviceStatistics)
  554. for id := range m.cfg.Devices() {
  555. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  556. }
  557. return res
  558. }
  559. // FolderStatistics returns statistics about each folder
  560. func (m *model) FolderStatistics() map[string]stats.FolderStatistics {
  561. res := make(map[string]stats.FolderStatistics)
  562. m.fmut.RLock()
  563. defer m.fmut.RUnlock()
  564. for id, runner := range m.folderRunners {
  565. res[id] = runner.GetStatistics()
  566. }
  567. return res
  568. }
  569. type FolderCompletion struct {
  570. CompletionPct float64
  571. NeedBytes int64
  572. NeedItems int64
  573. GlobalBytes int64
  574. NeedDeletes int64
  575. }
  576. // Map returns the members as a map, e.g. used in api to serialize as Json.
  577. func (comp FolderCompletion) Map() map[string]interface{} {
  578. return map[string]interface{}{
  579. "completion": comp.CompletionPct,
  580. "needBytes": comp.NeedBytes,
  581. "needItems": comp.NeedItems,
  582. "globalBytes": comp.GlobalBytes,
  583. "needDeletes": comp.NeedDeletes,
  584. }
  585. }
  586. // Completion returns the completion status, in percent, for the given device
  587. // and folder.
  588. func (m *model) Completion(device protocol.DeviceID, folder string) FolderCompletion {
  589. m.fmut.RLock()
  590. rf, ok := m.folderFiles[folder]
  591. m.fmut.RUnlock()
  592. if !ok {
  593. return FolderCompletion{} // Folder doesn't exist, so we hardly have any of it
  594. }
  595. tot := rf.GlobalSize().Bytes
  596. if tot == 0 {
  597. // Folder is empty, so we have all of it
  598. return FolderCompletion{
  599. CompletionPct: 100,
  600. }
  601. }
  602. m.pmut.RLock()
  603. counts := m.deviceDownloads[device].GetBlockCounts(folder)
  604. m.pmut.RUnlock()
  605. var need, items, fileNeed, downloaded, deletes int64
  606. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  607. ft := f.(db.FileInfoTruncated)
  608. // If the file is deleted, we account it only in the deleted column.
  609. if ft.Deleted {
  610. deletes++
  611. return true
  612. }
  613. // This might might be more than it really is, because some blocks can be of a smaller size.
  614. downloaded = int64(counts[ft.Name] * int(ft.BlockSize()))
  615. fileNeed = ft.FileSize() - downloaded
  616. if fileNeed < 0 {
  617. fileNeed = 0
  618. }
  619. need += fileNeed
  620. items++
  621. return true
  622. })
  623. needRatio := float64(need) / float64(tot)
  624. completionPct := 100 * (1 - needRatio)
  625. // If the completion is 100% but there are deletes we need to handle,
  626. // drop it down a notch. Hack for consumers that look only at the
  627. // percentage (our own GUI does the same calculation as here on its own
  628. // and needs the same fixup).
  629. if need == 0 && deletes > 0 {
  630. completionPct = 95 // chosen by fair dice roll
  631. }
  632. l.Debugf("%v Completion(%s, %q): %f (%d / %d = %f)", m, device, folder, completionPct, need, tot, needRatio)
  633. return FolderCompletion{
  634. CompletionPct: completionPct,
  635. NeedBytes: need,
  636. NeedItems: items,
  637. GlobalBytes: tot,
  638. NeedDeletes: deletes,
  639. }
  640. }
  641. func addSizeOfFile(s *db.Counts, f db.FileIntf) {
  642. switch {
  643. case f.IsDeleted():
  644. s.Deleted++
  645. case f.IsDirectory():
  646. s.Directories++
  647. case f.IsSymlink():
  648. s.Symlinks++
  649. default:
  650. s.Files++
  651. }
  652. s.Bytes += f.FileSize()
  653. }
  654. // GlobalSize returns the number of files, deleted files and total bytes for all
  655. // files in the global model.
  656. func (m *model) GlobalSize(folder string) db.Counts {
  657. m.fmut.RLock()
  658. defer m.fmut.RUnlock()
  659. if rf, ok := m.folderFiles[folder]; ok {
  660. return rf.GlobalSize()
  661. }
  662. return db.Counts{}
  663. }
  664. // LocalSize returns the number of files, deleted files and total bytes for all
  665. // files in the local folder.
  666. func (m *model) LocalSize(folder string) db.Counts {
  667. m.fmut.RLock()
  668. defer m.fmut.RUnlock()
  669. if rf, ok := m.folderFiles[folder]; ok {
  670. return rf.LocalSize()
  671. }
  672. return db.Counts{}
  673. }
  674. // ReceiveOnlyChangedSize returns the number of files, deleted files and
  675. // total bytes for all files that have changed locally in a receieve only
  676. // folder.
  677. func (m *model) ReceiveOnlyChangedSize(folder string) db.Counts {
  678. m.fmut.RLock()
  679. defer m.fmut.RUnlock()
  680. if rf, ok := m.folderFiles[folder]; ok {
  681. return rf.ReceiveOnlyChangedSize()
  682. }
  683. return db.Counts{}
  684. }
  685. // NeedSize returns the number and total size of currently needed files.
  686. func (m *model) NeedSize(folder string) db.Counts {
  687. m.fmut.RLock()
  688. rf, ok := m.folderFiles[folder]
  689. cfg := m.folderCfgs[folder]
  690. m.fmut.RUnlock()
  691. var result db.Counts
  692. if ok {
  693. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  694. if cfg.IgnoreDelete && f.IsDeleted() {
  695. return true
  696. }
  697. addSizeOfFile(&result, f)
  698. return true
  699. })
  700. }
  701. result.Bytes -= m.progressEmitter.BytesCompleted(folder)
  702. l.Debugf("%v NeedSize(%q): %v", m, folder, result)
  703. return result
  704. }
  705. // NeedFolderFiles returns paginated list of currently needed files in
  706. // progress, queued, and to be queued on next puller iteration, as well as the
  707. // total number of files currently needed.
  708. func (m *model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated) {
  709. m.fmut.RLock()
  710. rf, rfOk := m.folderFiles[folder]
  711. runner, runnerOk := m.folderRunners[folder]
  712. cfg := m.folderCfgs[folder]
  713. m.fmut.RUnlock()
  714. if !rfOk {
  715. return nil, nil, nil
  716. }
  717. var progress, queued, rest []db.FileInfoTruncated
  718. var seen map[string]struct{}
  719. skip := (page - 1) * perpage
  720. get := perpage
  721. if runnerOk {
  722. allProgressNames, allQueuedNames := runner.Jobs()
  723. var progressNames, queuedNames []string
  724. progressNames, skip, get = getChunk(allProgressNames, skip, get)
  725. queuedNames, skip, get = getChunk(allQueuedNames, skip, get)
  726. progress = make([]db.FileInfoTruncated, len(progressNames))
  727. queued = make([]db.FileInfoTruncated, len(queuedNames))
  728. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  729. for i, name := range progressNames {
  730. if f, ok := rf.GetGlobalTruncated(name); ok {
  731. progress[i] = f
  732. seen[name] = struct{}{}
  733. }
  734. }
  735. for i, name := range queuedNames {
  736. if f, ok := rf.GetGlobalTruncated(name); ok {
  737. queued[i] = f
  738. seen[name] = struct{}{}
  739. }
  740. }
  741. }
  742. rest = make([]db.FileInfoTruncated, 0, perpage)
  743. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  744. if cfg.IgnoreDelete && f.IsDeleted() {
  745. return true
  746. }
  747. if skip > 0 {
  748. skip--
  749. return true
  750. }
  751. ft := f.(db.FileInfoTruncated)
  752. if _, ok := seen[ft.Name]; !ok {
  753. rest = append(rest, ft)
  754. get--
  755. }
  756. return get > 0
  757. })
  758. return progress, queued, rest
  759. }
  760. // LocalChangedFiles returns a paginated list of currently needed files in
  761. // progress, queued, and to be queued on next puller iteration, as well as the
  762. // total number of files currently needed.
  763. func (m *model) LocalChangedFiles(folder string, page, perpage int) []db.FileInfoTruncated {
  764. m.fmut.RLock()
  765. rf, ok := m.folderFiles[folder]
  766. fcfg := m.folderCfgs[folder]
  767. m.fmut.RUnlock()
  768. if !ok {
  769. return nil
  770. }
  771. if fcfg.Type != config.FolderTypeReceiveOnly {
  772. return nil
  773. }
  774. if rf.ReceiveOnlyChangedSize().TotalItems() == 0 {
  775. return nil
  776. }
  777. files := make([]db.FileInfoTruncated, 0, perpage)
  778. skip := (page - 1) * perpage
  779. get := perpage
  780. rf.WithHaveTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  781. if !f.IsReceiveOnlyChanged() {
  782. return true
  783. }
  784. if skip > 0 {
  785. skip--
  786. return true
  787. }
  788. ft := f.(db.FileInfoTruncated)
  789. files = append(files, ft)
  790. get--
  791. return get > 0
  792. })
  793. return files
  794. }
  795. // RemoteNeedFolderFiles returns paginated list of currently needed files in
  796. // progress, queued, and to be queued on next puller iteration, as well as the
  797. // total number of files currently needed.
  798. func (m *model) RemoteNeedFolderFiles(device protocol.DeviceID, folder string, page, perpage int) ([]db.FileInfoTruncated, error) {
  799. m.fmut.RLock()
  800. m.pmut.RLock()
  801. err := m.checkDeviceFolderConnectedLocked(device, folder)
  802. rf := m.folderFiles[folder]
  803. m.pmut.RUnlock()
  804. m.fmut.RUnlock()
  805. if err != nil {
  806. return nil, err
  807. }
  808. files := make([]db.FileInfoTruncated, 0, perpage)
  809. skip := (page - 1) * perpage
  810. get := perpage
  811. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  812. if skip > 0 {
  813. skip--
  814. return true
  815. }
  816. files = append(files, f.(db.FileInfoTruncated))
  817. get--
  818. return get > 0
  819. })
  820. return files, nil
  821. }
  822. // Index is called when a new device is connected and we receive their full index.
  823. // Implements the protocol.Model interface.
  824. func (m *model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  825. m.handleIndex(deviceID, folder, fs, false)
  826. }
  827. // IndexUpdate is called for incremental updates to connected devices' indexes.
  828. // Implements the protocol.Model interface.
  829. func (m *model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  830. m.handleIndex(deviceID, folder, fs, true)
  831. }
  832. func (m *model) handleIndex(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo, update bool) {
  833. op := "Index"
  834. if update {
  835. op += " update"
  836. }
  837. l.Debugf("%v (in): %s / %q: %d files", op, deviceID, folder, len(fs))
  838. if cfg, ok := m.cfg.Folder(folder); !ok || !cfg.SharedWith(deviceID) {
  839. l.Infof("%v for unexpected folder ID %q sent from device %q; ensure that the folder exists and that this device is selected under \"Share With\" in the folder configuration.", op, folder, deviceID)
  840. return
  841. } else if cfg.Paused {
  842. l.Debugf("%v for paused folder (ID %q) sent from device %q.", op, folder, deviceID)
  843. return
  844. }
  845. m.fmut.RLock()
  846. files, existing := m.folderFiles[folder]
  847. runner, running := m.folderRunners[folder]
  848. m.fmut.RUnlock()
  849. if !existing {
  850. panic(fmt.Sprintf("%v for nonexistent folder %q", op, folder))
  851. }
  852. if running {
  853. defer runner.SchedulePull()
  854. } else if update {
  855. // Runner may legitimately not be set if this is the "cleanup" Index
  856. // message at startup.
  857. panic(fmt.Sprintf("%v for not running folder %q", op, folder))
  858. }
  859. m.pmut.RLock()
  860. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  861. m.pmut.RUnlock()
  862. if !update {
  863. files.Drop(deviceID)
  864. }
  865. for i := range fs {
  866. // The local flags should never be transmitted over the wire. Make
  867. // sure they look like they weren't.
  868. fs[i].LocalFlags = 0
  869. }
  870. files.Update(deviceID, fs)
  871. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  872. "device": deviceID.String(),
  873. "folder": folder,
  874. "items": len(fs),
  875. "version": files.Sequence(deviceID),
  876. })
  877. }
  878. func (m *model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfig) {
  879. // Check the peer device's announced folders against our own. Emits events
  880. // for folders that we don't expect (unknown or not shared).
  881. // Also, collect a list of folders we do share, and if he's interested in
  882. // temporary indexes, subscribe the connection.
  883. tempIndexFolders := make([]string, 0, len(cm.Folders))
  884. m.pmut.RLock()
  885. conn, ok := m.conn[deviceID]
  886. closed := m.closed[deviceID]
  887. hello := m.helloMessages[deviceID]
  888. m.pmut.RUnlock()
  889. if !ok {
  890. panic("bug: ClusterConfig called on closed or nonexistent connection")
  891. }
  892. changed := false
  893. deviceCfg := m.cfg.Devices()[deviceID]
  894. // See issue #3802 - in short, we can't send modern symlink entries to older
  895. // clients.
  896. dropSymlinks := false
  897. if hello.ClientName == m.clientName && upgrade.CompareVersions(hello.ClientVersion, "v0.14.14") < 0 {
  898. l.Warnln("Not sending symlinks to old client", deviceID, "- please upgrade to v0.14.14 or newer")
  899. dropSymlinks = true
  900. }
  901. // Needs to happen outside of the fmut, as can cause CommitConfiguration
  902. if deviceCfg.AutoAcceptFolders {
  903. for _, folder := range cm.Folders {
  904. changed = m.handleAutoAccepts(deviceCfg, folder) || changed
  905. }
  906. }
  907. m.fmut.Lock()
  908. defer m.fmut.Unlock()
  909. var paused []string
  910. for _, folder := range cm.Folders {
  911. cfg, ok := m.cfg.Folder(folder.ID)
  912. if !ok || !cfg.SharedWith(deviceID) {
  913. if deviceCfg.IgnoredFolder(folder.ID) {
  914. l.Infof("Ignoring folder %s from device %s since we are configured to", folder.Description(), deviceID)
  915. continue
  916. }
  917. m.cfg.AddOrUpdatePendingFolder(folder.ID, folder.Label, deviceID)
  918. events.Default.Log(events.FolderRejected, map[string]string{
  919. "folder": folder.ID,
  920. "folderLabel": folder.Label,
  921. "device": deviceID.String(),
  922. })
  923. l.Infof("Unexpected folder %s sent from device %q; ensure that the folder exists and that this device is selected under \"Share With\" in the folder configuration.", folder.Description(), deviceID)
  924. continue
  925. }
  926. if folder.Paused {
  927. paused = append(paused, folder.ID)
  928. continue
  929. }
  930. if cfg.Paused {
  931. continue
  932. }
  933. fs, ok := m.folderFiles[folder.ID]
  934. if !ok {
  935. // Shouldn't happen because !cfg.Paused, but might happen
  936. // if the folder is about to be unpaused, but not yet.
  937. continue
  938. }
  939. if !folder.DisableTempIndexes {
  940. tempIndexFolders = append(tempIndexFolders, folder.ID)
  941. }
  942. myIndexID := fs.IndexID(protocol.LocalDeviceID)
  943. mySequence := fs.Sequence(protocol.LocalDeviceID)
  944. var startSequence int64
  945. for _, dev := range folder.Devices {
  946. if dev.ID == m.id {
  947. // This is the other side's description of what it knows
  948. // about us. Lets check to see if we can start sending index
  949. // updates directly or need to send the index from start...
  950. if dev.IndexID == myIndexID {
  951. // They say they've seen our index ID before, so we can
  952. // send a delta update only.
  953. if dev.MaxSequence > mySequence {
  954. // Safety check. They claim to have more or newer
  955. // index data than we have - either we have lost
  956. // index data, or reset the index without resetting
  957. // the IndexID, or something else weird has
  958. // happened. We send a full index to reset the
  959. // situation.
  960. l.Infof("Device %v folder %s is delta index compatible, but seems out of sync with reality", deviceID, folder.Description())
  961. startSequence = 0
  962. continue
  963. }
  964. l.Debugf("Device %v folder %s is delta index compatible (mlv=%d)", deviceID, folder.Description(), dev.MaxSequence)
  965. startSequence = dev.MaxSequence
  966. } else if dev.IndexID != 0 {
  967. // They say they've seen an index ID from us, but it's
  968. // not the right one. Either they are confused or we
  969. // must have reset our database since last talking to
  970. // them. We'll start with a full index transfer.
  971. l.Infof("Device %v folder %s has mismatching index ID for us (%v != %v)", deviceID, folder.Description(), dev.IndexID, myIndexID)
  972. startSequence = 0
  973. }
  974. } else if dev.ID == deviceID {
  975. // This is the other side's description of themselves. We
  976. // check to see that it matches the IndexID we have on file,
  977. // otherwise we drop our old index data and expect to get a
  978. // completely new set.
  979. theirIndexID := fs.IndexID(deviceID)
  980. if dev.IndexID == 0 {
  981. // They're not announcing an index ID. This means they
  982. // do not support delta indexes and we should clear any
  983. // information we have from them before accepting their
  984. // index, which will presumably be a full index.
  985. fs.Drop(deviceID)
  986. } else if dev.IndexID != theirIndexID {
  987. // The index ID we have on file is not what they're
  988. // announcing. They must have reset their database and
  989. // will probably send us a full index. We drop any
  990. // information we have and remember this new index ID
  991. // instead.
  992. l.Infof("Device %v folder %s has a new index ID (%v)", deviceID, folder.Description(), dev.IndexID)
  993. fs.Drop(deviceID)
  994. fs.SetIndexID(deviceID, dev.IndexID)
  995. } else {
  996. // They're sending a recognized index ID and will most
  997. // likely use delta indexes. We might already have files
  998. // that we need to pull so let the folder runner know
  999. // that it should recheck the index data.
  1000. if runner := m.folderRunners[folder.ID]; runner != nil {
  1001. defer runner.SchedulePull()
  1002. }
  1003. }
  1004. }
  1005. }
  1006. // The token isn't tracked as the service stops when the connection
  1007. // terminates and is automatically removed from supervisor (by
  1008. // implementing suture.IsCompletable).
  1009. m.Add(&indexSender{
  1010. conn: conn,
  1011. connClosed: closed,
  1012. folder: folder.ID,
  1013. fset: fs,
  1014. prevSequence: startSequence,
  1015. dropSymlinks: dropSymlinks,
  1016. stop: make(chan struct{}),
  1017. stopped: make(chan struct{}),
  1018. })
  1019. }
  1020. m.pmut.Lock()
  1021. m.remotePausedFolders[deviceID] = paused
  1022. m.pmut.Unlock()
  1023. // This breaks if we send multiple CM messages during the same connection.
  1024. if len(tempIndexFolders) > 0 {
  1025. m.pmut.RLock()
  1026. conn, ok := m.conn[deviceID]
  1027. m.pmut.RUnlock()
  1028. // In case we've got ClusterConfig, and the connection disappeared
  1029. // from infront of our nose.
  1030. if ok {
  1031. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  1032. }
  1033. }
  1034. if deviceCfg.Introducer {
  1035. foldersDevices, introduced := m.handleIntroductions(deviceCfg, cm)
  1036. if introduced {
  1037. changed = true
  1038. }
  1039. // If permitted, check if the introducer has unshare devices/folders with
  1040. // some of the devices/folders that we know were introduced to us by him.
  1041. if !deviceCfg.SkipIntroductionRemovals && m.handleDeintroductions(deviceCfg, cm, foldersDevices) {
  1042. changed = true
  1043. }
  1044. }
  1045. if changed {
  1046. if err := m.cfg.Save(); err != nil {
  1047. l.Warnln("Failed to save config", err)
  1048. }
  1049. }
  1050. }
  1051. // handleIntroductions handles adding devices/shares that are shared by an introducer device
  1052. func (m *model) handleIntroductions(introducerCfg config.DeviceConfiguration, cm protocol.ClusterConfig) (folderDeviceSet, bool) {
  1053. // This device is an introducer. Go through the announced lists of folders
  1054. // and devices and add what we are missing, remove what we have extra that
  1055. // has been introducer by the introducer.
  1056. changed := false
  1057. foldersDevices := make(folderDeviceSet)
  1058. for _, folder := range cm.Folders {
  1059. // Adds devices which we do not have, but the introducer has
  1060. // for the folders that we have in common. Also, shares folders
  1061. // with devices that we have in common, yet are currently not sharing
  1062. // the folder.
  1063. fcfg, ok := m.cfg.Folder(folder.ID)
  1064. if !ok {
  1065. // Don't have this folder, carry on.
  1066. continue
  1067. }
  1068. for _, device := range folder.Devices {
  1069. // No need to share with self.
  1070. if device.ID == m.id {
  1071. continue
  1072. }
  1073. foldersDevices.set(device.ID, folder.ID)
  1074. if _, ok := m.cfg.Devices()[device.ID]; !ok {
  1075. // The device is currently unknown. Add it to the config.
  1076. m.introduceDevice(device, introducerCfg)
  1077. } else if fcfg.SharedWith(device.ID) {
  1078. // We already share the folder with this device, so
  1079. // nothing to do.
  1080. continue
  1081. }
  1082. // We don't yet share this folder with this device. Add the device
  1083. // to sharing list of the folder.
  1084. l.Infof("Sharing folder %s with %v (vouched for by introducer %v)", folder.Description(), device.ID, introducerCfg.DeviceID)
  1085. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1086. DeviceID: device.ID,
  1087. IntroducedBy: introducerCfg.DeviceID,
  1088. })
  1089. changed = true
  1090. }
  1091. if changed {
  1092. m.cfg.SetFolder(fcfg)
  1093. }
  1094. }
  1095. return foldersDevices, changed
  1096. }
  1097. // handleDeintroductions handles removals of devices/shares that are removed by an introducer device
  1098. func (m *model) handleDeintroductions(introducerCfg config.DeviceConfiguration, cm protocol.ClusterConfig, foldersDevices folderDeviceSet) bool {
  1099. changed := false
  1100. devicesNotIntroduced := make(map[protocol.DeviceID]struct{})
  1101. folders := m.cfg.FolderList()
  1102. // Check if we should unshare some folders, if the introducer has unshared them.
  1103. for i := range folders {
  1104. for k := 0; k < len(folders[i].Devices); k++ {
  1105. if folders[i].Devices[k].IntroducedBy != introducerCfg.DeviceID {
  1106. devicesNotIntroduced[folders[i].Devices[k].DeviceID] = struct{}{}
  1107. continue
  1108. }
  1109. if !foldersDevices.has(folders[i].Devices[k].DeviceID, folders[i].ID) {
  1110. // We could not find that folder shared on the
  1111. // introducer with the device that was introduced to us.
  1112. // We should follow and unshare as well.
  1113. l.Infof("Unsharing folder %s with %v as introducer %v no longer shares the folder with that device", folders[i].Description(), folders[i].Devices[k].DeviceID, folders[i].Devices[k].IntroducedBy)
  1114. folders[i].Devices = append(folders[i].Devices[:k], folders[i].Devices[k+1:]...)
  1115. k--
  1116. changed = true
  1117. }
  1118. }
  1119. }
  1120. // Check if we should remove some devices, if the introducer no longer
  1121. // shares any folder with them. Yet do not remove if we share other
  1122. // folders that haven't been introduced by the introducer.
  1123. devMap := m.cfg.Devices()
  1124. devices := make([]config.DeviceConfiguration, 0, len(devMap))
  1125. for deviceID, device := range devMap {
  1126. if device.IntroducedBy == introducerCfg.DeviceID {
  1127. if !foldersDevices.hasDevice(deviceID) {
  1128. if _, ok := devicesNotIntroduced[deviceID]; !ok {
  1129. // The introducer no longer shares any folder with the
  1130. // device, remove the device.
  1131. l.Infof("Removing device %v as introducer %v no longer shares any folders with that device", deviceID, device.IntroducedBy)
  1132. changed = true
  1133. continue
  1134. }
  1135. l.Infof("Would have removed %v as %v no longer shares any folders, yet there are other folders that are shared with this device that haven't been introduced by this introducer.", deviceID, device.IntroducedBy)
  1136. }
  1137. }
  1138. devices = append(devices, device)
  1139. }
  1140. if changed {
  1141. cfg := m.cfg.RawCopy()
  1142. cfg.Folders = folders
  1143. cfg.Devices = devices
  1144. m.cfg.Replace(cfg)
  1145. }
  1146. return changed
  1147. }
  1148. // handleAutoAccepts handles adding and sharing folders for devices that have
  1149. // AutoAcceptFolders set to true.
  1150. func (m *model) handleAutoAccepts(deviceCfg config.DeviceConfiguration, folder protocol.Folder) bool {
  1151. if cfg, ok := m.cfg.Folder(folder.ID); !ok {
  1152. defaultPath := m.cfg.Options().DefaultFolderPath
  1153. defaultPathFs := fs.NewFilesystem(fs.FilesystemTypeBasic, defaultPath)
  1154. pathAlternatives := []string{
  1155. sanitizePath(folder.Label),
  1156. sanitizePath(folder.ID),
  1157. }
  1158. for _, path := range pathAlternatives {
  1159. if _, err := defaultPathFs.Lstat(path); !fs.IsNotExist(err) {
  1160. continue
  1161. }
  1162. fcfg := config.NewFolderConfiguration(m.id, folder.ID, folder.Label, fs.FilesystemTypeBasic, filepath.Join(defaultPath, path))
  1163. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1164. DeviceID: deviceCfg.DeviceID,
  1165. })
  1166. // Need to wait for the waiter, as this calls CommitConfiguration,
  1167. // which sets up the folder and as we return from this call,
  1168. // ClusterConfig starts poking at m.folderFiles and other things
  1169. // that might not exist until the config is committed.
  1170. w, _ := m.cfg.SetFolder(fcfg)
  1171. w.Wait()
  1172. l.Infof("Auto-accepted %s folder %s at path %s", deviceCfg.DeviceID, folder.Description(), fcfg.Path)
  1173. return true
  1174. }
  1175. l.Infof("Failed to auto-accept folder %s from %s due to path conflict", folder.Description(), deviceCfg.DeviceID)
  1176. return false
  1177. } else {
  1178. for _, device := range cfg.DeviceIDs() {
  1179. if device == deviceCfg.DeviceID {
  1180. // Already shared nothing todo.
  1181. return false
  1182. }
  1183. }
  1184. cfg.Devices = append(cfg.Devices, config.FolderDeviceConfiguration{
  1185. DeviceID: deviceCfg.DeviceID,
  1186. })
  1187. w, _ := m.cfg.SetFolder(cfg)
  1188. w.Wait()
  1189. l.Infof("Shared %s with %s due to auto-accept", folder.ID, deviceCfg.DeviceID)
  1190. return true
  1191. }
  1192. }
  1193. func (m *model) introduceDevice(device protocol.Device, introducerCfg config.DeviceConfiguration) {
  1194. addresses := []string{"dynamic"}
  1195. for _, addr := range device.Addresses {
  1196. if addr != "dynamic" {
  1197. addresses = append(addresses, addr)
  1198. }
  1199. }
  1200. l.Infof("Adding device %v to config (vouched for by introducer %v)", device.ID, introducerCfg.DeviceID)
  1201. newDeviceCfg := config.DeviceConfiguration{
  1202. DeviceID: device.ID,
  1203. Name: device.Name,
  1204. Compression: introducerCfg.Compression,
  1205. Addresses: addresses,
  1206. CertName: device.CertName,
  1207. IntroducedBy: introducerCfg.DeviceID,
  1208. }
  1209. // The introducers' introducers are also our introducers.
  1210. if device.Introducer {
  1211. l.Infof("Device %v is now also an introducer", device.ID)
  1212. newDeviceCfg.Introducer = true
  1213. newDeviceCfg.SkipIntroductionRemovals = device.SkipIntroductionRemovals
  1214. }
  1215. m.cfg.SetDevice(newDeviceCfg)
  1216. }
  1217. // Closed is called when a connection has been closed
  1218. func (m *model) Closed(conn protocol.Connection, err error) {
  1219. device := conn.ID()
  1220. m.pmut.Lock()
  1221. defer m.pmut.Unlock()
  1222. conn, ok := m.conn[device]
  1223. if !ok {
  1224. return
  1225. }
  1226. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  1227. delete(m.conn, device)
  1228. delete(m.connRequestLimiters, device)
  1229. delete(m.helloMessages, device)
  1230. delete(m.deviceDownloads, device)
  1231. delete(m.remotePausedFolders, device)
  1232. closed := m.closed[device]
  1233. delete(m.closed, device)
  1234. l.Infof("Connection to %s at %s closed: %v", device, conn.Name(), err)
  1235. events.Default.Log(events.DeviceDisconnected, map[string]string{
  1236. "id": device.String(),
  1237. "error": err.Error(),
  1238. })
  1239. close(closed)
  1240. }
  1241. // closeConns will close the underlying connection for given devices
  1242. func (m *model) closeConns(devs []protocol.DeviceID, err error) {
  1243. conns := make([]connections.Connection, 0, len(devs))
  1244. m.pmut.Lock()
  1245. for _, dev := range devs {
  1246. if conn, ok := m.conn[dev]; ok {
  1247. conns = append(conns, conn)
  1248. }
  1249. }
  1250. m.pmut.Unlock()
  1251. for _, conn := range conns {
  1252. conn.Close(err)
  1253. }
  1254. }
  1255. func (m *model) closeConn(dev protocol.DeviceID, err error) {
  1256. m.closeConns([]protocol.DeviceID{dev}, err)
  1257. }
  1258. // Implements protocol.RequestResponse
  1259. type requestResponse struct {
  1260. data []byte
  1261. closed chan struct{}
  1262. once stdsync.Once
  1263. }
  1264. func newRequestResponse(size int) *requestResponse {
  1265. return &requestResponse{
  1266. data: protocol.BufferPool.Get(size),
  1267. closed: make(chan struct{}),
  1268. }
  1269. }
  1270. func (r *requestResponse) Data() []byte {
  1271. return r.data
  1272. }
  1273. func (r *requestResponse) Close() {
  1274. r.once.Do(func() {
  1275. protocol.BufferPool.Put(r.data)
  1276. close(r.closed)
  1277. })
  1278. }
  1279. func (r *requestResponse) Wait() {
  1280. <-r.closed
  1281. }
  1282. // Request returns the specified data segment by reading it from local disk.
  1283. // Implements the protocol.Model interface.
  1284. func (m *model) Request(deviceID protocol.DeviceID, folder, name string, size int32, offset int64, hash []byte, weakHash uint32, fromTemporary bool) (out protocol.RequestResponse, err error) {
  1285. if size < 0 || offset < 0 {
  1286. return nil, protocol.ErrInvalid
  1287. }
  1288. m.fmut.RLock()
  1289. folderCfg, ok := m.folderCfgs[folder]
  1290. folderIgnores := m.folderIgnores[folder]
  1291. m.fmut.RUnlock()
  1292. if !ok {
  1293. // The folder might be already unpaused in the config, but not yet
  1294. // in the model.
  1295. l.Debugf("Request from %s for file %s in unstarted folder %q", deviceID, name, folder)
  1296. return nil, protocol.ErrGeneric
  1297. }
  1298. if !folderCfg.SharedWith(deviceID) {
  1299. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  1300. return nil, protocol.ErrGeneric
  1301. }
  1302. if folderCfg.Paused {
  1303. l.Debugf("Request from %s for file %s in paused folder %q", deviceID, name, folder)
  1304. return nil, protocol.ErrGeneric
  1305. }
  1306. // Make sure the path is valid and in canonical form
  1307. if name, err = fs.Canonicalize(name); err != nil {
  1308. l.Debugf("Request from %s in folder %q for invalid filename %s", deviceID, folder, name)
  1309. return nil, protocol.ErrGeneric
  1310. }
  1311. if deviceID != protocol.LocalDeviceID {
  1312. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, size, fromTemporary)
  1313. }
  1314. if fs.IsInternal(name) {
  1315. l.Debugf("%v REQ(in) for internal file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  1316. return nil, protocol.ErrInvalid
  1317. }
  1318. if folderIgnores.Match(name).IsIgnored() {
  1319. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  1320. return nil, protocol.ErrInvalid
  1321. }
  1322. folderFs := folderCfg.Filesystem()
  1323. if err := osutil.TraversesSymlink(folderFs, filepath.Dir(name)); err != nil {
  1324. l.Debugf("%v REQ(in) traversal check: %s - %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1325. return nil, protocol.ErrNoSuchFile
  1326. }
  1327. // Restrict parallel requests by connection/device
  1328. m.pmut.RLock()
  1329. limiter := m.connRequestLimiters[deviceID]
  1330. m.pmut.RUnlock()
  1331. if limiter != nil {
  1332. limiter.take(int(size))
  1333. }
  1334. // The requestResponse releases the bytes to the limiter when its Close method is called.
  1335. res := newRequestResponse(int(size))
  1336. defer func() {
  1337. // Close it ourselves if it isn't returned due to an error
  1338. if err != nil {
  1339. res.Close()
  1340. }
  1341. }()
  1342. if limiter != nil {
  1343. go func() {
  1344. res.Wait()
  1345. limiter.give(int(size))
  1346. }()
  1347. }
  1348. // Only check temp files if the flag is set, and if we are set to advertise
  1349. // the temp indexes.
  1350. if fromTemporary && !folderCfg.DisableTempIndexes {
  1351. tempFn := fs.TempName(name)
  1352. if info, err := folderFs.Lstat(tempFn); err != nil || !info.IsRegular() {
  1353. // Reject reads for anything that doesn't exist or is something
  1354. // other than a regular file.
  1355. l.Debugf("%v REQ(in) failed stating temp file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1356. return nil, protocol.ErrNoSuchFile
  1357. }
  1358. err := readOffsetIntoBuf(folderFs, tempFn, offset, res.data)
  1359. if err == nil && scanner.Validate(res.data, hash, weakHash) {
  1360. return res, nil
  1361. }
  1362. // Fall through to reading from a non-temp file, just incase the temp
  1363. // file has finished downloading.
  1364. }
  1365. if info, err := folderFs.Lstat(name); err != nil || !info.IsRegular() {
  1366. // Reject reads for anything that doesn't exist or is something
  1367. // other than a regular file.
  1368. l.Debugf("%v REQ(in) failed stating file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1369. return nil, protocol.ErrNoSuchFile
  1370. }
  1371. if err := readOffsetIntoBuf(folderFs, name, offset, res.data); fs.IsNotExist(err) {
  1372. l.Debugf("%v REQ(in) file doesn't exist: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  1373. return nil, protocol.ErrNoSuchFile
  1374. } else if err != nil {
  1375. l.Debugf("%v REQ(in) failed reading file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1376. return nil, protocol.ErrGeneric
  1377. }
  1378. if !scanner.Validate(res.data, hash, weakHash) {
  1379. m.recheckFile(deviceID, folderFs, folder, name, size, offset, hash)
  1380. l.Debugf("%v REQ(in) failed validating data (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1381. return nil, protocol.ErrNoSuchFile
  1382. }
  1383. return res, nil
  1384. }
  1385. func (m *model) recheckFile(deviceID protocol.DeviceID, folderFs fs.Filesystem, folder, name string, size int32, offset int64, hash []byte) {
  1386. cf, ok := m.CurrentFolderFile(folder, name)
  1387. if !ok {
  1388. l.Debugf("%v recheckFile: %s: %q / %q: no current file", m, deviceID, folder, name)
  1389. return
  1390. }
  1391. if cf.IsDeleted() || cf.IsInvalid() || cf.IsSymlink() || cf.IsDirectory() {
  1392. l.Debugf("%v recheckFile: %s: %q / %q: not a regular file", m, deviceID, folder, name)
  1393. return
  1394. }
  1395. blockIndex := int(offset) / cf.BlockSize()
  1396. if blockIndex >= len(cf.Blocks) {
  1397. l.Debugf("%v recheckFile: %s: %q / %q i=%d: block index too far", m, deviceID, folder, name, blockIndex)
  1398. return
  1399. }
  1400. block := cf.Blocks[blockIndex]
  1401. // Seems to want a different version of the file, whatever.
  1402. if !bytes.Equal(block.Hash, hash) {
  1403. l.Debugf("%v recheckFile: %s: %q / %q i=%d: hash mismatch %x != %x", m, deviceID, folder, name, blockIndex, block.Hash, hash)
  1404. return
  1405. }
  1406. // The hashes provided part of the request match what we expect to find according
  1407. // to what we have in the database, yet the content we've read off the filesystem doesn't
  1408. // Something is fishy, invalidate the file and rescan it.
  1409. // The file will temporarily become invalid, which is ok as the content is messed up.
  1410. m.fmut.Lock()
  1411. runner, ok := m.folderRunners[folder]
  1412. m.fmut.Unlock()
  1413. if !ok {
  1414. l.Debugf("%v recheckFile: %s: %q / %q: Folder stopped before rescan could be scheduled", m, deviceID, folder, name)
  1415. return
  1416. }
  1417. if err := runner.ForceRescan(cf); err != nil {
  1418. l.Debugf("%v recheckFile: %s: %q / %q rescan: %s", m, deviceID, folder, name, err)
  1419. return
  1420. }
  1421. l.Debugf("%v recheckFile: %s: %q / %q", m, deviceID, folder, name)
  1422. }
  1423. func (m *model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  1424. m.fmut.RLock()
  1425. fs, ok := m.folderFiles[folder]
  1426. m.fmut.RUnlock()
  1427. if !ok {
  1428. return protocol.FileInfo{}, false
  1429. }
  1430. return fs.Get(protocol.LocalDeviceID, file)
  1431. }
  1432. func (m *model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  1433. m.fmut.RLock()
  1434. fs, ok := m.folderFiles[folder]
  1435. m.fmut.RUnlock()
  1436. if !ok {
  1437. return protocol.FileInfo{}, false
  1438. }
  1439. return fs.GetGlobal(file)
  1440. }
  1441. // Connection returns the current connection for device, and a boolean whether a connection was found.
  1442. func (m *model) Connection(deviceID protocol.DeviceID) (connections.Connection, bool) {
  1443. m.pmut.RLock()
  1444. cn, ok := m.conn[deviceID]
  1445. m.pmut.RUnlock()
  1446. if ok {
  1447. m.deviceWasSeen(deviceID)
  1448. }
  1449. return cn, ok
  1450. }
  1451. func (m *model) GetIgnores(folder string) ([]string, []string, error) {
  1452. m.fmut.RLock()
  1453. cfg, cfgOk := m.folderCfgs[folder]
  1454. ignores, ignoresOk := m.folderIgnores[folder]
  1455. m.fmut.RUnlock()
  1456. if !cfgOk {
  1457. cfg, cfgOk = m.cfg.Folders()[folder]
  1458. if !cfgOk {
  1459. return nil, nil, fmt.Errorf("Folder %s does not exist", folder)
  1460. }
  1461. }
  1462. // On creation a new folder with ignore patterns validly has no marker yet.
  1463. if err := cfg.CheckPath(); err != nil && err != config.ErrMarkerMissing {
  1464. return nil, nil, err
  1465. }
  1466. if !ignoresOk {
  1467. ignores = ignore.New(fs.NewFilesystem(cfg.FilesystemType, cfg.Path))
  1468. }
  1469. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  1470. return nil, nil, err
  1471. }
  1472. return ignores.Lines(), ignores.Patterns(), nil
  1473. }
  1474. func (m *model) SetIgnores(folder string, content []string) error {
  1475. cfg, ok := m.cfg.Folders()[folder]
  1476. if !ok {
  1477. return fmt.Errorf("folder %s does not exist", cfg.Description())
  1478. }
  1479. err := cfg.CheckPath()
  1480. if err == config.ErrPathMissing {
  1481. if err = cfg.CreateRoot(); err != nil {
  1482. return fmt.Errorf("failed to create folder root: %v", err)
  1483. }
  1484. err = cfg.CheckPath()
  1485. }
  1486. if err != nil && err != config.ErrMarkerMissing {
  1487. return err
  1488. }
  1489. if err := ignore.WriteIgnores(cfg.Filesystem(), ".stignore", content); err != nil {
  1490. l.Warnln("Saving .stignore:", err)
  1491. return err
  1492. }
  1493. m.fmut.RLock()
  1494. runner, ok := m.folderRunners[folder]
  1495. m.fmut.RUnlock()
  1496. if ok {
  1497. return runner.Scan(nil)
  1498. }
  1499. return nil
  1500. }
  1501. // OnHello is called when an device connects to us.
  1502. // This allows us to extract some information from the Hello message
  1503. // and add it to a list of known devices ahead of any checks.
  1504. func (m *model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloResult) error {
  1505. if m.cfg.IgnoredDevice(remoteID) {
  1506. return errDeviceIgnored
  1507. }
  1508. cfg, ok := m.cfg.Device(remoteID)
  1509. if !ok {
  1510. m.cfg.AddOrUpdatePendingDevice(remoteID, hello.DeviceName, addr.String())
  1511. events.Default.Log(events.DeviceRejected, map[string]string{
  1512. "name": hello.DeviceName,
  1513. "device": remoteID.String(),
  1514. "address": addr.String(),
  1515. })
  1516. return errDeviceUnknown
  1517. }
  1518. if cfg.Paused {
  1519. return errDevicePaused
  1520. }
  1521. if len(cfg.AllowedNetworks) > 0 {
  1522. if !connections.IsAllowedNetwork(addr.String(), cfg.AllowedNetworks) {
  1523. return errNetworkNotAllowed
  1524. }
  1525. }
  1526. return nil
  1527. }
  1528. // GetHello is called when we are about to connect to some remote device.
  1529. func (m *model) GetHello(id protocol.DeviceID) protocol.HelloIntf {
  1530. name := ""
  1531. if _, ok := m.cfg.Device(id); ok {
  1532. name = m.cfg.MyName()
  1533. }
  1534. return &protocol.Hello{
  1535. DeviceName: name,
  1536. ClientName: m.clientName,
  1537. ClientVersion: m.clientVersion,
  1538. }
  1539. }
  1540. // AddConnection adds a new peer connection to the model. An initial index will
  1541. // be sent to the connected peer, thereafter index updates whenever the local
  1542. // folder changes.
  1543. func (m *model) AddConnection(conn connections.Connection, hello protocol.HelloResult) {
  1544. deviceID := conn.ID()
  1545. device, ok := m.cfg.Device(deviceID)
  1546. if !ok {
  1547. l.Infoln("Trying to add connection to unknown device")
  1548. return
  1549. }
  1550. m.pmut.Lock()
  1551. if oldConn, ok := m.conn[deviceID]; ok {
  1552. l.Infoln("Replacing old connection", oldConn, "with", conn, "for", deviceID)
  1553. // There is an existing connection to this device that we are
  1554. // replacing. We must close the existing connection and wait for the
  1555. // close to complete before adding the new connection. We do the
  1556. // actual close without holding pmut as the connection will call
  1557. // back into Closed() for the cleanup.
  1558. closed := m.closed[deviceID]
  1559. m.pmut.Unlock()
  1560. oldConn.Close(errReplacingConnection)
  1561. <-closed
  1562. m.pmut.Lock()
  1563. }
  1564. m.conn[deviceID] = conn
  1565. m.closed[deviceID] = make(chan struct{})
  1566. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  1567. // 0: default, <0: no limiting
  1568. switch {
  1569. case device.MaxRequestKiB > 0:
  1570. m.connRequestLimiters[deviceID] = newByteSemaphore(1024 * device.MaxRequestKiB)
  1571. case device.MaxRequestKiB == 0:
  1572. m.connRequestLimiters[deviceID] = newByteSemaphore(1024 * defaultPullerPendingKiB)
  1573. }
  1574. m.helloMessages[deviceID] = hello
  1575. event := map[string]string{
  1576. "id": deviceID.String(),
  1577. "deviceName": hello.DeviceName,
  1578. "clientName": hello.ClientName,
  1579. "clientVersion": hello.ClientVersion,
  1580. "type": conn.Type(),
  1581. }
  1582. addr := conn.RemoteAddr()
  1583. if addr != nil {
  1584. event["addr"] = addr.String()
  1585. }
  1586. events.Default.Log(events.DeviceConnected, event)
  1587. l.Infof(`Device %s client is "%s %s" named "%s" at %s`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName, conn)
  1588. conn.Start()
  1589. m.pmut.Unlock()
  1590. // Acquires fmut, so has to be done outside of pmut.
  1591. cm := m.generateClusterConfig(deviceID)
  1592. conn.ClusterConfig(cm)
  1593. if (device.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) && hello.DeviceName != "" {
  1594. device.Name = hello.DeviceName
  1595. m.cfg.SetDevice(device)
  1596. m.cfg.Save()
  1597. }
  1598. m.deviceWasSeen(deviceID)
  1599. }
  1600. func (m *model) DownloadProgress(device protocol.DeviceID, folder string, updates []protocol.FileDownloadProgressUpdate) {
  1601. m.fmut.RLock()
  1602. cfg, ok := m.folderCfgs[folder]
  1603. m.fmut.RUnlock()
  1604. if !ok || cfg.DisableTempIndexes || !cfg.SharedWith(device) {
  1605. return
  1606. }
  1607. m.pmut.RLock()
  1608. m.deviceDownloads[device].Update(folder, updates)
  1609. state := m.deviceDownloads[device].GetBlockCounts(folder)
  1610. m.pmut.RUnlock()
  1611. events.Default.Log(events.RemoteDownloadProgress, map[string]interface{}{
  1612. "device": device.String(),
  1613. "folder": folder,
  1614. "state": state,
  1615. })
  1616. }
  1617. func (m *model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  1618. m.fmut.Lock()
  1619. defer m.fmut.Unlock()
  1620. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  1621. return sr
  1622. }
  1623. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  1624. m.deviceStatRefs[deviceID] = sr
  1625. return sr
  1626. }
  1627. func (m *model) deviceWasSeen(deviceID protocol.DeviceID) {
  1628. m.deviceStatRef(deviceID).WasSeen()
  1629. }
  1630. type indexSender struct {
  1631. conn protocol.Connection
  1632. folder string
  1633. dev string
  1634. fset *db.FileSet
  1635. prevSequence int64
  1636. dropSymlinks bool
  1637. connClosed chan struct{}
  1638. stop chan struct{}
  1639. stopped chan struct{}
  1640. }
  1641. func (s *indexSender) Serve() {
  1642. defer close(s.stopped)
  1643. var err error
  1644. l.Debugf("Starting indexSender for %s to %s at %s (slv=%d)", s.folder, s.dev, s.conn, s.prevSequence)
  1645. defer l.Debugf("Exiting indexSender for %s to %s at %s: %v", s.folder, s.dev, s.conn, err)
  1646. // We need to send one index, regardless of whether there is something to send or not
  1647. err = s.sendIndexTo()
  1648. // Subscribe to LocalIndexUpdated (we have new information to send) and
  1649. // DeviceDisconnected (it might be us who disconnected, so we should
  1650. // exit).
  1651. sub := events.Default.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  1652. defer events.Default.Unsubscribe(sub)
  1653. evChan := sub.C()
  1654. ticker := time.NewTicker(time.Minute)
  1655. defer ticker.Stop()
  1656. for err == nil {
  1657. select {
  1658. case <-s.stop:
  1659. return
  1660. case <-s.connClosed:
  1661. return
  1662. default:
  1663. }
  1664. // While we have sent a sequence at least equal to the one
  1665. // currently in the database, wait for the local index to update. The
  1666. // local index may update for other folders than the one we are
  1667. // sending for.
  1668. if s.fset.Sequence(protocol.LocalDeviceID) <= s.prevSequence {
  1669. select {
  1670. case <-s.stop:
  1671. return
  1672. case <-s.connClosed:
  1673. return
  1674. case <-evChan:
  1675. case <-ticker.C:
  1676. }
  1677. continue
  1678. }
  1679. err = s.sendIndexTo()
  1680. // Wait a short amount of time before entering the next loop. If there
  1681. // are continuous changes happening to the local index, this gives us
  1682. // time to batch them up a little.
  1683. time.Sleep(250 * time.Millisecond)
  1684. }
  1685. }
  1686. func (s *indexSender) Stop() {
  1687. close(s.stop)
  1688. <-s.stopped
  1689. }
  1690. // Complete implements the suture.IsCompletable interface. When Serve terminates
  1691. // before Stop is called, the supervisor will check for this method and if it
  1692. // returns true removes the service instead of restarting it. Here it always
  1693. // returns true, as indexSender only terminates when a connection is
  1694. // closed/has failed, in which case retrying doesn't help.
  1695. func (s *indexSender) Complete() bool { return true }
  1696. // sendIndexTo sends file infos with a sequence number higher than prevSequence and
  1697. // returns the highest sent sequence number.
  1698. func (s *indexSender) sendIndexTo() error {
  1699. initial := s.prevSequence == 0
  1700. batch := newFileInfoBatch(nil)
  1701. batch.flushFn = func(fs []protocol.FileInfo) error {
  1702. l.Debugf("Sending indexes for %s to %s at %s: %d files (<%d bytes)", s.folder, s.dev, s.conn, len(batch.infos), batch.size)
  1703. if initial {
  1704. initial = false
  1705. return s.conn.Index(s.folder, fs)
  1706. }
  1707. return s.conn.IndexUpdate(s.folder, fs)
  1708. }
  1709. var err error
  1710. var f protocol.FileInfo
  1711. s.fset.WithHaveSequence(s.prevSequence+1, func(fi db.FileIntf) bool {
  1712. if err = batch.flushIfFull(); err != nil {
  1713. return false
  1714. }
  1715. if shouldDebug() {
  1716. if fi.SequenceNo() < s.prevSequence+1 {
  1717. panic(fmt.Sprintln("sequence lower than requested, got:", fi.SequenceNo(), ", asked to start at:", s.prevSequence+1))
  1718. }
  1719. if f.Sequence > 0 && fi.SequenceNo() <= f.Sequence {
  1720. panic(fmt.Sprintln("non-increasing sequence, current:", fi.SequenceNo(), "<= previous:", f.Sequence))
  1721. }
  1722. }
  1723. f = fi.(protocol.FileInfo)
  1724. // Mark the file as invalid if any of the local bad stuff flags are set.
  1725. f.RawInvalid = f.IsInvalid()
  1726. // If the file is marked LocalReceive (i.e., changed locally on a
  1727. // receive only folder) we do not want it to ever become the
  1728. // globally best version, invalid or not.
  1729. if f.IsReceiveOnlyChanged() {
  1730. f.Version = protocol.Vector{}
  1731. }
  1732. f.LocalFlags = 0 // never sent externally
  1733. if s.dropSymlinks && f.IsSymlink() {
  1734. // Do not send index entries with symlinks to clients that can't
  1735. // handle it. Fixes issue #3802. Once both sides are upgraded, a
  1736. // rescan (i.e., change) of the symlink is required for it to
  1737. // sync again, due to delta indexes.
  1738. return true
  1739. }
  1740. batch.append(f)
  1741. return true
  1742. })
  1743. if err != nil {
  1744. return err
  1745. }
  1746. err = batch.flush()
  1747. // True if there was nothing to be sent
  1748. if f.Sequence == 0 {
  1749. return err
  1750. }
  1751. s.prevSequence = f.Sequence
  1752. return err
  1753. }
  1754. func (m *model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  1755. m.pmut.RLock()
  1756. nc, ok := m.conn[deviceID]
  1757. m.pmut.RUnlock()
  1758. if !ok {
  1759. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1760. }
  1761. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x wh=%x ft=%t", m, deviceID, folder, name, offset, size, hash, weakHash, fromTemporary)
  1762. return nc.Request(folder, name, offset, size, hash, weakHash, fromTemporary)
  1763. }
  1764. func (m *model) ScanFolders() map[string]error {
  1765. m.fmut.RLock()
  1766. folders := make([]string, 0, len(m.folderCfgs))
  1767. for folder := range m.folderCfgs {
  1768. folders = append(folders, folder)
  1769. }
  1770. m.fmut.RUnlock()
  1771. errors := make(map[string]error, len(m.folderCfgs))
  1772. errorsMut := sync.NewMutex()
  1773. wg := sync.NewWaitGroup()
  1774. wg.Add(len(folders))
  1775. for _, folder := range folders {
  1776. folder := folder
  1777. go func() {
  1778. err := m.ScanFolder(folder)
  1779. if err != nil {
  1780. errorsMut.Lock()
  1781. errors[folder] = err
  1782. errorsMut.Unlock()
  1783. }
  1784. wg.Done()
  1785. }()
  1786. }
  1787. wg.Wait()
  1788. return errors
  1789. }
  1790. func (m *model) ScanFolder(folder string) error {
  1791. return m.ScanFolderSubdirs(folder, nil)
  1792. }
  1793. func (m *model) ScanFolderSubdirs(folder string, subs []string) error {
  1794. m.fmut.RLock()
  1795. err := m.checkFolderRunningLocked(folder)
  1796. runner := m.folderRunners[folder]
  1797. m.fmut.RUnlock()
  1798. if err != nil {
  1799. return err
  1800. }
  1801. return runner.Scan(subs)
  1802. }
  1803. func (m *model) DelayScan(folder string, next time.Duration) {
  1804. m.fmut.Lock()
  1805. runner, ok := m.folderRunners[folder]
  1806. m.fmut.Unlock()
  1807. if !ok {
  1808. return
  1809. }
  1810. runner.DelayScan(next)
  1811. }
  1812. // numHashers returns the number of hasher routines to use for a given folder,
  1813. // taking into account configuration and available CPU cores.
  1814. func (m *model) numHashers(folder string) int {
  1815. m.fmut.Lock()
  1816. folderCfg := m.folderCfgs[folder]
  1817. numFolders := len(m.folderCfgs)
  1818. m.fmut.Unlock()
  1819. if folderCfg.Hashers > 0 {
  1820. // Specific value set in the config, use that.
  1821. return folderCfg.Hashers
  1822. }
  1823. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1824. // Interactive operating systems; don't load the system too heavily by
  1825. // default.
  1826. return 1
  1827. }
  1828. // For other operating systems and architectures, lets try to get some
  1829. // work done... Divide the available CPU cores among the configured
  1830. // folders.
  1831. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1832. return perFolder
  1833. }
  1834. return 1
  1835. }
  1836. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1837. // the given peer device
  1838. func (m *model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1839. var message protocol.ClusterConfig
  1840. m.fmut.RLock()
  1841. defer m.fmut.RUnlock()
  1842. for _, folderCfg := range m.cfg.FolderList() {
  1843. if !folderCfg.SharedWith(device) {
  1844. continue
  1845. }
  1846. protocolFolder := protocol.Folder{
  1847. ID: folderCfg.ID,
  1848. Label: folderCfg.Label,
  1849. ReadOnly: folderCfg.Type == config.FolderTypeSendOnly,
  1850. IgnorePermissions: folderCfg.IgnorePerms,
  1851. IgnoreDelete: folderCfg.IgnoreDelete,
  1852. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1853. Paused: folderCfg.Paused,
  1854. }
  1855. var fs *db.FileSet
  1856. if !folderCfg.Paused {
  1857. fs = m.folderFiles[folderCfg.ID]
  1858. }
  1859. for _, device := range folderCfg.Devices {
  1860. deviceCfg, _ := m.cfg.Device(device.DeviceID)
  1861. protocolDevice := protocol.Device{
  1862. ID: deviceCfg.DeviceID,
  1863. Name: deviceCfg.Name,
  1864. Addresses: deviceCfg.Addresses,
  1865. Compression: deviceCfg.Compression,
  1866. CertName: deviceCfg.CertName,
  1867. Introducer: deviceCfg.Introducer,
  1868. }
  1869. if fs != nil {
  1870. if deviceCfg.DeviceID == m.id {
  1871. protocolDevice.IndexID = fs.IndexID(protocol.LocalDeviceID)
  1872. protocolDevice.MaxSequence = fs.Sequence(protocol.LocalDeviceID)
  1873. } else {
  1874. protocolDevice.IndexID = fs.IndexID(deviceCfg.DeviceID)
  1875. protocolDevice.MaxSequence = fs.Sequence(deviceCfg.DeviceID)
  1876. }
  1877. }
  1878. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1879. }
  1880. message.Folders = append(message.Folders, protocolFolder)
  1881. }
  1882. return message
  1883. }
  1884. func (m *model) State(folder string) (string, time.Time, error) {
  1885. m.fmut.RLock()
  1886. runner, ok := m.folderRunners[folder]
  1887. m.fmut.RUnlock()
  1888. if !ok {
  1889. // The returned error should be an actual folder error, so returning
  1890. // errors.New("does not exist") or similar here would be
  1891. // inappropriate.
  1892. return "", time.Time{}, nil
  1893. }
  1894. state, changed, err := runner.getState()
  1895. return state.String(), changed, err
  1896. }
  1897. func (m *model) FolderErrors(folder string) ([]FileError, error) {
  1898. m.fmut.RLock()
  1899. defer m.fmut.RUnlock()
  1900. if err := m.checkFolderRunningLocked(folder); err != nil {
  1901. return nil, err
  1902. }
  1903. return m.folderRunners[folder].Errors(), nil
  1904. }
  1905. func (m *model) WatchError(folder string) error {
  1906. m.fmut.RLock()
  1907. defer m.fmut.RUnlock()
  1908. if err := m.checkFolderRunningLocked(folder); err != nil {
  1909. return err
  1910. }
  1911. return m.folderRunners[folder].WatchError()
  1912. }
  1913. func (m *model) Override(folder string) {
  1914. // Grab the runner and the file set.
  1915. m.fmut.RLock()
  1916. runner, ok := m.folderRunners[folder]
  1917. m.fmut.RUnlock()
  1918. if !ok {
  1919. return
  1920. }
  1921. // Run the override, taking updates as if they came from scanning.
  1922. runner.Override()
  1923. }
  1924. func (m *model) Revert(folder string) {
  1925. // Grab the runner and the file set.
  1926. m.fmut.RLock()
  1927. runner, ok := m.folderRunners[folder]
  1928. m.fmut.RUnlock()
  1929. if !ok {
  1930. return
  1931. }
  1932. // Run the revert, taking updates as if they came from scanning.
  1933. runner.Revert()
  1934. }
  1935. // CurrentSequence returns the change version for the given folder.
  1936. // This is guaranteed to increment if the contents of the local folder has
  1937. // changed.
  1938. func (m *model) CurrentSequence(folder string) (int64, bool) {
  1939. m.fmut.RLock()
  1940. fs, ok := m.folderFiles[folder]
  1941. m.fmut.RUnlock()
  1942. if !ok {
  1943. // The folder might not exist, since this can be called with a user
  1944. // specified folder name from the REST interface.
  1945. return 0, false
  1946. }
  1947. return fs.Sequence(protocol.LocalDeviceID), true
  1948. }
  1949. // RemoteSequence returns the change version for the given folder, as
  1950. // sent by remote peers. This is guaranteed to increment if the contents of
  1951. // the remote or global folder has changed.
  1952. func (m *model) RemoteSequence(folder string) (int64, bool) {
  1953. m.fmut.RLock()
  1954. fs, ok := m.folderFiles[folder]
  1955. cfg := m.folderCfgs[folder]
  1956. m.fmut.RUnlock()
  1957. if !ok {
  1958. // The folder might not exist, since this can be called with a user
  1959. // specified folder name from the REST interface.
  1960. return 0, false
  1961. }
  1962. var ver int64
  1963. for _, device := range cfg.Devices {
  1964. ver += fs.Sequence(device.DeviceID)
  1965. }
  1966. return ver, true
  1967. }
  1968. func (m *model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1969. m.fmut.RLock()
  1970. files, ok := m.folderFiles[folder]
  1971. m.fmut.RUnlock()
  1972. if !ok {
  1973. return nil
  1974. }
  1975. output := make(map[string]interface{})
  1976. sep := string(filepath.Separator)
  1977. prefix = osutil.NativeFilename(prefix)
  1978. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1979. prefix = prefix + sep
  1980. }
  1981. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1982. f := fi.(db.FileInfoTruncated)
  1983. // Don't include the prefix itself.
  1984. if f.IsInvalid() || f.IsDeleted() || strings.HasPrefix(prefix, f.Name) {
  1985. return true
  1986. }
  1987. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1988. var dir, base string
  1989. if f.IsDirectory() && !f.IsSymlink() {
  1990. dir = f.Name
  1991. } else {
  1992. dir = filepath.Dir(f.Name)
  1993. base = filepath.Base(f.Name)
  1994. }
  1995. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1996. return true
  1997. }
  1998. last := output
  1999. if dir != "." {
  2000. for _, path := range strings.Split(dir, sep) {
  2001. directory, ok := last[path]
  2002. if !ok {
  2003. newdir := make(map[string]interface{})
  2004. last[path] = newdir
  2005. last = newdir
  2006. } else {
  2007. last = directory.(map[string]interface{})
  2008. }
  2009. }
  2010. }
  2011. if !dirsonly && base != "" {
  2012. last[base] = []interface{}{
  2013. f.ModTime(), f.FileSize(),
  2014. }
  2015. }
  2016. return true
  2017. })
  2018. return output
  2019. }
  2020. func (m *model) GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error) {
  2021. fcfg, ok := m.cfg.Folder(folder)
  2022. if !ok {
  2023. return nil, errFolderMissing
  2024. }
  2025. ver := fcfg.Versioner()
  2026. if ver == nil {
  2027. return nil, errors.New("no versioner configured")
  2028. }
  2029. return ver.GetVersions()
  2030. }
  2031. func (m *model) RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]string, error) {
  2032. fcfg, ok := m.cfg.Folder(folder)
  2033. if !ok {
  2034. return nil, errFolderMissing
  2035. }
  2036. ver := fcfg.Versioner()
  2037. restoreErrors := make(map[string]string)
  2038. for file, version := range versions {
  2039. if err := ver.Restore(file, version); err != nil {
  2040. restoreErrors[file] = err.Error()
  2041. }
  2042. }
  2043. // Trigger scan
  2044. if !fcfg.FSWatcherEnabled {
  2045. go func() { _ = m.ScanFolder(folder) }()
  2046. }
  2047. return restoreErrors, nil
  2048. }
  2049. func (m *model) Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) []Availability {
  2050. // The slightly unusual locking sequence here is because we need to hold
  2051. // pmut for the duration (as the value returned from foldersFiles can
  2052. // get heavily modified on Close()), but also must acquire fmut before
  2053. // pmut. (The locks can be *released* in any order.)
  2054. m.fmut.RLock()
  2055. m.pmut.RLock()
  2056. defer m.pmut.RUnlock()
  2057. fs, ok := m.folderFiles[folder]
  2058. cfg := m.folderCfgs[folder]
  2059. m.fmut.RUnlock()
  2060. if !ok {
  2061. return nil
  2062. }
  2063. var availabilities []Availability
  2064. next:
  2065. for _, device := range fs.Availability(file.Name) {
  2066. for _, pausedFolder := range m.remotePausedFolders[device] {
  2067. if pausedFolder == folder {
  2068. continue next
  2069. }
  2070. }
  2071. _, ok := m.conn[device]
  2072. if ok {
  2073. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  2074. }
  2075. }
  2076. for _, device := range cfg.Devices {
  2077. if m.deviceDownloads[device.DeviceID].Has(folder, file.Name, file.Version, int32(block.Offset/int64(file.BlockSize()))) {
  2078. availabilities = append(availabilities, Availability{ID: device.DeviceID, FromTemporary: true})
  2079. }
  2080. }
  2081. return availabilities
  2082. }
  2083. // BringToFront bumps the given files priority in the job queue.
  2084. func (m *model) BringToFront(folder, file string) {
  2085. m.fmut.RLock()
  2086. runner, ok := m.folderRunners[folder]
  2087. m.fmut.RUnlock()
  2088. if ok {
  2089. runner.BringToFront(file)
  2090. }
  2091. }
  2092. func (m *model) ResetFolder(folder string) {
  2093. l.Infof("Cleaning data for folder %q", folder)
  2094. db.DropFolder(m.db, folder)
  2095. }
  2096. func (m *model) String() string {
  2097. return fmt.Sprintf("model@%p", m)
  2098. }
  2099. func (m *model) VerifyConfiguration(from, to config.Configuration) error {
  2100. return nil
  2101. }
  2102. func (m *model) CommitConfiguration(from, to config.Configuration) bool {
  2103. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  2104. // Go through the folder configs and figure out if we need to restart or not.
  2105. fromFolders := mapFolders(from.Folders)
  2106. toFolders := mapFolders(to.Folders)
  2107. for folderID, cfg := range toFolders {
  2108. if _, ok := fromFolders[folderID]; !ok {
  2109. // A folder was added.
  2110. if cfg.Paused {
  2111. l.Infoln("Paused folder", cfg.Description())
  2112. } else {
  2113. l.Infoln("Adding folder", cfg.Description())
  2114. m.AddFolder(cfg)
  2115. m.StartFolder(folderID)
  2116. }
  2117. }
  2118. }
  2119. for folderID, fromCfg := range fromFolders {
  2120. toCfg, ok := toFolders[folderID]
  2121. if !ok {
  2122. // The folder was removed.
  2123. m.RemoveFolder(fromCfg)
  2124. continue
  2125. }
  2126. if fromCfg.Paused && toCfg.Paused {
  2127. continue
  2128. }
  2129. // This folder exists on both sides. Settings might have changed.
  2130. // Check if anything differs that requires a restart.
  2131. if !reflect.DeepEqual(fromCfg.RequiresRestartOnly(), toCfg.RequiresRestartOnly()) {
  2132. m.RestartFolder(fromCfg, toCfg)
  2133. }
  2134. // Emit the folder pause/resume event
  2135. if fromCfg.Paused != toCfg.Paused {
  2136. eventType := events.FolderResumed
  2137. if toCfg.Paused {
  2138. eventType = events.FolderPaused
  2139. }
  2140. events.Default.Log(eventType, map[string]string{"id": toCfg.ID, "label": toCfg.Label})
  2141. }
  2142. }
  2143. // Removing a device. We actually don't need to do anything.
  2144. // Because folder config has changed (since the device lists do not match)
  2145. // Folders for that had device got "restarted", which involves killing
  2146. // connections to all devices that we were sharing the folder with.
  2147. // At some point model.Close() will get called for that device which will
  2148. // clean residue device state that is not part of any folder.
  2149. // Pausing a device, unpausing is handled by the connection service.
  2150. fromDevices := from.DeviceMap()
  2151. toDevices := to.DeviceMap()
  2152. for deviceID, toCfg := range toDevices {
  2153. fromCfg, ok := fromDevices[deviceID]
  2154. if !ok || fromCfg.Paused == toCfg.Paused {
  2155. continue
  2156. }
  2157. // Ignored folder was removed, reconnect to retrigger the prompt.
  2158. if len(fromCfg.IgnoredFolders) > len(toCfg.IgnoredFolders) {
  2159. m.closeConn(deviceID, errIgnoredFolderRemoved)
  2160. }
  2161. if toCfg.Paused {
  2162. l.Infoln("Pausing", deviceID)
  2163. m.closeConn(deviceID, errDevicePaused)
  2164. events.Default.Log(events.DevicePaused, map[string]string{"device": deviceID.String()})
  2165. } else {
  2166. events.Default.Log(events.DeviceResumed, map[string]string{"device": deviceID.String()})
  2167. }
  2168. }
  2169. scanLimiter.setCapacity(to.Options.MaxConcurrentScans)
  2170. // Some options don't require restart as those components handle it fine
  2171. // by themselves. Compare the options structs containing only the
  2172. // attributes that require restart and act apprioriately.
  2173. if !reflect.DeepEqual(from.Options.RequiresRestartOnly(), to.Options.RequiresRestartOnly()) {
  2174. l.Debugln(m, "requires restart, options differ")
  2175. return false
  2176. }
  2177. return true
  2178. }
  2179. // checkFolderRunningLocked returns nil if the folder is up and running and a
  2180. // descriptive error if not.
  2181. // Need to hold (read) lock on m.fmut when calling this.
  2182. func (m *model) checkFolderRunningLocked(folder string) error {
  2183. _, ok := m.folderRunners[folder]
  2184. if ok {
  2185. return nil
  2186. }
  2187. if cfg, ok := m.cfg.Folder(folder); !ok {
  2188. return errFolderMissing
  2189. } else if cfg.Paused {
  2190. return ErrFolderPaused
  2191. }
  2192. return errFolderNotRunning
  2193. }
  2194. // checkFolderDeviceStatusLocked first checks the folder and then whether the
  2195. // given device is connected and shares this folder.
  2196. // Need to hold (read) lock on both m.fmut and m.pmut when calling this.
  2197. func (m *model) checkDeviceFolderConnectedLocked(device protocol.DeviceID, folder string) error {
  2198. if err := m.checkFolderRunningLocked(folder); err != nil {
  2199. return err
  2200. }
  2201. if cfg, ok := m.cfg.Device(device); !ok {
  2202. return errDeviceUnknown
  2203. } else if cfg.Paused {
  2204. return errDevicePaused
  2205. }
  2206. if _, ok := m.conn[device]; !ok {
  2207. return errors.New("device is not connected")
  2208. }
  2209. if cfg, ok := m.cfg.Folder(folder); !ok || !cfg.SharedWith(device) {
  2210. return errors.New("folder is not shared with device")
  2211. }
  2212. return nil
  2213. }
  2214. // mapFolders returns a map of folder ID to folder configuration for the given
  2215. // slice of folder configurations.
  2216. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  2217. m := make(map[string]config.FolderConfiguration, len(folders))
  2218. for _, cfg := range folders {
  2219. m[cfg.ID] = cfg
  2220. }
  2221. return m
  2222. }
  2223. // mapDevices returns a map of device ID to nothing for the given slice of
  2224. // device IDs.
  2225. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  2226. m := make(map[protocol.DeviceID]struct{}, len(devices))
  2227. for _, dev := range devices {
  2228. m[dev] = struct{}{}
  2229. }
  2230. return m
  2231. }
  2232. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  2233. // Returns the resulting slice, plus how much elements are left to skip or
  2234. // copy to satisfy the values which were provided, given the slice is not
  2235. // big enough.
  2236. func getChunk(data []string, skip, get int) ([]string, int, int) {
  2237. l := len(data)
  2238. if l <= skip {
  2239. return []string{}, skip - l, get
  2240. } else if l < skip+get {
  2241. return data[skip:l], 0, get - (l - skip)
  2242. }
  2243. return data[skip : skip+get], 0, 0
  2244. }
  2245. func readOffsetIntoBuf(fs fs.Filesystem, file string, offset int64, buf []byte) error {
  2246. fd, err := fs.Open(file)
  2247. if err != nil {
  2248. l.Debugln("readOffsetIntoBuf.Open", file, err)
  2249. return err
  2250. }
  2251. defer fd.Close()
  2252. _, err = fd.ReadAt(buf, offset)
  2253. if err != nil {
  2254. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  2255. }
  2256. return err
  2257. }
  2258. // makeForgetUpdate takes an index update and constructs a download progress update
  2259. // causing to forget any progress for files which we've just been sent.
  2260. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  2261. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  2262. for _, file := range files {
  2263. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  2264. continue
  2265. }
  2266. updates = append(updates, protocol.FileDownloadProgressUpdate{
  2267. Name: file.Name,
  2268. Version: file.Version,
  2269. UpdateType: protocol.UpdateTypeForget,
  2270. })
  2271. }
  2272. return updates
  2273. }
  2274. // folderDeviceSet is a set of (folder, deviceID) pairs
  2275. type folderDeviceSet map[string]map[protocol.DeviceID]struct{}
  2276. // set adds the (dev, folder) pair to the set
  2277. func (s folderDeviceSet) set(dev protocol.DeviceID, folder string) {
  2278. devs, ok := s[folder]
  2279. if !ok {
  2280. devs = make(map[protocol.DeviceID]struct{})
  2281. s[folder] = devs
  2282. }
  2283. devs[dev] = struct{}{}
  2284. }
  2285. // has returns true if the (dev, folder) pair is in the set
  2286. func (s folderDeviceSet) has(dev protocol.DeviceID, folder string) bool {
  2287. _, ok := s[folder][dev]
  2288. return ok
  2289. }
  2290. // hasDevice returns true if the device is set on any folder
  2291. func (s folderDeviceSet) hasDevice(dev protocol.DeviceID) bool {
  2292. for _, devices := range s {
  2293. if _, ok := devices[dev]; ok {
  2294. return true
  2295. }
  2296. }
  2297. return false
  2298. }
  2299. type fileInfoBatch struct {
  2300. infos []protocol.FileInfo
  2301. size int
  2302. flushFn func([]protocol.FileInfo) error
  2303. }
  2304. func newFileInfoBatch(fn func([]protocol.FileInfo) error) *fileInfoBatch {
  2305. return &fileInfoBatch{
  2306. infos: make([]protocol.FileInfo, 0, maxBatchSizeFiles),
  2307. flushFn: fn,
  2308. }
  2309. }
  2310. func (b *fileInfoBatch) append(f protocol.FileInfo) {
  2311. b.infos = append(b.infos, f)
  2312. b.size += f.ProtoSize()
  2313. }
  2314. func (b *fileInfoBatch) flushIfFull() error {
  2315. if len(b.infos) >= maxBatchSizeFiles || b.size >= maxBatchSizeBytes {
  2316. return b.flush()
  2317. }
  2318. return nil
  2319. }
  2320. func (b *fileInfoBatch) flush() error {
  2321. if len(b.infos) == 0 {
  2322. return nil
  2323. }
  2324. if err := b.flushFn(b.infos); err != nil {
  2325. return err
  2326. }
  2327. b.reset()
  2328. return nil
  2329. }
  2330. func (b *fileInfoBatch) reset() {
  2331. b.infos = b.infos[:0]
  2332. b.size = 0
  2333. }
  2334. // syncMutexMap is a type safe wrapper for a sync.Map that holds mutexes
  2335. type syncMutexMap struct {
  2336. inner stdsync.Map
  2337. }
  2338. func (m *syncMutexMap) Get(key string) sync.Mutex {
  2339. v, _ := m.inner.LoadOrStore(key, sync.NewMutex())
  2340. return v.(sync.Mutex)
  2341. }
  2342. // sanitizePath takes a string that might contain all kinds of special
  2343. // characters and makes a valid, similar, path name out of it.
  2344. //
  2345. // Spans of invalid characters are replaced by a single space. Invalid
  2346. // characters are control characters, the things not allowed in file names
  2347. // in Windows, and common shell metacharacters. Even if asterisks and pipes
  2348. // and stuff are allowed on Unixes in general they might not be allowed by
  2349. // the filesystem and may surprise the user and cause shell oddness. This
  2350. // function is intended for file names we generate on behalf of the user,
  2351. // and surprising them with odd shell characters in file names is unkind.
  2352. //
  2353. // We include whitespace in the invalid characters so that multiple
  2354. // whitespace is collapsed to a single space. Additionally, whitespace at
  2355. // either end is removed.
  2356. func sanitizePath(path string) string {
  2357. invalid := regexp.MustCompile(`([[:cntrl:]]|[<>:"'/\\|?*\n\r\t \[\]\{\};:!@$%&^#])+`)
  2358. return strings.TrimSpace(invalid.ReplaceAllString(path, " "))
  2359. }