model.go 82 KB

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