model.go 78 KB

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