model.go 82 KB

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