model.go 85 KB

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