model.go 85 KB

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