model.go 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453
  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 http://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bufio"
  9. "bytes"
  10. "crypto/tls"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "os"
  17. "path/filepath"
  18. "reflect"
  19. "runtime"
  20. "sort"
  21. "strings"
  22. stdsync "sync"
  23. "time"
  24. "github.com/syncthing/syncthing/lib/config"
  25. "github.com/syncthing/syncthing/lib/connections"
  26. "github.com/syncthing/syncthing/lib/db"
  27. "github.com/syncthing/syncthing/lib/events"
  28. "github.com/syncthing/syncthing/lib/fs"
  29. "github.com/syncthing/syncthing/lib/ignore"
  30. "github.com/syncthing/syncthing/lib/osutil"
  31. "github.com/syncthing/syncthing/lib/protocol"
  32. "github.com/syncthing/syncthing/lib/scanner"
  33. "github.com/syncthing/syncthing/lib/stats"
  34. "github.com/syncthing/syncthing/lib/symlinks"
  35. "github.com/syncthing/syncthing/lib/sync"
  36. "github.com/syncthing/syncthing/lib/versioner"
  37. "github.com/thejerf/suture"
  38. )
  39. // How many files to send in each Index/IndexUpdate message.
  40. const (
  41. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  42. indexBatchSize = 1000 // Either way, don't include more files than this
  43. )
  44. type service interface {
  45. BringToFront(string)
  46. DelayScan(d time.Duration)
  47. IndexUpdated() // Remote index was updated notification
  48. Jobs() ([]string, []string) // In progress, Queued
  49. Scan(subs []string) error
  50. Serve()
  51. Stop()
  52. getState() (folderState, time.Time, error)
  53. setState(state folderState)
  54. clearError()
  55. setError(err error)
  56. }
  57. type Availability struct {
  58. ID protocol.DeviceID `json:"id"`
  59. FromTemporary bool `json:"fromTemporary"`
  60. }
  61. type Model struct {
  62. *suture.Supervisor
  63. cfg *config.Wrapper
  64. db *db.Instance
  65. finder *db.BlockFinder
  66. progressEmitter *ProgressEmitter
  67. id protocol.DeviceID
  68. shortID protocol.ShortID
  69. cacheIgnoredFiles bool
  70. protectedFiles []string
  71. deviceName string
  72. clientName string
  73. clientVersion string
  74. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  75. folderFiles map[string]*db.FileSet // folder -> files
  76. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  77. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  78. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  79. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  80. folderRunners map[string]service // folder -> puller or scanner
  81. folderRunnerTokens map[string][]suture.ServiceToken // folder -> tokens for puller or scanner
  82. folderStatRefs map[string]*stats.FolderStatisticsReference // folder -> statsRef
  83. fmut sync.RWMutex // protects the above
  84. conn map[protocol.DeviceID]connections.Connection
  85. closed map[protocol.DeviceID]chan struct{}
  86. helloMessages map[protocol.DeviceID]protocol.HelloResult
  87. devicePaused map[protocol.DeviceID]bool
  88. deviceDownloads map[protocol.DeviceID]*deviceDownloadState
  89. pmut sync.RWMutex // protects the above
  90. }
  91. type folderFactory func(*Model, config.FolderConfiguration, versioner.Versioner, *fs.MtimeFS) service
  92. var (
  93. symlinkWarning = stdsync.Once{}
  94. folderFactories = make(map[config.FolderType]folderFactory, 0)
  95. )
  96. // errors returned by the CheckFolderHealth method
  97. var (
  98. errFolderPathEmpty = errors.New("folder path empty")
  99. errFolderPathMissing = errors.New("folder path missing")
  100. errFolderMarkerMissing = errors.New("folder marker missing")
  101. errHomeDiskNoSpace = errors.New("home disk has insufficient free space")
  102. errFolderNoSpace = errors.New("folder has insufficient free space")
  103. errUnsupportedSymlink = errors.New("symlink not supported")
  104. errInvalidFilename = errors.New("filename is invalid")
  105. errDeviceUnknown = errors.New("unknown device")
  106. errDevicePaused = errors.New("device is paused")
  107. errDeviceIgnored = errors.New("device is ignored")
  108. )
  109. // NewModel creates and starts a new model. The model starts in read-only mode,
  110. // where it sends index information to connected peers and responds to requests
  111. // for file data without altering the local folder in any way.
  112. func NewModel(cfg *config.Wrapper, id protocol.DeviceID, deviceName, clientName, clientVersion string, ldb *db.Instance, protectedFiles []string) *Model {
  113. m := &Model{
  114. Supervisor: suture.New("model", suture.Spec{
  115. Log: func(line string) {
  116. l.Debugln(line)
  117. },
  118. }),
  119. cfg: cfg,
  120. db: ldb,
  121. finder: db.NewBlockFinder(ldb),
  122. progressEmitter: NewProgressEmitter(cfg),
  123. id: id,
  124. shortID: id.Short(),
  125. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  126. protectedFiles: protectedFiles,
  127. deviceName: deviceName,
  128. clientName: clientName,
  129. clientVersion: clientVersion,
  130. folderCfgs: make(map[string]config.FolderConfiguration),
  131. folderFiles: make(map[string]*db.FileSet),
  132. folderDevices: make(map[string][]protocol.DeviceID),
  133. deviceFolders: make(map[protocol.DeviceID][]string),
  134. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  135. folderIgnores: make(map[string]*ignore.Matcher),
  136. folderRunners: make(map[string]service),
  137. folderRunnerTokens: make(map[string][]suture.ServiceToken),
  138. folderStatRefs: make(map[string]*stats.FolderStatisticsReference),
  139. conn: make(map[protocol.DeviceID]connections.Connection),
  140. closed: make(map[protocol.DeviceID]chan struct{}),
  141. helloMessages: make(map[protocol.DeviceID]protocol.HelloResult),
  142. devicePaused: make(map[protocol.DeviceID]bool),
  143. deviceDownloads: make(map[protocol.DeviceID]*deviceDownloadState),
  144. fmut: sync.NewRWMutex(),
  145. pmut: sync.NewRWMutex(),
  146. }
  147. if cfg.Options().ProgressUpdateIntervalS > -1 {
  148. go m.progressEmitter.Serve()
  149. }
  150. cfg.Subscribe(m)
  151. return m
  152. }
  153. // StartDeadlockDetector starts a deadlock detector on the models locks which
  154. // causes panics in case the locks cannot be acquired in the given timeout
  155. // period.
  156. func (m *Model) StartDeadlockDetector(timeout time.Duration) {
  157. l.Infof("Starting deadlock detector with %v timeout", timeout)
  158. deadlockDetect(m.fmut, timeout)
  159. deadlockDetect(m.pmut, timeout)
  160. }
  161. // StartFolder constructs the folder service and starts it.
  162. func (m *Model) StartFolder(folder string) {
  163. m.fmut.Lock()
  164. folderType := m.startFolderLocked(folder)
  165. m.fmut.Unlock()
  166. l.Infoln("Ready to synchronize", folder, fmt.Sprintf("(%s)", folderType))
  167. }
  168. func (m *Model) startFolderLocked(folder string) config.FolderType {
  169. cfg, ok := m.folderCfgs[folder]
  170. if !ok {
  171. panic("cannot start nonexistent folder " + folder)
  172. }
  173. _, ok = m.folderRunners[folder]
  174. if ok {
  175. panic("cannot start already running folder " + folder)
  176. }
  177. folderFactory, ok := folderFactories[cfg.Type]
  178. if !ok {
  179. panic(fmt.Sprintf("unknown folder type 0x%x", cfg.Type))
  180. }
  181. fs := m.folderFiles[folder]
  182. // Find any devices for which we hold the index in the db, but the folder
  183. // is not shared, and drop it.
  184. expected := mapDevices(cfg.DeviceIDs())
  185. for _, available := range fs.ListDevices() {
  186. if _, ok := expected[available]; !ok {
  187. l.Debugln("dropping", folder, "state for", available)
  188. fs.Replace(available, nil)
  189. }
  190. }
  191. v, ok := fs.Sequence(protocol.LocalDeviceID), true
  192. indexHasFiles := ok && v > 0
  193. if !indexHasFiles {
  194. // It's a blank folder, so this may the first time we're looking at
  195. // it. Attempt to create and tag with our marker as appropriate. We
  196. // don't really do anything with errors at this point except warn -
  197. // if these things don't work, we still want to start the folder and
  198. // it'll show up as errored later.
  199. if _, err := os.Stat(cfg.Path()); os.IsNotExist(err) {
  200. if err := osutil.MkdirAll(cfg.Path(), 0700); err != nil {
  201. l.Warnln("Creating folder:", err)
  202. }
  203. }
  204. if err := cfg.CreateMarker(); err != nil {
  205. l.Warnln("Creating folder marker:", err)
  206. }
  207. }
  208. var ver versioner.Versioner
  209. if len(cfg.Versioning.Type) > 0 {
  210. versionerFactory, ok := versioner.Factories[cfg.Versioning.Type]
  211. if !ok {
  212. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  213. }
  214. ver = versionerFactory(folder, cfg.Path(), cfg.Versioning.Params)
  215. if service, ok := ver.(suture.Service); ok {
  216. // The versioner implements the suture.Service interface, so
  217. // expects to be run in the background in addition to being called
  218. // when files are going to be archived.
  219. token := m.Add(service)
  220. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  221. }
  222. }
  223. p := folderFactory(m, cfg, ver, fs.MtimeFS())
  224. m.folderRunners[folder] = p
  225. m.warnAboutOverwritingProtectedFiles(folder)
  226. token := m.Add(p)
  227. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  228. return cfg.Type
  229. }
  230. func (m *Model) warnAboutOverwritingProtectedFiles(folder string) {
  231. if m.folderCfgs[folder].Type == config.FolderTypeReadOnly {
  232. return
  233. }
  234. folderLocation := m.folderCfgs[folder].Path()
  235. ignores := m.folderIgnores[folder]
  236. var filesAtRisk []string
  237. for _, protectedFilePath := range m.protectedFiles {
  238. // check if file is synced in this folder
  239. if !strings.HasPrefix(protectedFilePath, folderLocation) {
  240. continue
  241. }
  242. // check if file is ignored
  243. if ignores.Match(protectedFilePath).IsIgnored() {
  244. continue
  245. }
  246. filesAtRisk = append(filesAtRisk, protectedFilePath)
  247. }
  248. if len(filesAtRisk) > 0 {
  249. l.Warnln("Some protected files may be overwritten and cause issues. See http://docs.syncthing.net/users/config.html#syncing-configuration-files for more information. The at risk files are:", strings.Join(filesAtRisk, ", "))
  250. }
  251. }
  252. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  253. if len(cfg.ID) == 0 {
  254. panic("cannot add empty folder id")
  255. }
  256. m.fmut.Lock()
  257. m.addFolderLocked(cfg)
  258. m.fmut.Unlock()
  259. }
  260. func (m *Model) addFolderLocked(cfg config.FolderConfiguration) {
  261. m.folderCfgs[cfg.ID] = cfg
  262. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  263. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  264. for i, device := range cfg.Devices {
  265. m.folderDevices[cfg.ID][i] = device.DeviceID
  266. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  267. }
  268. ignores := ignore.New(m.cacheIgnoredFiles)
  269. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  270. l.Warnln("Loading ignores:", err)
  271. }
  272. m.folderIgnores[cfg.ID] = ignores
  273. }
  274. func (m *Model) RemoveFolder(folder string) {
  275. m.fmut.Lock()
  276. m.pmut.Lock()
  277. m.tearDownFolderLocked(folder)
  278. // Remove it from the database
  279. db.DropFolder(m.db, folder)
  280. m.pmut.Unlock()
  281. m.fmut.Unlock()
  282. }
  283. func (m *Model) tearDownFolderLocked(folder string) {
  284. // Stop the services running for this folder
  285. for _, id := range m.folderRunnerTokens[folder] {
  286. m.Remove(id)
  287. }
  288. // Close connections to affected devices
  289. for _, dev := range m.folderDevices[folder] {
  290. if conn, ok := m.conn[dev]; ok {
  291. closeRawConn(conn)
  292. }
  293. }
  294. // Clean up our config maps
  295. delete(m.folderCfgs, folder)
  296. delete(m.folderFiles, folder)
  297. delete(m.folderDevices, folder)
  298. delete(m.folderIgnores, folder)
  299. delete(m.folderRunners, folder)
  300. delete(m.folderRunnerTokens, folder)
  301. delete(m.folderStatRefs, folder)
  302. for dev, folders := range m.deviceFolders {
  303. m.deviceFolders[dev] = stringSliceWithout(folders, folder)
  304. }
  305. }
  306. func (m *Model) RestartFolder(cfg config.FolderConfiguration) {
  307. if len(cfg.ID) == 0 {
  308. panic("cannot add empty folder id")
  309. }
  310. m.fmut.Lock()
  311. m.pmut.Lock()
  312. m.tearDownFolderLocked(cfg.ID)
  313. m.addFolderLocked(cfg)
  314. folderType := m.startFolderLocked(cfg.ID)
  315. m.pmut.Unlock()
  316. m.fmut.Unlock()
  317. l.Infoln("Restarted folder", cfg.ID, fmt.Sprintf("(%s)", folderType))
  318. }
  319. type ConnectionInfo struct {
  320. protocol.Statistics
  321. Connected bool
  322. Paused bool
  323. Address string
  324. ClientVersion string
  325. Type string
  326. }
  327. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  328. return json.Marshal(map[string]interface{}{
  329. "at": info.At,
  330. "inBytesTotal": info.InBytesTotal,
  331. "outBytesTotal": info.OutBytesTotal,
  332. "connected": info.Connected,
  333. "paused": info.Paused,
  334. "address": info.Address,
  335. "clientVersion": info.ClientVersion,
  336. "type": info.Type,
  337. })
  338. }
  339. // ConnectionStats returns a map with connection statistics for each device.
  340. func (m *Model) ConnectionStats() map[string]interface{} {
  341. m.pmut.RLock()
  342. m.fmut.RLock()
  343. res := make(map[string]interface{})
  344. devs := m.cfg.Devices()
  345. conns := make(map[string]ConnectionInfo, len(devs))
  346. for device := range devs {
  347. hello := m.helloMessages[device]
  348. versionString := hello.ClientVersion
  349. if hello.ClientName != "syncthing" {
  350. versionString = hello.ClientName + " " + hello.ClientVersion
  351. }
  352. ci := ConnectionInfo{
  353. ClientVersion: strings.TrimSpace(versionString),
  354. Paused: m.devicePaused[device],
  355. }
  356. if conn, ok := m.conn[device]; ok {
  357. ci.Type = conn.Type
  358. ci.Connected = ok
  359. ci.Statistics = conn.Statistics()
  360. if addr := conn.RemoteAddr(); addr != nil {
  361. ci.Address = addr.String()
  362. }
  363. }
  364. conns[device.String()] = ci
  365. }
  366. res["connections"] = conns
  367. m.fmut.RUnlock()
  368. m.pmut.RUnlock()
  369. in, out := protocol.TotalInOut()
  370. res["total"] = ConnectionInfo{
  371. Statistics: protocol.Statistics{
  372. At: time.Now(),
  373. InBytesTotal: in,
  374. OutBytesTotal: out,
  375. },
  376. }
  377. return res
  378. }
  379. // DeviceStatistics returns statistics about each device
  380. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  381. var res = make(map[string]stats.DeviceStatistics)
  382. for id := range m.cfg.Devices() {
  383. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  384. }
  385. return res
  386. }
  387. // FolderStatistics returns statistics about each folder
  388. func (m *Model) FolderStatistics() map[string]stats.FolderStatistics {
  389. var res = make(map[string]stats.FolderStatistics)
  390. for id := range m.cfg.Folders() {
  391. res[id] = m.folderStatRef(id).GetStatistics()
  392. }
  393. return res
  394. }
  395. type FolderCompletion struct {
  396. CompletionPct float64
  397. NeedBytes int64
  398. GlobalBytes int64
  399. }
  400. // Completion returns the completion status, in percent, for the given device
  401. // and folder.
  402. func (m *Model) Completion(device protocol.DeviceID, folder string) FolderCompletion {
  403. m.fmut.RLock()
  404. rf, ok := m.folderFiles[folder]
  405. m.fmut.RUnlock()
  406. if !ok {
  407. return FolderCompletion{} // Folder doesn't exist, so we hardly have any of it
  408. }
  409. _, _, tot := rf.GlobalSize()
  410. if tot == 0 {
  411. // Folder is empty, so we have all of it
  412. return FolderCompletion{
  413. CompletionPct: 100,
  414. }
  415. }
  416. m.pmut.RLock()
  417. counts := m.deviceDownloads[device].GetBlockCounts(folder)
  418. m.pmut.RUnlock()
  419. var need, fileNeed, downloaded int64
  420. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  421. ft := f.(db.FileInfoTruncated)
  422. // This might might be more than it really is, because some blocks can be of a smaller size.
  423. downloaded = int64(counts[ft.Name] * protocol.BlockSize)
  424. fileNeed = ft.Size - downloaded
  425. if fileNeed < 0 {
  426. fileNeed = 0
  427. }
  428. need += fileNeed
  429. return true
  430. })
  431. needRatio := float64(need) / float64(tot)
  432. completionPct := 100 * (1 - needRatio)
  433. l.Debugf("%v Completion(%s, %q): %f (%d / %d = %f)", m, device, folder, completionPct, need, tot, needRatio)
  434. return FolderCompletion{
  435. CompletionPct: completionPct,
  436. NeedBytes: need,
  437. GlobalBytes: tot,
  438. }
  439. }
  440. func sizeOfFile(f db.FileIntf) (files, deleted int, bytes int64) {
  441. if !f.IsDeleted() {
  442. files++
  443. } else {
  444. deleted++
  445. }
  446. bytes += f.FileSize()
  447. return
  448. }
  449. // GlobalSize returns the number of files, deleted files and total bytes for all
  450. // files in the global model.
  451. func (m *Model) GlobalSize(folder string) (nfiles, deleted int, bytes int64) {
  452. m.fmut.RLock()
  453. defer m.fmut.RUnlock()
  454. if rf, ok := m.folderFiles[folder]; ok {
  455. nfiles, deleted, bytes = rf.GlobalSize()
  456. }
  457. return
  458. }
  459. // LocalSize returns the number of files, deleted files and total bytes for all
  460. // files in the local folder.
  461. func (m *Model) LocalSize(folder string) (nfiles, deleted int, bytes int64) {
  462. m.fmut.RLock()
  463. defer m.fmut.RUnlock()
  464. if rf, ok := m.folderFiles[folder]; ok {
  465. nfiles, deleted, bytes = rf.LocalSize()
  466. }
  467. return
  468. }
  469. // NeedSize returns the number and total size of currently needed files.
  470. func (m *Model) NeedSize(folder string) (nfiles int, bytes int64) {
  471. m.fmut.RLock()
  472. defer m.fmut.RUnlock()
  473. if rf, ok := m.folderFiles[folder]; ok {
  474. ignores := m.folderIgnores[folder]
  475. cfg := m.folderCfgs[folder]
  476. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  477. if shouldIgnore(f, ignores, cfg.IgnoreDelete) {
  478. return true
  479. }
  480. fs, de, by := sizeOfFile(f)
  481. nfiles += fs + de
  482. bytes += by
  483. return true
  484. })
  485. }
  486. bytes -= m.progressEmitter.BytesCompleted(folder)
  487. l.Debugf("%v NeedSize(%q): %d %d", m, folder, nfiles, bytes)
  488. return
  489. }
  490. // NeedFolderFiles returns paginated list of currently needed files in
  491. // progress, queued, and to be queued on next puller iteration, as well as the
  492. // total number of files currently needed.
  493. func (m *Model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated, int) {
  494. m.fmut.RLock()
  495. defer m.fmut.RUnlock()
  496. total := 0
  497. rf, ok := m.folderFiles[folder]
  498. if !ok {
  499. return nil, nil, nil, 0
  500. }
  501. var progress, queued, rest []db.FileInfoTruncated
  502. var seen map[string]struct{}
  503. skip := (page - 1) * perpage
  504. get := perpage
  505. runner, ok := m.folderRunners[folder]
  506. if ok {
  507. allProgressNames, allQueuedNames := runner.Jobs()
  508. var progressNames, queuedNames []string
  509. progressNames, skip, get = getChunk(allProgressNames, skip, get)
  510. queuedNames, skip, get = getChunk(allQueuedNames, skip, get)
  511. progress = make([]db.FileInfoTruncated, len(progressNames))
  512. queued = make([]db.FileInfoTruncated, len(queuedNames))
  513. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  514. for i, name := range progressNames {
  515. if f, ok := rf.GetGlobalTruncated(name); ok {
  516. progress[i] = f
  517. seen[name] = struct{}{}
  518. }
  519. }
  520. for i, name := range queuedNames {
  521. if f, ok := rf.GetGlobalTruncated(name); ok {
  522. queued[i] = f
  523. seen[name] = struct{}{}
  524. }
  525. }
  526. }
  527. rest = make([]db.FileInfoTruncated, 0, perpage)
  528. ignores := m.folderIgnores[folder]
  529. cfg := m.folderCfgs[folder]
  530. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  531. if shouldIgnore(f, ignores, cfg.IgnoreDelete) {
  532. return true
  533. }
  534. total++
  535. if skip > 0 {
  536. skip--
  537. return true
  538. }
  539. if get > 0 {
  540. ft := f.(db.FileInfoTruncated)
  541. if _, ok := seen[ft.Name]; !ok {
  542. rest = append(rest, ft)
  543. get--
  544. }
  545. }
  546. return true
  547. })
  548. return progress, queued, rest, total
  549. }
  550. // Index is called when a new device is connected and we receive their full index.
  551. // Implements the protocol.Model interface.
  552. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  553. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  554. if !m.folderSharedWith(folder, deviceID) {
  555. l.Debugf("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.", folder, deviceID)
  556. return
  557. }
  558. m.fmut.RLock()
  559. files, ok := m.folderFiles[folder]
  560. runner := m.folderRunners[folder]
  561. m.fmut.RUnlock()
  562. if runner != nil {
  563. // Runner may legitimately not be set if this is the "cleanup" Index
  564. // message at startup.
  565. defer runner.IndexUpdated()
  566. }
  567. if !ok {
  568. l.Fatalf("Index for nonexistent folder %q", folder)
  569. }
  570. m.pmut.RLock()
  571. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  572. m.pmut.RUnlock()
  573. files.Replace(deviceID, fs)
  574. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  575. "device": deviceID.String(),
  576. "folder": folder,
  577. "items": len(fs),
  578. "version": files.Sequence(deviceID),
  579. })
  580. }
  581. // IndexUpdate is called for incremental updates to connected devices' indexes.
  582. // Implements the protocol.Model interface.
  583. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  584. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  585. if !m.folderSharedWith(folder, deviceID) {
  586. l.Debugf("Update 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.", folder, deviceID)
  587. return
  588. }
  589. m.fmut.RLock()
  590. files := m.folderFiles[folder]
  591. runner, ok := m.folderRunners[folder]
  592. m.fmut.RUnlock()
  593. if !ok {
  594. l.Fatalf("IndexUpdate for nonexistent folder %q", folder)
  595. }
  596. m.pmut.RLock()
  597. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  598. m.pmut.RUnlock()
  599. files.Update(deviceID, fs)
  600. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  601. "device": deviceID.String(),
  602. "folder": folder,
  603. "items": len(fs),
  604. "version": files.Sequence(deviceID),
  605. })
  606. runner.IndexUpdated()
  607. }
  608. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  609. m.fmut.RLock()
  610. defer m.fmut.RUnlock()
  611. return m.folderSharedWithLocked(folder, deviceID)
  612. }
  613. func (m *Model) folderSharedWithLocked(folder string, deviceID protocol.DeviceID) bool {
  614. for _, nfolder := range m.deviceFolders[deviceID] {
  615. if nfolder == folder {
  616. return true
  617. }
  618. }
  619. return false
  620. }
  621. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfig) {
  622. // Check the peer device's announced folders against our own. Emits events
  623. // for folders that we don't expect (unknown or not shared).
  624. // Also, collect a list of folders we do share, and if he's interested in
  625. // temporary indexes, subscribe the connection.
  626. tempIndexFolders := make([]string, 0, len(cm.Folders))
  627. m.pmut.RLock()
  628. conn, ok := m.conn[deviceID]
  629. m.pmut.RUnlock()
  630. if !ok {
  631. panic("bug: ClusterConfig called on closed or nonexistent connection")
  632. }
  633. dbLocation := filepath.Dir(m.db.Location())
  634. m.fmut.Lock()
  635. for _, folder := range cm.Folders {
  636. if !m.folderSharedWithLocked(folder.ID, deviceID) {
  637. events.Default.Log(events.FolderRejected, map[string]string{
  638. "folder": folder.ID,
  639. "folderLabel": folder.Label,
  640. "device": deviceID.String(),
  641. })
  642. l.Infof("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.", folder.ID, deviceID)
  643. continue
  644. }
  645. if !folder.DisableTempIndexes {
  646. tempIndexFolders = append(tempIndexFolders, folder.ID)
  647. }
  648. fs := m.folderFiles[folder.ID]
  649. myIndexID := fs.IndexID(protocol.LocalDeviceID)
  650. mySequence := fs.Sequence(protocol.LocalDeviceID)
  651. var startSequence int64
  652. for _, dev := range folder.Devices {
  653. if bytes.Equal(dev.ID, m.id[:]) {
  654. // This is the other side's description of what it knows
  655. // about us. Lets check to see if we can start sending index
  656. // updates directly or need to send the index from start...
  657. if dev.IndexID == myIndexID {
  658. // They say they've seen our index ID before, so we can
  659. // send a delta update only.
  660. if dev.MaxSequence > mySequence {
  661. // Safety check. They claim to have more or newer
  662. // index data than we have - either we have lost
  663. // index data, or reset the index without resetting
  664. // the IndexID, or something else weird has
  665. // happened. We send a full index to reset the
  666. // situation.
  667. l.Infof("Device %v folder %q is delta index compatible, but seems out of sync with reality", deviceID, folder.ID)
  668. startSequence = 0
  669. continue
  670. }
  671. l.Infof("Device %v folder %q is delta index compatible (mlv=%d)", deviceID, folder.ID, dev.MaxSequence)
  672. startSequence = dev.MaxSequence
  673. } else if dev.IndexID != 0 {
  674. // They say they've seen an index ID from us, but it's
  675. // not the right one. Either they are confused or we
  676. // must have reset our database since last talking to
  677. // them. We'll start with a full index transfer.
  678. l.Infof("Device %v folder %q has mismatching index ID for us (%v != %v)", deviceID, folder.ID, dev.IndexID, myIndexID)
  679. startSequence = 0
  680. }
  681. } else if bytes.Equal(dev.ID, deviceID[:]) && dev.IndexID != 0 {
  682. // This is the other side's description of themselves. We
  683. // check to see that it matches the IndexID we have on file,
  684. // otherwise we drop our old index data and expect to get a
  685. // completely new set.
  686. theirIndexID := fs.IndexID(deviceID)
  687. if dev.IndexID == 0 {
  688. // They're not announcing an index ID. This means they
  689. // do not support delta indexes and we should clear any
  690. // information we have from them before accepting their
  691. // index, which will presumably be a full index.
  692. fs.Replace(deviceID, nil)
  693. } else if dev.IndexID != theirIndexID {
  694. // The index ID we have on file is not what they're
  695. // announcing. They must have reset their database and
  696. // will probably send us a full index. We drop any
  697. // information we have and remember this new index ID
  698. // instead.
  699. l.Infof("Device %v folder %q has a new index ID (%v)", deviceID, folder.ID, dev.IndexID)
  700. fs.Replace(deviceID, nil)
  701. fs.SetIndexID(deviceID, dev.IndexID)
  702. } else {
  703. // They're sending a recognized index ID and will most
  704. // likely use delta indexes. We might already have files
  705. // that we need to pull so let the folder runner know
  706. // that it should recheck the index data.
  707. if runner := m.folderRunners[folder.ID]; runner != nil {
  708. defer runner.IndexUpdated()
  709. }
  710. }
  711. }
  712. }
  713. go sendIndexes(conn, folder.ID, fs, m.folderIgnores[folder.ID], startSequence, dbLocation)
  714. }
  715. m.fmut.Unlock()
  716. // This breaks if we send multiple CM messages during the same connection.
  717. if len(tempIndexFolders) > 0 {
  718. m.pmut.RLock()
  719. conn, ok := m.conn[deviceID]
  720. m.pmut.RUnlock()
  721. // In case we've got ClusterConfig, and the connection disappeared
  722. // from infront of our nose.
  723. if ok {
  724. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  725. }
  726. }
  727. var changed bool
  728. if m.cfg.Devices()[deviceID].Introducer {
  729. // This device is an introducer. Go through the announced lists of folders
  730. // and devices and add what we are missing.
  731. for _, folder := range cm.Folders {
  732. if _, ok := m.folderDevices[folder.ID]; !ok {
  733. continue
  734. }
  735. nextDevice:
  736. for _, device := range folder.Devices {
  737. var id protocol.DeviceID
  738. copy(id[:], device.ID)
  739. if _, ok := m.cfg.Devices()[id]; !ok {
  740. // The device is currently unknown. Add it to the config.
  741. addresses := []string{"dynamic"}
  742. for _, addr := range device.Addresses {
  743. if addr != "dynamic" {
  744. addresses = append(addresses, addr)
  745. }
  746. }
  747. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  748. newDeviceCfg := config.DeviceConfiguration{
  749. DeviceID: id,
  750. Name: device.Name,
  751. Compression: m.cfg.Devices()[deviceID].Compression,
  752. Addresses: addresses,
  753. CertName: device.CertName,
  754. }
  755. // The introducers' introducers are also our introducers.
  756. if device.Introducer {
  757. l.Infof("Device %v is now also an introducer", id)
  758. newDeviceCfg.Introducer = true
  759. }
  760. m.cfg.SetDevice(newDeviceCfg)
  761. changed = true
  762. }
  763. for _, er := range m.deviceFolders[id] {
  764. if er == folder.ID {
  765. // We already share the folder with this device, so
  766. // nothing to do.
  767. continue nextDevice
  768. }
  769. }
  770. // We don't yet share this folder with this device. Add the device
  771. // to sharing list of the folder.
  772. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  773. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  774. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  775. folderCfg := m.cfg.Folders()[folder.ID]
  776. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  777. DeviceID: id,
  778. })
  779. m.cfg.SetFolder(folderCfg)
  780. changed = true
  781. }
  782. }
  783. }
  784. if changed {
  785. m.cfg.Save()
  786. }
  787. }
  788. // Closed is called when a connection has been closed
  789. func (m *Model) Closed(conn protocol.Connection, err error) {
  790. device := conn.ID()
  791. m.pmut.Lock()
  792. conn, ok := m.conn[device]
  793. if ok {
  794. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  795. }
  796. delete(m.conn, device)
  797. delete(m.helloMessages, device)
  798. delete(m.deviceDownloads, device)
  799. closed := m.closed[device]
  800. delete(m.closed, device)
  801. m.pmut.Unlock()
  802. l.Infof("Connection to %s closed: %v", device, err)
  803. events.Default.Log(events.DeviceDisconnected, map[string]string{
  804. "id": device.String(),
  805. "error": err.Error(),
  806. })
  807. close(closed)
  808. }
  809. // close will close the underlying connection for a given device
  810. func (m *Model) close(device protocol.DeviceID) {
  811. m.pmut.Lock()
  812. conn, ok := m.conn[device]
  813. m.pmut.Unlock()
  814. if !ok {
  815. // There is no connection to close
  816. return
  817. }
  818. closeRawConn(conn)
  819. }
  820. // Request returns the specified data segment by reading it from local disk.
  821. // Implements the protocol.Model interface.
  822. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, fromTemporary bool, buf []byte) error {
  823. if offset < 0 {
  824. return protocol.ErrInvalid
  825. }
  826. if !m.folderSharedWith(folder, deviceID) {
  827. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  828. return protocol.ErrNoSuchFile
  829. }
  830. if deviceID != protocol.LocalDeviceID {
  831. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, len(buf), fromTemporary)
  832. }
  833. m.fmut.RLock()
  834. folderCfg := m.folderCfgs[folder]
  835. folderPath := folderCfg.Path()
  836. folderIgnores := m.folderIgnores[folder]
  837. m.fmut.RUnlock()
  838. // filepath.Join() returns a filepath.Clean()ed path, which (quoting the
  839. // docs for clarity here):
  840. //
  841. // Clean returns the shortest path name equivalent to path by purely lexical
  842. // processing. It applies the following rules iteratively until no further
  843. // processing can be done:
  844. //
  845. // 1. Replace multiple Separator elements with a single one.
  846. // 2. Eliminate each . path name element (the current directory).
  847. // 3. Eliminate each inner .. path name element (the parent directory)
  848. // along with the non-.. element that precedes it.
  849. // 4. Eliminate .. elements that begin a rooted path:
  850. // that is, replace "/.." by "/" at the beginning of a path,
  851. // assuming Separator is '/'.
  852. fn := filepath.Join(folderPath, name)
  853. if !strings.HasPrefix(fn, folderPath) {
  854. // Request tries to escape!
  855. l.Debugf("%v Invalid REQ(in) tries to escape: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  856. return protocol.ErrInvalid
  857. }
  858. if folderIgnores != nil {
  859. // "rn" becomes the relative name of the file within the folder. This is
  860. // different than the original "name" parameter in that it's been
  861. // cleaned from any possible funny business.
  862. if rn, err := filepath.Rel(folderPath, fn); err != nil {
  863. return err
  864. } else if folderIgnores.Match(rn).IsIgnored() {
  865. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  866. return protocol.ErrNoSuchFile
  867. }
  868. }
  869. if info, err := osutil.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  870. target, _, err := symlinks.Read(fn)
  871. if err != nil {
  872. l.Debugln("symlinks.Read:", err)
  873. if os.IsNotExist(err) {
  874. return protocol.ErrNoSuchFile
  875. }
  876. return protocol.ErrGeneric
  877. }
  878. if _, err := strings.NewReader(target).ReadAt(buf, offset); err != nil {
  879. l.Debugln("symlink.Reader.ReadAt", err)
  880. return protocol.ErrGeneric
  881. }
  882. return nil
  883. }
  884. // Only check temp files if the flag is set, and if we are set to advertise
  885. // the temp indexes.
  886. if fromTemporary && !folderCfg.DisableTempIndexes {
  887. tempFn := filepath.Join(folderPath, defTempNamer.TempName(name))
  888. if err := readOffsetIntoBuf(tempFn, offset, buf); err == nil {
  889. return nil
  890. }
  891. // Fall through to reading from a non-temp file, just incase the temp
  892. // file has finished downloading.
  893. }
  894. err := readOffsetIntoBuf(fn, offset, buf)
  895. if os.IsNotExist(err) {
  896. return protocol.ErrNoSuchFile
  897. } else if err != nil {
  898. return protocol.ErrGeneric
  899. }
  900. return nil
  901. }
  902. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  903. m.fmut.RLock()
  904. fs, ok := m.folderFiles[folder]
  905. m.fmut.RUnlock()
  906. if !ok {
  907. return protocol.FileInfo{}, false
  908. }
  909. f, ok := fs.Get(protocol.LocalDeviceID, file)
  910. return f, ok
  911. }
  912. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  913. m.fmut.RLock()
  914. fs, ok := m.folderFiles[folder]
  915. m.fmut.RUnlock()
  916. if !ok {
  917. return protocol.FileInfo{}, false
  918. }
  919. f, ok := fs.GetGlobal(file)
  920. return f, ok
  921. }
  922. type cFiler struct {
  923. m *Model
  924. r string
  925. }
  926. // Implements scanner.CurrentFiler
  927. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  928. return cf.m.CurrentFolderFile(cf.r, file)
  929. }
  930. // ConnectedTo returns true if we are connected to the named device.
  931. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  932. m.pmut.RLock()
  933. _, ok := m.conn[deviceID]
  934. m.pmut.RUnlock()
  935. if ok {
  936. m.deviceWasSeen(deviceID)
  937. }
  938. return ok
  939. }
  940. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  941. var lines []string
  942. m.fmut.RLock()
  943. cfg, ok := m.folderCfgs[folder]
  944. m.fmut.RUnlock()
  945. if !ok {
  946. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  947. }
  948. if !cfg.HasMarker() {
  949. return lines, nil, fmt.Errorf("Folder %s stopped", folder)
  950. }
  951. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  952. if err != nil {
  953. if os.IsNotExist(err) {
  954. return lines, nil, nil
  955. }
  956. l.Warnln("Loading .stignore:", err)
  957. return lines, nil, err
  958. }
  959. defer fd.Close()
  960. scanner := bufio.NewScanner(fd)
  961. for scanner.Scan() {
  962. lines = append(lines, strings.TrimSpace(scanner.Text()))
  963. }
  964. m.fmut.RLock()
  965. patterns := m.folderIgnores[folder].Patterns()
  966. m.fmut.RUnlock()
  967. return lines, patterns, nil
  968. }
  969. func (m *Model) SetIgnores(folder string, content []string) error {
  970. cfg, ok := m.folderCfgs[folder]
  971. if !ok {
  972. return fmt.Errorf("Folder %s does not exist", folder)
  973. }
  974. path := filepath.Join(cfg.Path(), ".stignore")
  975. fd, err := osutil.CreateAtomic(path, 0644)
  976. if err != nil {
  977. l.Warnln("Saving .stignore:", err)
  978. return err
  979. }
  980. for _, line := range content {
  981. fmt.Fprintln(fd, line)
  982. }
  983. if err := fd.Close(); err != nil {
  984. l.Warnln("Saving .stignore:", err)
  985. return err
  986. }
  987. osutil.HideFile(path)
  988. return m.ScanFolder(folder)
  989. }
  990. // OnHello is called when an device connects to us.
  991. // This allows us to extract some information from the Hello message
  992. // and add it to a list of known devices ahead of any checks.
  993. func (m *Model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloResult) error {
  994. if m.IsPaused(remoteID) {
  995. return errDevicePaused
  996. }
  997. if m.cfg.IgnoredDevice(remoteID) {
  998. return errDeviceIgnored
  999. }
  1000. if _, ok := m.cfg.Device(remoteID); ok {
  1001. // The device exists
  1002. return nil
  1003. }
  1004. events.Default.Log(events.DeviceRejected, map[string]string{
  1005. "name": hello.DeviceName,
  1006. "device": remoteID.String(),
  1007. "address": addr.String(),
  1008. })
  1009. return errDeviceUnknown
  1010. }
  1011. // GetHello is called when we are about to connect to some remote device.
  1012. func (m *Model) GetHello(protocol.DeviceID) protocol.HelloIntf {
  1013. return &protocol.Hello{
  1014. DeviceName: m.deviceName,
  1015. ClientName: m.clientName,
  1016. ClientVersion: m.clientVersion,
  1017. }
  1018. }
  1019. // AddConnection adds a new peer connection to the model. An initial index will
  1020. // be sent to the connected peer, thereafter index updates whenever the local
  1021. // folder changes.
  1022. func (m *Model) AddConnection(conn connections.Connection, hello protocol.HelloResult) {
  1023. deviceID := conn.ID()
  1024. m.pmut.Lock()
  1025. if oldConn, ok := m.conn[deviceID]; ok {
  1026. l.Infoln("Replacing old connection", oldConn, "with", conn, "for", deviceID)
  1027. // There is an existing connection to this device that we are
  1028. // replacing. We must close the existing connection and wait for the
  1029. // close to complete before adding the new connection. We do the
  1030. // actual close without holding pmut as the connection will call
  1031. // back into Closed() for the cleanup.
  1032. closed := m.closed[deviceID]
  1033. m.pmut.Unlock()
  1034. closeRawConn(oldConn)
  1035. <-closed
  1036. m.pmut.Lock()
  1037. }
  1038. m.conn[deviceID] = conn
  1039. m.closed[deviceID] = make(chan struct{})
  1040. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  1041. m.helloMessages[deviceID] = hello
  1042. event := map[string]string{
  1043. "id": deviceID.String(),
  1044. "deviceName": hello.DeviceName,
  1045. "clientName": hello.ClientName,
  1046. "clientVersion": hello.ClientVersion,
  1047. "type": conn.Type,
  1048. }
  1049. addr := conn.RemoteAddr()
  1050. if addr != nil {
  1051. event["addr"] = addr.String()
  1052. }
  1053. events.Default.Log(events.DeviceConnected, event)
  1054. l.Infof(`Device %s client is "%s %s" named "%s"`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName)
  1055. conn.Start()
  1056. cm := m.generateClusterConfig(deviceID)
  1057. conn.ClusterConfig(cm)
  1058. m.pmut.Unlock()
  1059. device, ok := m.cfg.Devices()[deviceID]
  1060. if ok && (device.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) {
  1061. device.Name = hello.DeviceName
  1062. m.cfg.SetDevice(device)
  1063. m.cfg.Save()
  1064. }
  1065. m.deviceWasSeen(deviceID)
  1066. }
  1067. func (m *Model) PauseDevice(device protocol.DeviceID) {
  1068. m.pmut.Lock()
  1069. m.devicePaused[device] = true
  1070. conn, ok := m.conn[device]
  1071. m.pmut.Unlock()
  1072. if ok {
  1073. closeRawConn(conn)
  1074. }
  1075. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  1076. }
  1077. func (m *Model) DownloadProgress(device protocol.DeviceID, folder string, updates []protocol.FileDownloadProgressUpdate) {
  1078. if !m.folderSharedWith(folder, device) {
  1079. return
  1080. }
  1081. m.fmut.RLock()
  1082. cfg, ok := m.folderCfgs[folder]
  1083. m.fmut.RUnlock()
  1084. if !ok || cfg.Type == config.FolderTypeReadOnly || cfg.DisableTempIndexes {
  1085. return
  1086. }
  1087. m.pmut.RLock()
  1088. m.deviceDownloads[device].Update(folder, updates)
  1089. state := m.deviceDownloads[device].GetBlockCounts(folder)
  1090. m.pmut.RUnlock()
  1091. events.Default.Log(events.RemoteDownloadProgress, map[string]interface{}{
  1092. "device": device.String(),
  1093. "folder": folder,
  1094. "state": state,
  1095. })
  1096. }
  1097. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  1098. m.pmut.Lock()
  1099. m.devicePaused[device] = false
  1100. m.pmut.Unlock()
  1101. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  1102. }
  1103. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  1104. m.pmut.Lock()
  1105. paused := m.devicePaused[device]
  1106. m.pmut.Unlock()
  1107. return paused
  1108. }
  1109. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  1110. m.fmut.Lock()
  1111. defer m.fmut.Unlock()
  1112. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  1113. return sr
  1114. }
  1115. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  1116. m.deviceStatRefs[deviceID] = sr
  1117. return sr
  1118. }
  1119. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  1120. m.deviceStatRef(deviceID).WasSeen()
  1121. }
  1122. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  1123. m.fmut.Lock()
  1124. defer m.fmut.Unlock()
  1125. sr, ok := m.folderStatRefs[folder]
  1126. if !ok {
  1127. sr = stats.NewFolderStatisticsReference(m.db, folder)
  1128. m.folderStatRefs[folder] = sr
  1129. }
  1130. return sr
  1131. }
  1132. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  1133. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  1134. }
  1135. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, startSequence int64, dbLocation string) {
  1136. deviceID := conn.ID()
  1137. name := conn.Name()
  1138. var err error
  1139. l.Debugf("sendIndexes for %s-%s/%q starting (slv=%d)", deviceID, name, folder, startSequence)
  1140. defer l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  1141. minSequence, err := sendIndexTo(startSequence, conn, folder, fs, ignores, dbLocation)
  1142. // Subscribe to LocalIndexUpdated (we have new information to send) and
  1143. // DeviceDisconnected (it might be us who disconnected, so we should
  1144. // exit).
  1145. sub := events.Default.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  1146. defer events.Default.Unsubscribe(sub)
  1147. for err == nil {
  1148. if conn.Closed() {
  1149. // Our work is done.
  1150. return
  1151. }
  1152. // While we have sent a sequence at least equal to the one
  1153. // currently in the database, wait for the local index to update. The
  1154. // local index may update for other folders than the one we are
  1155. // sending for.
  1156. if fs.Sequence(protocol.LocalDeviceID) <= minSequence {
  1157. sub.Poll(time.Minute)
  1158. continue
  1159. }
  1160. minSequence, err = sendIndexTo(minSequence, conn, folder, fs, ignores, dbLocation)
  1161. // Wait a short amount of time before entering the next loop. If there
  1162. // are continuous changes happening to the local index, this gives us
  1163. // time to batch them up a little.
  1164. time.Sleep(250 * time.Millisecond)
  1165. }
  1166. }
  1167. func sendIndexTo(minSequence int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, dbLocation string) (int64, error) {
  1168. deviceID := conn.ID()
  1169. name := conn.Name()
  1170. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1171. currentBatchSize := 0
  1172. initial := minSequence == 0
  1173. maxSequence := minSequence
  1174. var err error
  1175. sorter := NewIndexSorter(dbLocation)
  1176. defer sorter.Close()
  1177. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1178. f := fi.(protocol.FileInfo)
  1179. if f.Sequence <= minSequence {
  1180. return true
  1181. }
  1182. if f.Sequence > maxSequence {
  1183. maxSequence = f.Sequence
  1184. }
  1185. sorter.Append(f)
  1186. return true
  1187. })
  1188. sorter.Sorted(func(f protocol.FileInfo) bool {
  1189. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  1190. if initial {
  1191. if err = conn.Index(folder, batch); err != nil {
  1192. return false
  1193. }
  1194. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  1195. initial = false
  1196. } else {
  1197. if err = conn.IndexUpdate(folder, batch); err != nil {
  1198. return false
  1199. }
  1200. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  1201. }
  1202. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  1203. currentBatchSize = 0
  1204. }
  1205. batch = append(batch, f)
  1206. currentBatchSize += f.ProtoSize()
  1207. return true
  1208. })
  1209. if initial && err == nil {
  1210. err = conn.Index(folder, batch)
  1211. if err == nil {
  1212. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  1213. }
  1214. } else if len(batch) > 0 && err == nil {
  1215. err = conn.IndexUpdate(folder, batch)
  1216. if err == nil {
  1217. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  1218. }
  1219. }
  1220. return maxSequence, err
  1221. }
  1222. func (m *Model) updateLocalsFromScanning(folder string, fs []protocol.FileInfo) {
  1223. m.updateLocals(folder, fs)
  1224. // Fire the LocalChangeDetected event to notify listeners about local
  1225. // updates.
  1226. m.fmut.RLock()
  1227. path := m.folderCfgs[folder].Path()
  1228. m.fmut.RUnlock()
  1229. m.localChangeDetected(folder, path, fs)
  1230. }
  1231. func (m *Model) updateLocalsFromPulling(folder string, fs []protocol.FileInfo) {
  1232. m.updateLocals(folder, fs)
  1233. }
  1234. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  1235. m.fmut.RLock()
  1236. files := m.folderFiles[folder]
  1237. m.fmut.RUnlock()
  1238. if files == nil {
  1239. // The folder doesn't exist.
  1240. return
  1241. }
  1242. files.Update(protocol.LocalDeviceID, fs)
  1243. filenames := make([]string, len(fs))
  1244. for i, file := range fs {
  1245. filenames[i] = file.Name
  1246. }
  1247. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1248. "folder": folder,
  1249. "items": len(fs),
  1250. "filenames": filenames,
  1251. "version": files.Sequence(protocol.LocalDeviceID),
  1252. })
  1253. }
  1254. func (m *Model) localChangeDetected(folder, path string, files []protocol.FileInfo) {
  1255. // For windows paths, strip unwanted chars from the front
  1256. path = strings.Replace(path, `\\?\`, "", 1)
  1257. for _, file := range files {
  1258. objType := "file"
  1259. action := "modified"
  1260. // If our local vector is version 1 AND it is the only version
  1261. // vector so far seen for this file then it is a new file. Else if
  1262. // it is > 1 it's not new, and if it is 1 but another shortId
  1263. // version vector exists then it is new for us but created elsewhere
  1264. // so the file is still not new but modified by us. Only if it is
  1265. // truly new do we change this to 'added', else we leave it as
  1266. // 'modified'.
  1267. if len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1 {
  1268. action = "added"
  1269. }
  1270. if file.IsDirectory() {
  1271. objType = "dir"
  1272. }
  1273. if file.IsDeleted() {
  1274. action = "deleted"
  1275. }
  1276. // The full file path, adjusted to the local path separator character.
  1277. path := filepath.Join(path, filepath.FromSlash(file.Name))
  1278. events.Default.Log(events.LocalChangeDetected, map[string]string{
  1279. "folder": folder,
  1280. "action": action,
  1281. "type": objType,
  1282. "path": path,
  1283. })
  1284. }
  1285. }
  1286. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  1287. m.pmut.RLock()
  1288. nc, ok := m.conn[deviceID]
  1289. m.pmut.RUnlock()
  1290. if !ok {
  1291. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1292. }
  1293. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x ft=%t", m, deviceID, folder, name, offset, size, hash, fromTemporary)
  1294. return nc.Request(folder, name, offset, size, hash, fromTemporary)
  1295. }
  1296. func (m *Model) ScanFolders() map[string]error {
  1297. m.fmut.RLock()
  1298. folders := make([]string, 0, len(m.folderCfgs))
  1299. for folder := range m.folderCfgs {
  1300. folders = append(folders, folder)
  1301. }
  1302. m.fmut.RUnlock()
  1303. errors := make(map[string]error, len(m.folderCfgs))
  1304. errorsMut := sync.NewMutex()
  1305. wg := sync.NewWaitGroup()
  1306. wg.Add(len(folders))
  1307. for _, folder := range folders {
  1308. folder := folder
  1309. go func() {
  1310. err := m.ScanFolder(folder)
  1311. if err != nil {
  1312. errorsMut.Lock()
  1313. errors[folder] = err
  1314. errorsMut.Unlock()
  1315. // Potentially sets the error twice, once in the scanner just
  1316. // by doing a check, and once here, if the error returned is
  1317. // the same one as returned by CheckFolderHealth, though
  1318. // duplicate set is handled by setError.
  1319. m.fmut.RLock()
  1320. srv := m.folderRunners[folder]
  1321. m.fmut.RUnlock()
  1322. srv.setError(err)
  1323. }
  1324. wg.Done()
  1325. }()
  1326. }
  1327. wg.Wait()
  1328. return errors
  1329. }
  1330. func (m *Model) ScanFolder(folder string) error {
  1331. return m.ScanFolderSubdirs(folder, nil)
  1332. }
  1333. func (m *Model) ScanFolderSubdirs(folder string, subs []string) error {
  1334. m.fmut.Lock()
  1335. runner, ok := m.folderRunners[folder]
  1336. m.fmut.Unlock()
  1337. // Folders are added to folderRunners only when they are started. We can't
  1338. // scan them before they have started, so that's what we need to check for
  1339. // here.
  1340. if !ok {
  1341. return errors.New("no such folder")
  1342. }
  1343. return runner.Scan(subs)
  1344. }
  1345. func (m *Model) internalScanFolderSubdirs(folder string, subDirs []string) error {
  1346. for i, sub := range subDirs {
  1347. sub = osutil.NativeFilename(sub)
  1348. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1349. return errors.New("invalid subpath")
  1350. }
  1351. subDirs[i] = sub
  1352. }
  1353. m.fmut.Lock()
  1354. fs := m.folderFiles[folder]
  1355. folderCfg := m.folderCfgs[folder]
  1356. ignores := m.folderIgnores[folder]
  1357. runner, ok := m.folderRunners[folder]
  1358. m.fmut.Unlock()
  1359. mtimefs := fs.MtimeFS()
  1360. // Check if the ignore patterns changed as part of scanning this folder.
  1361. // If they did we should schedule a pull of the folder so that we
  1362. // request things we might have suddenly become unignored and so on.
  1363. oldHash := ignores.Hash()
  1364. defer func() {
  1365. if ignores.Hash() != oldHash {
  1366. l.Debugln("Folder", folder, "ignore patterns changed; triggering puller")
  1367. runner.IndexUpdated()
  1368. }
  1369. }()
  1370. // Folders are added to folderRunners only when they are started. We can't
  1371. // scan them before they have started, so that's what we need to check for
  1372. // here.
  1373. if !ok {
  1374. return errors.New("no such folder")
  1375. }
  1376. if err := m.CheckFolderHealth(folder); err != nil {
  1377. runner.setError(err)
  1378. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1379. return err
  1380. }
  1381. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1382. err = fmt.Errorf("loading ignores: %v", err)
  1383. runner.setError(err)
  1384. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1385. return err
  1386. }
  1387. // Clean the list of subitems to ensure that we start at a known
  1388. // directory, and don't scan subdirectories of things we've already
  1389. // scanned.
  1390. subDirs = unifySubs(subDirs, func(f string) bool {
  1391. _, ok := fs.Get(protocol.LocalDeviceID, f)
  1392. return ok
  1393. })
  1394. // The cancel channel is closed whenever we return (such as from an error),
  1395. // to signal the potentially still running walker to stop.
  1396. cancel := make(chan struct{})
  1397. defer close(cancel)
  1398. runner.setState(FolderScanning)
  1399. fchan, err := scanner.Walk(scanner.Config{
  1400. Folder: folderCfg.ID,
  1401. Dir: folderCfg.Path(),
  1402. Subs: subDirs,
  1403. Matcher: ignores,
  1404. BlockSize: protocol.BlockSize,
  1405. TempNamer: defTempNamer,
  1406. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1407. CurrentFiler: cFiler{m, folder},
  1408. Lstater: mtimefs,
  1409. IgnorePerms: folderCfg.IgnorePerms,
  1410. AutoNormalize: folderCfg.AutoNormalize,
  1411. Hashers: m.numHashers(folder),
  1412. ShortID: m.shortID,
  1413. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1414. Cancel: cancel,
  1415. })
  1416. if err != nil {
  1417. // The error we get here is likely an OS level error, which might not be
  1418. // as readable as our health check errors. Check if we can get a health
  1419. // check error first, and use that if it's available.
  1420. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1421. err = ferr
  1422. }
  1423. runner.setError(err)
  1424. return err
  1425. }
  1426. batchSizeFiles := 100
  1427. batchSizeBlocks := 2048 // about 256 MB
  1428. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1429. blocksHandled := 0
  1430. for f := range fchan {
  1431. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1432. if err := m.CheckFolderHealth(folder); err != nil {
  1433. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1434. return err
  1435. }
  1436. m.updateLocalsFromScanning(folder, batch)
  1437. batch = batch[:0]
  1438. blocksHandled = 0
  1439. }
  1440. batch = append(batch, f)
  1441. blocksHandled += len(f.Blocks)
  1442. }
  1443. if err := m.CheckFolderHealth(folder); err != nil {
  1444. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1445. return err
  1446. } else if len(batch) > 0 {
  1447. m.updateLocalsFromScanning(folder, batch)
  1448. }
  1449. if len(subDirs) == 0 {
  1450. // If we have no specific subdirectories to traverse, set it to one
  1451. // empty prefix so we traverse the entire folder contents once.
  1452. subDirs = []string{""}
  1453. }
  1454. // Do a scan of the database for each prefix, to check for deleted files.
  1455. batch = batch[:0]
  1456. for _, sub := range subDirs {
  1457. var iterError error
  1458. fs.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  1459. f := fi.(db.FileInfoTruncated)
  1460. if !f.IsDeleted() {
  1461. if len(batch) == batchSizeFiles {
  1462. if err := m.CheckFolderHealth(folder); err != nil {
  1463. iterError = err
  1464. return false
  1465. }
  1466. m.updateLocalsFromScanning(folder, batch)
  1467. batch = batch[:0]
  1468. }
  1469. if !f.IsInvalid() && (ignores.Match(f.Name).IsIgnored() || symlinkInvalid(folder, f)) {
  1470. // File has been ignored or an unsupported symlink. Set invalid bit.
  1471. l.Debugln("setting invalid bit on ignored", f)
  1472. nf := protocol.FileInfo{
  1473. Name: f.Name,
  1474. Type: f.Type,
  1475. Size: f.Size,
  1476. ModifiedS: f.ModifiedS,
  1477. ModifiedNs: f.ModifiedNs,
  1478. Permissions: f.Permissions,
  1479. NoPermissions: f.NoPermissions,
  1480. Invalid: true,
  1481. Version: f.Version, // The file is still the same, so don't bump version
  1482. }
  1483. batch = append(batch, nf)
  1484. } else if _, err := mtimefs.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1485. // File has been deleted.
  1486. // We don't specifically verify that the error is
  1487. // os.IsNotExist because there is a corner case when a
  1488. // directory is suddenly transformed into a file. When that
  1489. // happens, files that were in the directory (that is now a
  1490. // file) are deleted but will return a confusing error ("not a
  1491. // directory") when we try to Lstat() them.
  1492. nf := protocol.FileInfo{
  1493. Name: f.Name,
  1494. Type: f.Type,
  1495. Size: f.Size,
  1496. ModifiedS: f.ModifiedS,
  1497. ModifiedNs: f.ModifiedNs,
  1498. Deleted: true,
  1499. Version: f.Version.Update(m.shortID),
  1500. }
  1501. batch = append(batch, nf)
  1502. }
  1503. }
  1504. return true
  1505. })
  1506. if iterError != nil {
  1507. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1508. return iterError
  1509. }
  1510. }
  1511. if err := m.CheckFolderHealth(folder); err != nil {
  1512. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1513. return err
  1514. } else if len(batch) > 0 {
  1515. m.updateLocalsFromScanning(folder, batch)
  1516. }
  1517. m.folderStatRef(folder).ScanCompleted()
  1518. runner.setState(FolderIdle)
  1519. return nil
  1520. }
  1521. func (m *Model) DelayScan(folder string, next time.Duration) {
  1522. m.fmut.Lock()
  1523. runner, ok := m.folderRunners[folder]
  1524. m.fmut.Unlock()
  1525. if !ok {
  1526. return
  1527. }
  1528. runner.DelayScan(next)
  1529. }
  1530. // numHashers returns the number of hasher routines to use for a given folder,
  1531. // taking into account configuration and available CPU cores.
  1532. func (m *Model) numHashers(folder string) int {
  1533. m.fmut.Lock()
  1534. folderCfg := m.folderCfgs[folder]
  1535. numFolders := len(m.folderCfgs)
  1536. m.fmut.Unlock()
  1537. if folderCfg.Hashers > 0 {
  1538. // Specific value set in the config, use that.
  1539. return folderCfg.Hashers
  1540. }
  1541. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1542. // Interactive operating systems; don't load the system too heavily by
  1543. // default.
  1544. return 1
  1545. }
  1546. // For other operating systems and architectures, lets try to get some
  1547. // work done... Divide the available CPU cores among the configured
  1548. // folders.
  1549. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1550. return perFolder
  1551. }
  1552. return 1
  1553. }
  1554. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1555. // the given peer device
  1556. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1557. var message protocol.ClusterConfig
  1558. m.fmut.RLock()
  1559. for _, folder := range m.deviceFolders[device] {
  1560. folderCfg := m.cfg.Folders()[folder]
  1561. fs := m.folderFiles[folder]
  1562. protocolFolder := protocol.Folder{
  1563. ID: folder,
  1564. Label: folderCfg.Label,
  1565. ReadOnly: folderCfg.Type == config.FolderTypeReadOnly,
  1566. IgnorePermissions: folderCfg.IgnorePerms,
  1567. IgnoreDelete: folderCfg.IgnoreDelete,
  1568. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1569. }
  1570. for _, device := range m.folderDevices[folder] {
  1571. // DeviceID is a value type, but with an underlying array. Copy it
  1572. // so we don't grab aliases to the same array later on in device[:]
  1573. device := device
  1574. // TODO: Set read only bit when relevant, and when we have per device
  1575. // access controls.
  1576. deviceCfg := m.cfg.Devices()[device]
  1577. var indexID protocol.IndexID
  1578. var maxSequence int64
  1579. if device == m.id {
  1580. indexID = fs.IndexID(protocol.LocalDeviceID)
  1581. maxSequence = fs.Sequence(protocol.LocalDeviceID)
  1582. } else {
  1583. indexID = fs.IndexID(device)
  1584. maxSequence = fs.Sequence(device)
  1585. }
  1586. protocolDevice := protocol.Device{
  1587. ID: device[:],
  1588. Name: deviceCfg.Name,
  1589. Addresses: deviceCfg.Addresses,
  1590. Compression: deviceCfg.Compression,
  1591. CertName: deviceCfg.CertName,
  1592. Introducer: deviceCfg.Introducer,
  1593. IndexID: indexID,
  1594. MaxSequence: maxSequence,
  1595. }
  1596. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1597. }
  1598. message.Folders = append(message.Folders, protocolFolder)
  1599. }
  1600. m.fmut.RUnlock()
  1601. return message
  1602. }
  1603. func (m *Model) State(folder string) (string, time.Time, error) {
  1604. m.fmut.RLock()
  1605. runner, ok := m.folderRunners[folder]
  1606. m.fmut.RUnlock()
  1607. if !ok {
  1608. // The returned error should be an actual folder error, so returning
  1609. // errors.New("does not exist") or similar here would be
  1610. // inappropriate.
  1611. return "", time.Time{}, nil
  1612. }
  1613. state, changed, err := runner.getState()
  1614. return state.String(), changed, err
  1615. }
  1616. func (m *Model) Override(folder string) {
  1617. m.fmut.RLock()
  1618. fs, ok := m.folderFiles[folder]
  1619. runner := m.folderRunners[folder]
  1620. m.fmut.RUnlock()
  1621. if !ok {
  1622. return
  1623. }
  1624. runner.setState(FolderScanning)
  1625. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1626. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1627. need := fi.(protocol.FileInfo)
  1628. if len(batch) == indexBatchSize {
  1629. m.updateLocalsFromScanning(folder, batch)
  1630. batch = batch[:0]
  1631. }
  1632. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1633. if !ok || have.Name != need.Name {
  1634. // We are missing the file
  1635. need.Deleted = true
  1636. need.Blocks = nil
  1637. need.Version = need.Version.Update(m.shortID)
  1638. } else {
  1639. // We have the file, replace with our version
  1640. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1641. need = have
  1642. }
  1643. need.Sequence = 0
  1644. batch = append(batch, need)
  1645. return true
  1646. })
  1647. if len(batch) > 0 {
  1648. m.updateLocalsFromScanning(folder, batch)
  1649. }
  1650. runner.setState(FolderIdle)
  1651. }
  1652. // CurrentSequence returns the change version for the given folder.
  1653. // This is guaranteed to increment if the contents of the local folder has
  1654. // changed.
  1655. func (m *Model) CurrentSequence(folder string) (int64, bool) {
  1656. m.fmut.RLock()
  1657. fs, ok := m.folderFiles[folder]
  1658. m.fmut.RUnlock()
  1659. if !ok {
  1660. // The folder might not exist, since this can be called with a user
  1661. // specified folder name from the REST interface.
  1662. return 0, false
  1663. }
  1664. return fs.Sequence(protocol.LocalDeviceID), true
  1665. }
  1666. // RemoteSequence returns the change version for the given folder, as
  1667. // sent by remote peers. This is guaranteed to increment if the contents of
  1668. // the remote or global folder has changed.
  1669. func (m *Model) RemoteSequence(folder string) (int64, bool) {
  1670. m.fmut.RLock()
  1671. defer m.fmut.RUnlock()
  1672. fs, ok := m.folderFiles[folder]
  1673. if !ok {
  1674. // The folder might not exist, since this can be called with a user
  1675. // specified folder name from the REST interface.
  1676. return 0, false
  1677. }
  1678. var ver int64
  1679. for _, n := range m.folderDevices[folder] {
  1680. ver += fs.Sequence(n)
  1681. }
  1682. return ver, true
  1683. }
  1684. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1685. m.fmut.RLock()
  1686. files, ok := m.folderFiles[folder]
  1687. m.fmut.RUnlock()
  1688. if !ok {
  1689. return nil
  1690. }
  1691. output := make(map[string]interface{})
  1692. sep := string(filepath.Separator)
  1693. prefix = osutil.NativeFilename(prefix)
  1694. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1695. prefix = prefix + sep
  1696. }
  1697. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1698. f := fi.(db.FileInfoTruncated)
  1699. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1700. return true
  1701. }
  1702. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1703. var dir, base string
  1704. if f.IsDirectory() && !f.IsSymlink() {
  1705. dir = f.Name
  1706. } else {
  1707. dir = filepath.Dir(f.Name)
  1708. base = filepath.Base(f.Name)
  1709. }
  1710. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1711. return true
  1712. }
  1713. last := output
  1714. if dir != "." {
  1715. for _, path := range strings.Split(dir, sep) {
  1716. directory, ok := last[path]
  1717. if !ok {
  1718. newdir := make(map[string]interface{})
  1719. last[path] = newdir
  1720. last = newdir
  1721. } else {
  1722. last = directory.(map[string]interface{})
  1723. }
  1724. }
  1725. }
  1726. if !dirsonly && base != "" {
  1727. last[base] = []interface{}{
  1728. f.ModTime(), f.FileSize(),
  1729. }
  1730. }
  1731. return true
  1732. })
  1733. return output
  1734. }
  1735. func (m *Model) Availability(folder, file string, version protocol.Vector, block protocol.BlockInfo) []Availability {
  1736. // Acquire this lock first, as the value returned from foldersFiles can
  1737. // get heavily modified on Close()
  1738. m.pmut.RLock()
  1739. defer m.pmut.RUnlock()
  1740. m.fmut.RLock()
  1741. fs, ok := m.folderFiles[folder]
  1742. devices := m.folderDevices[folder]
  1743. m.fmut.RUnlock()
  1744. if !ok {
  1745. return nil
  1746. }
  1747. var availabilities []Availability
  1748. for _, device := range fs.Availability(file) {
  1749. _, ok := m.conn[device]
  1750. if ok {
  1751. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  1752. }
  1753. }
  1754. for _, device := range devices {
  1755. if m.deviceDownloads[device].Has(folder, file, version, int32(block.Offset/protocol.BlockSize)) {
  1756. availabilities = append(availabilities, Availability{ID: device, FromTemporary: true})
  1757. }
  1758. }
  1759. return availabilities
  1760. }
  1761. // BringToFront bumps the given files priority in the job queue.
  1762. func (m *Model) BringToFront(folder, file string) {
  1763. m.pmut.RLock()
  1764. defer m.pmut.RUnlock()
  1765. runner, ok := m.folderRunners[folder]
  1766. if ok {
  1767. runner.BringToFront(file)
  1768. }
  1769. }
  1770. // CheckFolderHealth checks the folder for common errors and returns the
  1771. // current folder error, or nil if the folder is healthy.
  1772. func (m *Model) CheckFolderHealth(id string) error {
  1773. folder, ok := m.cfg.Folders()[id]
  1774. if !ok {
  1775. return errors.New("folder does not exist")
  1776. }
  1777. // Check for folder errors, with the most serious and specific first and
  1778. // generic ones like out of space on the home disk later. Note the
  1779. // inverted error flow (err==nil checks) here.
  1780. err := m.checkFolderPath(folder)
  1781. if err == nil {
  1782. err = m.checkFolderFreeSpace(folder)
  1783. }
  1784. if err == nil {
  1785. err = m.checkHomeDiskFree()
  1786. }
  1787. // Set or clear the error on the runner, which also does logging and
  1788. // generates events and stuff.
  1789. m.runnerExchangeError(folder, err)
  1790. return err
  1791. }
  1792. // checkFolderPath returns nil if the folder path exists and has the marker file.
  1793. func (m *Model) checkFolderPath(folder config.FolderConfiguration) error {
  1794. if folder.Path() == "" {
  1795. return errFolderPathEmpty
  1796. }
  1797. if fi, err := os.Stat(folder.Path()); err != nil || !fi.IsDir() {
  1798. return errFolderPathMissing
  1799. }
  1800. if !folder.HasMarker() {
  1801. return errFolderMarkerMissing
  1802. }
  1803. return nil
  1804. }
  1805. // checkFolderFreeSpace returns nil if the folder has the required amount of
  1806. // free space, or if folder free space checking is disabled.
  1807. func (m *Model) checkFolderFreeSpace(folder config.FolderConfiguration) error {
  1808. if folder.MinDiskFreePct <= 0 {
  1809. return nil
  1810. }
  1811. free, err := osutil.DiskFreePercentage(folder.Path())
  1812. if err == nil && free < folder.MinDiskFreePct {
  1813. return errFolderNoSpace
  1814. }
  1815. return nil
  1816. }
  1817. // checkHomeDiskFree returns nil if the home disk has the required amount of
  1818. // free space, or if home disk free space checking is disabled.
  1819. func (m *Model) checkHomeDiskFree() error {
  1820. minFree := m.cfg.Options().MinHomeDiskFreePct
  1821. if minFree <= 0 {
  1822. return nil
  1823. }
  1824. free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath())
  1825. if err == nil && free < minFree {
  1826. return errHomeDiskNoSpace
  1827. }
  1828. return nil
  1829. }
  1830. // runnerExchangeError sets the given error (which way be nil) on the folder
  1831. // runner. If the error differs from any previous error, logging and events
  1832. // happen.
  1833. func (m *Model) runnerExchangeError(folder config.FolderConfiguration, err error) {
  1834. m.fmut.RLock()
  1835. runner, runnerExists := m.folderRunners[folder.ID]
  1836. m.fmut.RUnlock()
  1837. var oldErr error
  1838. if runnerExists {
  1839. _, _, oldErr = runner.getState()
  1840. }
  1841. if err != nil {
  1842. if oldErr != nil && oldErr.Error() != err.Error() {
  1843. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1844. } else if oldErr == nil {
  1845. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1846. }
  1847. if runnerExists {
  1848. runner.setError(err)
  1849. }
  1850. } else if oldErr != nil {
  1851. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1852. if runnerExists {
  1853. runner.clearError()
  1854. }
  1855. }
  1856. }
  1857. func (m *Model) ResetFolder(folder string) {
  1858. l.Infof("Cleaning data for folder %q", folder)
  1859. db.DropFolder(m.db, folder)
  1860. }
  1861. func (m *Model) String() string {
  1862. return fmt.Sprintf("model@%p", m)
  1863. }
  1864. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1865. return nil
  1866. }
  1867. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1868. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1869. // Go through the folder configs and figure out if we need to restart or not.
  1870. fromFolders := mapFolders(from.Folders)
  1871. toFolders := mapFolders(to.Folders)
  1872. for folderID, cfg := range toFolders {
  1873. if _, ok := fromFolders[folderID]; !ok {
  1874. // A folder was added.
  1875. l.Debugln(m, "adding folder", folderID)
  1876. m.AddFolder(cfg)
  1877. m.StartFolder(folderID)
  1878. // Drop connections to all devices that can now share the new
  1879. // folder.
  1880. m.pmut.Lock()
  1881. for _, dev := range cfg.DeviceIDs() {
  1882. if conn, ok := m.conn[dev]; ok {
  1883. closeRawConn(conn)
  1884. }
  1885. }
  1886. m.pmut.Unlock()
  1887. }
  1888. }
  1889. for folderID, fromCfg := range fromFolders {
  1890. toCfg, ok := toFolders[folderID]
  1891. if !ok {
  1892. // The folder was removed.
  1893. m.RemoveFolder(folderID)
  1894. continue
  1895. }
  1896. // This folder exists on both sides. Settings might have changed.
  1897. // Check if anything differs, apart from the label.
  1898. toCfgCopy := toCfg
  1899. fromCfgCopy := fromCfg
  1900. fromCfgCopy.Label = ""
  1901. toCfgCopy.Label = ""
  1902. if !reflect.DeepEqual(fromCfgCopy, toCfgCopy) {
  1903. m.RestartFolder(toCfg)
  1904. }
  1905. }
  1906. // Removing a device. We actually don't need to do anything.
  1907. // Because folder config has changed (since the device lists do not match)
  1908. // Folders for that had device got "restarted", which involves killing
  1909. // connections to all devices that we were sharing the folder with.
  1910. // At some point model.Close() will get called for that device which will
  1911. // clean residue device state that is not part of any folder.
  1912. // Some options don't require restart as those components handle it fine
  1913. // by themselves.
  1914. from.Options.URAccepted = to.Options.URAccepted
  1915. from.Options.URUniqueID = to.Options.URUniqueID
  1916. from.Options.ListenAddresses = to.Options.ListenAddresses
  1917. from.Options.RelaysEnabled = to.Options.RelaysEnabled
  1918. from.Options.UnackedNotificationIDs = to.Options.UnackedNotificationIDs
  1919. // All of the other generic options require restart. Or at least they may;
  1920. // removing this check requires going through those options carefully and
  1921. // making sure there are individual services that handle them correctly.
  1922. // This code is the "original" requires-restart check and protects other
  1923. // components that haven't yet been converted to VerifyConfig/CommitConfig
  1924. // handling.
  1925. if !reflect.DeepEqual(from.Options, to.Options) {
  1926. l.Debugln(m, "requires restart, options differ")
  1927. return false
  1928. }
  1929. return true
  1930. }
  1931. // mapFolders returns a map of folder ID to folder configuration for the given
  1932. // slice of folder configurations.
  1933. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1934. m := make(map[string]config.FolderConfiguration, len(folders))
  1935. for _, cfg := range folders {
  1936. m[cfg.ID] = cfg
  1937. }
  1938. return m
  1939. }
  1940. // mapDevices returns a map of device ID to nothing for the given slice of
  1941. // device IDs.
  1942. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1943. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1944. for _, dev := range devices {
  1945. m[dev] = struct{}{}
  1946. }
  1947. return m
  1948. }
  1949. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1950. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1951. symlinkWarning.Do(func() {
  1952. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1953. })
  1954. // Need to type switch for the concrete type to be able to access fields...
  1955. var name string
  1956. switch fi := fi.(type) {
  1957. case protocol.FileInfo:
  1958. name = fi.Name
  1959. case db.FileInfoTruncated:
  1960. name = fi.Name
  1961. }
  1962. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1963. return true
  1964. }
  1965. return false
  1966. }
  1967. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1968. // Returns the resulting slice, plus how much elements are left to skip or
  1969. // copy to satisfy the values which were provided, given the slice is not
  1970. // big enough.
  1971. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1972. l := len(data)
  1973. if l <= skip {
  1974. return []string{}, skip - l, get
  1975. } else if l < skip+get {
  1976. return data[skip:l], 0, get - (l - skip)
  1977. }
  1978. return data[skip : skip+get], 0, 0
  1979. }
  1980. func closeRawConn(conn io.Closer) error {
  1981. if conn, ok := conn.(*tls.Conn); ok {
  1982. // If the underlying connection is a *tls.Conn, Close() does more
  1983. // than it says on the tin. Specifically, it sends a TLS alert
  1984. // message, which might block forever if the connection is dead
  1985. // and we don't have a deadline set.
  1986. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1987. }
  1988. return conn.Close()
  1989. }
  1990. func stringSliceWithout(ss []string, s string) []string {
  1991. for i := range ss {
  1992. if ss[i] == s {
  1993. copy(ss[i:], ss[i+1:])
  1994. ss = ss[:len(ss)-1]
  1995. return ss
  1996. }
  1997. }
  1998. return ss
  1999. }
  2000. func readOffsetIntoBuf(file string, offset int64, buf []byte) error {
  2001. fd, err := os.Open(file)
  2002. if err != nil {
  2003. l.Debugln("readOffsetIntoBuf.Open", file, err)
  2004. return err
  2005. }
  2006. defer fd.Close()
  2007. _, err = fd.ReadAt(buf, offset)
  2008. if err != nil {
  2009. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  2010. }
  2011. return err
  2012. }
  2013. // The exists function is expected to return true for all known paths
  2014. // (excluding "" and ".")
  2015. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  2016. subs := trimUntilParentKnown(dirs, exists)
  2017. sort.Strings(subs)
  2018. return simplifySortedPaths(subs)
  2019. }
  2020. func trimUntilParentKnown(dirs []string, exists func(dir string) bool) []string {
  2021. var subs []string
  2022. for _, sub := range dirs {
  2023. for sub != "" && sub != ".stfolder" && sub != ".stignore" {
  2024. sub = filepath.Clean(sub)
  2025. parent := filepath.Dir(sub)
  2026. if parent == "." || exists(parent) {
  2027. break
  2028. }
  2029. sub = parent
  2030. if sub == "." || sub == string(filepath.Separator) {
  2031. // Shortcut. We are going to scan the full folder, so we can
  2032. // just return an empty list of subs at this point.
  2033. return nil
  2034. }
  2035. }
  2036. if sub == "" {
  2037. return nil
  2038. }
  2039. subs = append(subs, sub)
  2040. }
  2041. return subs
  2042. }
  2043. func simplifySortedPaths(subs []string) []string {
  2044. var cleaned []string
  2045. next:
  2046. for _, sub := range subs {
  2047. for _, existing := range cleaned {
  2048. if sub == existing || strings.HasPrefix(sub, existing+string(os.PathSeparator)) {
  2049. continue next
  2050. }
  2051. }
  2052. cleaned = append(cleaned, sub)
  2053. }
  2054. return cleaned
  2055. }
  2056. // makeForgetUpdate takes an index update and constructs a download progress update
  2057. // causing to forget any progress for files which we've just been sent.
  2058. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  2059. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  2060. for _, file := range files {
  2061. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  2062. continue
  2063. }
  2064. updates = append(updates, protocol.FileDownloadProgressUpdate{
  2065. Name: file.Name,
  2066. Version: file.Version,
  2067. UpdateType: protocol.UpdateTypeForget,
  2068. })
  2069. }
  2070. return updates
  2071. }
  2072. // shouldIgnore returns true when a file should be excluded from processing
  2073. func shouldIgnore(file db.FileIntf, matcher *ignore.Matcher, ignoreDelete bool) bool {
  2074. // We check things in a certain order here...
  2075. switch {
  2076. case ignoreDelete && file.IsDeleted():
  2077. // ignoreDelete first because it's a very cheap test so a win if it
  2078. // succeeds, and we might in the long run accumulate quite a few
  2079. // deleted files.
  2080. return true
  2081. case matcher.Match(file.FileName()).IsIgnored():
  2082. // ignore patterns second because ignoring them is a valid way to
  2083. // silence warnings about them being invalid and so on.
  2084. return true
  2085. }
  2086. return false
  2087. }