model.go 71 KB

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