model.go 82 KB

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