model.go 82 KB

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