model.go 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/tls"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "path/filepath"
  17. "reflect"
  18. "runtime"
  19. "sort"
  20. "strings"
  21. "time"
  22. "github.com/syncthing/syncthing/lib/config"
  23. "github.com/syncthing/syncthing/lib/connections"
  24. "github.com/syncthing/syncthing/lib/db"
  25. "github.com/syncthing/syncthing/lib/events"
  26. "github.com/syncthing/syncthing/lib/fs"
  27. "github.com/syncthing/syncthing/lib/ignore"
  28. "github.com/syncthing/syncthing/lib/osutil"
  29. "github.com/syncthing/syncthing/lib/protocol"
  30. "github.com/syncthing/syncthing/lib/scanner"
  31. "github.com/syncthing/syncthing/lib/stats"
  32. "github.com/syncthing/syncthing/lib/sync"
  33. "github.com/syncthing/syncthing/lib/upgrade"
  34. "github.com/syncthing/syncthing/lib/versioner"
  35. "github.com/thejerf/suture"
  36. )
  37. var locationLocal *time.Location
  38. func init() {
  39. var err error
  40. locationLocal, err = time.LoadLocation("Local")
  41. if err != nil {
  42. panic(err.Error())
  43. }
  44. }
  45. // How many files to send in each Index/IndexUpdate message.
  46. const (
  47. maxBatchSizeBytes = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  48. maxBatchSizeFiles = 1000 // Either way, don't include more files than this
  49. )
  50. type service interface {
  51. BringToFront(string)
  52. 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] * int(ft.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, weakHash uint32, fromTemporary bool, buf []byte) error {
  1128. if offset < 0 {
  1129. return protocol.ErrInvalid
  1130. }
  1131. // Make sure the path is valid and in canonical form
  1132. var err error
  1133. if name, err = fs.Canonicalize(name); err != nil {
  1134. l.Debugf("Request from %s in paused folder %q for invalid filename %s", deviceID, folder, name)
  1135. return protocol.ErrInvalid
  1136. }
  1137. m.fmut.RLock()
  1138. folderCfg := m.folderCfgs[folder]
  1139. folderIgnores := m.folderIgnores[folder]
  1140. m.fmut.RUnlock()
  1141. if folderCfg.Paused {
  1142. l.Debugf("Request from %s for file %s in paused folder %q", deviceID, name, folder)
  1143. return protocol.ErrInvalid
  1144. }
  1145. if !m.folderSharedWith(folder, deviceID) {
  1146. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  1147. return protocol.ErrNoSuchFile
  1148. }
  1149. if deviceID != protocol.LocalDeviceID {
  1150. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, len(buf), fromTemporary)
  1151. }
  1152. folderFs := folderCfg.Filesystem()
  1153. if fs.IsInternal(name) {
  1154. l.Debugf("%v REQ(in) for internal file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  1155. return protocol.ErrNoSuchFile
  1156. }
  1157. if folderIgnores.Match(name).IsIgnored() {
  1158. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  1159. return protocol.ErrNoSuchFile
  1160. }
  1161. if err := osutil.TraversesSymlink(folderFs, filepath.Dir(name)); err != nil {
  1162. l.Debugf("%v REQ(in) traversal check: %s - %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, len(buf))
  1163. return protocol.ErrNoSuchFile
  1164. }
  1165. // Only check temp files if the flag is set, and if we are set to advertise
  1166. // the temp indexes.
  1167. if fromTemporary && !folderCfg.DisableTempIndexes {
  1168. tempFn := fs.TempName(name)
  1169. if info, err := folderFs.Lstat(tempFn); err != nil || !info.IsRegular() {
  1170. // Reject reads for anything that doesn't exist or is something
  1171. // other than a regular file.
  1172. return protocol.ErrNoSuchFile
  1173. }
  1174. err := readOffsetIntoBuf(folderFs, tempFn, offset, buf)
  1175. if err == nil && scanner.Validate(buf, hash, weakHash) {
  1176. return nil
  1177. }
  1178. // Fall through to reading from a non-temp file, just incase the temp
  1179. // file has finished downloading.
  1180. }
  1181. if info, err := folderFs.Lstat(name); err != nil || !info.IsRegular() {
  1182. // Reject reads for anything that doesn't exist or is something
  1183. // other than a regular file.
  1184. return protocol.ErrNoSuchFile
  1185. }
  1186. if err = readOffsetIntoBuf(folderFs, name, offset, buf); fs.IsNotExist(err) {
  1187. return protocol.ErrNoSuchFile
  1188. } else if err != nil {
  1189. return protocol.ErrGeneric
  1190. }
  1191. if !scanner.Validate(buf, hash, weakHash) {
  1192. m.recheckFile(deviceID, folderFs, folder, name, int(offset)/len(buf), hash)
  1193. return protocol.ErrNoSuchFile
  1194. }
  1195. return nil
  1196. }
  1197. func (m *Model) recheckFile(deviceID protocol.DeviceID, folderFs fs.Filesystem, folder, name string, blockIndex int, hash []byte) {
  1198. cf, ok := m.CurrentFolderFile(folder, name)
  1199. if !ok {
  1200. l.Debugf("%v recheckFile: %s: %q / %q: no current file", m, deviceID, folder, name)
  1201. return
  1202. }
  1203. if cf.IsDeleted() || cf.IsInvalid() || cf.IsSymlink() || cf.IsDirectory() {
  1204. l.Debugf("%v recheckFile: %s: %q / %q: not a regular file", m, deviceID, folder, name)
  1205. return
  1206. }
  1207. if blockIndex > len(cf.Blocks) {
  1208. l.Debugf("%v recheckFile: %s: %q / %q i=%d: block index too far", m, deviceID, folder, name, blockIndex)
  1209. return
  1210. }
  1211. block := cf.Blocks[blockIndex]
  1212. // Seems to want a different version of the file, whatever.
  1213. if !bytes.Equal(block.Hash, hash) {
  1214. l.Debugf("%v recheckFile: %s: %q / %q i=%d: hash mismatch %x != %x", m, deviceID, folder, name, blockIndex, block.Hash, hash)
  1215. return
  1216. }
  1217. // The hashes provided part of the request match what we expect to find according
  1218. // to what we have in the database, yet the content we've read off the filesystem doesn't
  1219. // Something is fishy, invalidate the file and rescan it.
  1220. cf.Invalidate(m.shortID)
  1221. // Update the index and tell others
  1222. // The file will temporarily become invalid, which is ok as the content is messed up.
  1223. m.updateLocalsFromScanning(folder, []protocol.FileInfo{cf})
  1224. if err := m.ScanFolderSubdirs(folder, []string{name}); err != nil {
  1225. l.Debugf("%v recheckFile: %s: %q / %q rescan: %s", m, deviceID, folder, name, err)
  1226. } else {
  1227. l.Debugf("%v recheckFile: %s: %q / %q", m, deviceID, folder, name)
  1228. }
  1229. }
  1230. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  1231. m.fmut.RLock()
  1232. fs, ok := m.folderFiles[folder]
  1233. m.fmut.RUnlock()
  1234. if !ok {
  1235. return protocol.FileInfo{}, false
  1236. }
  1237. return fs.Get(protocol.LocalDeviceID, file)
  1238. }
  1239. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  1240. m.fmut.RLock()
  1241. fs, ok := m.folderFiles[folder]
  1242. m.fmut.RUnlock()
  1243. if !ok {
  1244. return protocol.FileInfo{}, false
  1245. }
  1246. return fs.GetGlobal(file)
  1247. }
  1248. type cFiler struct {
  1249. m *Model
  1250. r string
  1251. }
  1252. // Implements scanner.CurrentFiler
  1253. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  1254. return cf.m.CurrentFolderFile(cf.r, file)
  1255. }
  1256. // Connection returns the current connection for device, and a boolean whether a connection was found.
  1257. func (m *Model) Connection(deviceID protocol.DeviceID) (connections.Connection, bool) {
  1258. m.pmut.RLock()
  1259. cn, ok := m.conn[deviceID]
  1260. m.pmut.RUnlock()
  1261. if ok {
  1262. m.deviceWasSeen(deviceID)
  1263. }
  1264. return cn, ok
  1265. }
  1266. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  1267. m.fmut.RLock()
  1268. defer m.fmut.RUnlock()
  1269. cfg, ok := m.folderCfgs[folder]
  1270. if !ok {
  1271. cfg, ok = m.cfg.Folders()[folder]
  1272. if !ok {
  1273. return nil, nil, fmt.Errorf("Folder %s does not exist", folder)
  1274. }
  1275. }
  1276. // On creation a new folder with ignore patterns validly has no marker yet.
  1277. if err := cfg.CheckPath(); err != nil && err != config.ErrMarkerMissing {
  1278. return nil, nil, err
  1279. }
  1280. ignores, ok := m.folderIgnores[folder]
  1281. if ok {
  1282. return ignores.Lines(), ignores.Patterns(), nil
  1283. }
  1284. ignores = ignore.New(fs.NewFilesystem(cfg.FilesystemType, cfg.Path))
  1285. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  1286. return nil, nil, err
  1287. }
  1288. return ignores.Lines(), ignores.Patterns(), nil
  1289. }
  1290. func (m *Model) SetIgnores(folder string, content []string) error {
  1291. cfg, ok := m.cfg.Folders()[folder]
  1292. if !ok {
  1293. return fmt.Errorf("Folder %s does not exist", folder)
  1294. }
  1295. if err := ignore.WriteIgnores(cfg.Filesystem(), ".stignore", content); err != nil {
  1296. l.Warnln("Saving .stignore:", err)
  1297. return err
  1298. }
  1299. m.fmut.RLock()
  1300. runner, ok := m.folderRunners[folder]
  1301. m.fmut.RUnlock()
  1302. if ok {
  1303. return runner.Scan(nil)
  1304. }
  1305. return nil
  1306. }
  1307. // OnHello is called when an device connects to us.
  1308. // This allows us to extract some information from the Hello message
  1309. // and add it to a list of known devices ahead of any checks.
  1310. func (m *Model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloResult) error {
  1311. if m.cfg.IgnoredDevice(remoteID) {
  1312. return errDeviceIgnored
  1313. }
  1314. cfg, ok := m.cfg.Device(remoteID)
  1315. if !ok {
  1316. events.Default.Log(events.DeviceRejected, map[string]string{
  1317. "name": hello.DeviceName,
  1318. "device": remoteID.String(),
  1319. "address": addr.String(),
  1320. })
  1321. return errDeviceUnknown
  1322. }
  1323. if cfg.Paused {
  1324. return errDevicePaused
  1325. }
  1326. if len(cfg.AllowedNetworks) > 0 {
  1327. if !connections.IsAllowedNetwork(addr.String(), cfg.AllowedNetworks) {
  1328. return errNetworkNotAllowed
  1329. }
  1330. }
  1331. return nil
  1332. }
  1333. // GetHello is called when we are about to connect to some remote device.
  1334. func (m *Model) GetHello(id protocol.DeviceID) protocol.HelloIntf {
  1335. name := ""
  1336. if _, ok := m.cfg.Device(id); ok {
  1337. name = m.cfg.MyName()
  1338. }
  1339. return &protocol.Hello{
  1340. DeviceName: name,
  1341. ClientName: m.clientName,
  1342. ClientVersion: m.clientVersion,
  1343. }
  1344. }
  1345. // AddConnection adds a new peer connection to the model. An initial index will
  1346. // be sent to the connected peer, thereafter index updates whenever the local
  1347. // folder changes.
  1348. func (m *Model) AddConnection(conn connections.Connection, hello protocol.HelloResult) {
  1349. deviceID := conn.ID()
  1350. m.pmut.Lock()
  1351. if oldConn, ok := m.conn[deviceID]; ok {
  1352. l.Infoln("Replacing old connection", oldConn, "with", conn, "for", deviceID)
  1353. // There is an existing connection to this device that we are
  1354. // replacing. We must close the existing connection and wait for the
  1355. // close to complete before adding the new connection. We do the
  1356. // actual close without holding pmut as the connection will call
  1357. // back into Closed() for the cleanup.
  1358. closed := m.closed[deviceID]
  1359. m.pmut.Unlock()
  1360. closeRawConn(oldConn)
  1361. <-closed
  1362. m.pmut.Lock()
  1363. }
  1364. m.conn[deviceID] = conn
  1365. m.closed[deviceID] = make(chan struct{})
  1366. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  1367. m.helloMessages[deviceID] = hello
  1368. event := map[string]string{
  1369. "id": deviceID.String(),
  1370. "deviceName": hello.DeviceName,
  1371. "clientName": hello.ClientName,
  1372. "clientVersion": hello.ClientVersion,
  1373. "type": conn.Type(),
  1374. }
  1375. addr := conn.RemoteAddr()
  1376. if addr != nil {
  1377. event["addr"] = addr.String()
  1378. }
  1379. events.Default.Log(events.DeviceConnected, event)
  1380. l.Infof(`Device %s client is "%s %s" named "%s" at %s`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName, conn)
  1381. conn.Start()
  1382. m.pmut.Unlock()
  1383. // Acquires fmut, so has to be done outside of pmut.
  1384. cm := m.generateClusterConfig(deviceID)
  1385. conn.ClusterConfig(cm)
  1386. device, ok := m.cfg.Devices()[deviceID]
  1387. if ok && (device.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) && hello.DeviceName != "" {
  1388. device.Name = hello.DeviceName
  1389. m.cfg.SetDevice(device)
  1390. m.cfg.Save()
  1391. }
  1392. m.deviceWasSeen(deviceID)
  1393. }
  1394. func (m *Model) DownloadProgress(device protocol.DeviceID, folder string, updates []protocol.FileDownloadProgressUpdate) {
  1395. if !m.folderSharedWith(folder, device) {
  1396. return
  1397. }
  1398. m.fmut.RLock()
  1399. cfg, ok := m.folderCfgs[folder]
  1400. m.fmut.RUnlock()
  1401. if !ok || cfg.Type == config.FolderTypeSendOnly || cfg.DisableTempIndexes {
  1402. return
  1403. }
  1404. m.pmut.RLock()
  1405. m.deviceDownloads[device].Update(folder, updates)
  1406. state := m.deviceDownloads[device].GetBlockCounts(folder)
  1407. m.pmut.RUnlock()
  1408. events.Default.Log(events.RemoteDownloadProgress, map[string]interface{}{
  1409. "device": device.String(),
  1410. "folder": folder,
  1411. "state": state,
  1412. })
  1413. }
  1414. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  1415. m.fmut.Lock()
  1416. defer m.fmut.Unlock()
  1417. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  1418. return sr
  1419. }
  1420. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  1421. m.deviceStatRefs[deviceID] = sr
  1422. return sr
  1423. }
  1424. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  1425. m.deviceStatRef(deviceID).WasSeen()
  1426. }
  1427. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  1428. m.fmut.Lock()
  1429. defer m.fmut.Unlock()
  1430. sr, ok := m.folderStatRefs[folder]
  1431. if !ok {
  1432. sr = stats.NewFolderStatisticsReference(m.db, folder)
  1433. m.folderStatRefs[folder] = sr
  1434. }
  1435. return sr
  1436. }
  1437. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  1438. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  1439. }
  1440. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, prevSequence int64, dbLocation string, dropSymlinks bool) {
  1441. deviceID := conn.ID()
  1442. var err error
  1443. l.Debugf("Starting sendIndexes for %s to %s at %s (slv=%d)", folder, deviceID, conn, prevSequence)
  1444. defer l.Debugf("Exiting sendIndexes for %s to %s at %s: %v", folder, deviceID, conn, err)
  1445. // We need to send one index, regardless of whether there is something to send or not
  1446. prevSequence, err = sendIndexTo(prevSequence, conn, folder, fs, ignores, dbLocation, dropSymlinks)
  1447. // Subscribe to LocalIndexUpdated (we have new information to send) and
  1448. // DeviceDisconnected (it might be us who disconnected, so we should
  1449. // exit).
  1450. sub := events.Default.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  1451. defer events.Default.Unsubscribe(sub)
  1452. for err == nil {
  1453. if conn.Closed() {
  1454. // Our work is done.
  1455. return
  1456. }
  1457. // While we have sent a sequence at least equal to the one
  1458. // currently in the database, wait for the local index to update. The
  1459. // local index may update for other folders than the one we are
  1460. // sending for.
  1461. if fs.Sequence(protocol.LocalDeviceID) <= prevSequence {
  1462. sub.Poll(time.Minute)
  1463. continue
  1464. }
  1465. prevSequence, err = sendIndexTo(prevSequence, conn, folder, fs, ignores, dbLocation, dropSymlinks)
  1466. // Wait a short amount of time before entering the next loop. If there
  1467. // are continuous changes happening to the local index, this gives us
  1468. // time to batch them up a little.
  1469. time.Sleep(250 * time.Millisecond)
  1470. }
  1471. }
  1472. // sendIndexTo sends file infos with a sequence number higher than prevSequence and
  1473. // returns the highest sent sequence number.
  1474. func sendIndexTo(prevSequence int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, dbLocation string, dropSymlinks bool) (int64, error) {
  1475. deviceID := conn.ID()
  1476. batch := make([]protocol.FileInfo, 0, maxBatchSizeFiles)
  1477. batchSizeBytes := 0
  1478. initial := prevSequence == 0
  1479. var err error
  1480. var f protocol.FileInfo
  1481. debugMsg := func(t string) string {
  1482. return fmt.Sprintf("Sending indexes for %s to %s at %s: %d files (<%d bytes) (%s)", folder, deviceID, conn, len(batch), batchSizeBytes, t)
  1483. }
  1484. fs.WithHaveSequence(prevSequence+1, func(fi db.FileIntf) bool {
  1485. if len(batch) == maxBatchSizeFiles || batchSizeBytes > maxBatchSizeBytes {
  1486. if initial {
  1487. if err = conn.Index(folder, batch); err != nil {
  1488. return false
  1489. }
  1490. l.Debugln(debugMsg("initial index"))
  1491. initial = false
  1492. } else {
  1493. if err = conn.IndexUpdate(folder, batch); err != nil {
  1494. return false
  1495. }
  1496. l.Debugln(debugMsg("batched update"))
  1497. }
  1498. batch = make([]protocol.FileInfo, 0, maxBatchSizeFiles)
  1499. batchSizeBytes = 0
  1500. }
  1501. f = fi.(protocol.FileInfo)
  1502. if dropSymlinks && f.IsSymlink() {
  1503. // Do not send index entries with symlinks to clients that can't
  1504. // handle it. Fixes issue #3802. Once both sides are upgraded, a
  1505. // rescan (i.e., change) of the symlink is required for it to
  1506. // sync again, due to delta indexes.
  1507. return true
  1508. }
  1509. batch = append(batch, f)
  1510. batchSizeBytes += f.ProtoSize()
  1511. return true
  1512. })
  1513. if err != nil {
  1514. return prevSequence, err
  1515. }
  1516. if initial {
  1517. err = conn.Index(folder, batch)
  1518. if err == nil {
  1519. l.Debugln(debugMsg("small initial index"))
  1520. }
  1521. } else if len(batch) > 0 {
  1522. err = conn.IndexUpdate(folder, batch)
  1523. if err == nil {
  1524. l.Debugln(debugMsg("last batch"))
  1525. }
  1526. }
  1527. // True if there was nothing to be sent
  1528. if f.Sequence == 0 {
  1529. return prevSequence, err
  1530. }
  1531. return f.Sequence, err
  1532. }
  1533. func (m *Model) updateLocalsFromScanning(folder string, fs []protocol.FileInfo) {
  1534. m.updateLocals(folder, fs)
  1535. m.fmut.RLock()
  1536. folderCfg := m.folderCfgs[folder]
  1537. m.fmut.RUnlock()
  1538. m.diskChangeDetected(folderCfg, fs, events.LocalChangeDetected)
  1539. }
  1540. func (m *Model) updateLocalsFromPulling(folder string, fs []protocol.FileInfo) {
  1541. m.updateLocals(folder, fs)
  1542. m.fmut.RLock()
  1543. folderCfg := m.folderCfgs[folder]
  1544. m.fmut.RUnlock()
  1545. m.diskChangeDetected(folderCfg, fs, events.RemoteChangeDetected)
  1546. }
  1547. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  1548. m.fmut.RLock()
  1549. files := m.folderFiles[folder]
  1550. m.fmut.RUnlock()
  1551. if files == nil {
  1552. // The folder doesn't exist.
  1553. return
  1554. }
  1555. files.Update(protocol.LocalDeviceID, fs)
  1556. filenames := make([]string, len(fs))
  1557. for i, file := range fs {
  1558. filenames[i] = file.Name
  1559. }
  1560. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1561. "folder": folder,
  1562. "items": len(fs),
  1563. "filenames": filenames,
  1564. "version": files.Sequence(protocol.LocalDeviceID),
  1565. })
  1566. }
  1567. func (m *Model) diskChangeDetected(folderCfg config.FolderConfiguration, files []protocol.FileInfo, typeOfEvent events.EventType) {
  1568. for _, file := range files {
  1569. if file.IsInvalid() {
  1570. continue
  1571. }
  1572. objType := "file"
  1573. action := "modified"
  1574. switch {
  1575. case file.IsDeleted():
  1576. action = "deleted"
  1577. // If our local vector is version 1 AND it is the only version
  1578. // vector so far seen for this file then it is a new file. Else if
  1579. // it is > 1 it's not new, and if it is 1 but another shortId
  1580. // version vector exists then it is new for us but created elsewhere
  1581. // so the file is still not new but modified by us. Only if it is
  1582. // truly new do we change this to 'added', else we leave it as
  1583. // 'modified'.
  1584. case len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1:
  1585. action = "added"
  1586. }
  1587. if file.IsSymlink() {
  1588. objType = "symlink"
  1589. } else if file.IsDirectory() {
  1590. objType = "dir"
  1591. }
  1592. // Two different events can be fired here based on what EventType is passed into function
  1593. events.Default.Log(typeOfEvent, map[string]string{
  1594. "folder": folderCfg.ID,
  1595. "folderID": folderCfg.ID, // incorrect, deprecated, kept for historical compliance
  1596. "label": folderCfg.Label,
  1597. "action": action,
  1598. "type": objType,
  1599. "path": filepath.FromSlash(file.Name),
  1600. "modifiedBy": file.ModifiedBy.String(),
  1601. })
  1602. }
  1603. }
  1604. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  1605. m.pmut.RLock()
  1606. nc, ok := m.conn[deviceID]
  1607. m.pmut.RUnlock()
  1608. if !ok {
  1609. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1610. }
  1611. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x wh=%x ft=%t", m, deviceID, folder, name, offset, size, hash, weakHash, fromTemporary)
  1612. return nc.Request(folder, name, offset, size, hash, weakHash, fromTemporary)
  1613. }
  1614. func (m *Model) ScanFolders() map[string]error {
  1615. m.fmut.RLock()
  1616. folders := make([]string, 0, len(m.folderCfgs))
  1617. for folder := range m.folderCfgs {
  1618. folders = append(folders, folder)
  1619. }
  1620. m.fmut.RUnlock()
  1621. errors := make(map[string]error, len(m.folderCfgs))
  1622. errorsMut := sync.NewMutex()
  1623. wg := sync.NewWaitGroup()
  1624. wg.Add(len(folders))
  1625. for _, folder := range folders {
  1626. folder := folder
  1627. go func() {
  1628. err := m.ScanFolder(folder)
  1629. if err != nil {
  1630. errorsMut.Lock()
  1631. errors[folder] = err
  1632. errorsMut.Unlock()
  1633. // Potentially sets the error twice, once in the scanner just
  1634. // by doing a check, and once here, if the error returned is
  1635. // the same one as returned by CheckHealth, though
  1636. // duplicate set is handled by setError.
  1637. m.fmut.RLock()
  1638. srv := m.folderRunners[folder]
  1639. m.fmut.RUnlock()
  1640. srv.setError(err)
  1641. }
  1642. wg.Done()
  1643. }()
  1644. }
  1645. wg.Wait()
  1646. return errors
  1647. }
  1648. func (m *Model) ScanFolder(folder string) error {
  1649. return m.ScanFolderSubdirs(folder, nil)
  1650. }
  1651. func (m *Model) ScanFolderSubdirs(folder string, subs []string) error {
  1652. m.fmut.RLock()
  1653. if err := m.checkFolderRunningLocked(folder); err != nil {
  1654. m.fmut.RUnlock()
  1655. return err
  1656. }
  1657. runner := m.folderRunners[folder]
  1658. m.fmut.RUnlock()
  1659. return runner.Scan(subs)
  1660. }
  1661. func (m *Model) internalScanFolderSubdirs(ctx context.Context, folder string, subDirs []string) error {
  1662. m.fmut.RLock()
  1663. if err := m.checkFolderRunningLocked(folder); err != nil {
  1664. m.fmut.RUnlock()
  1665. return err
  1666. }
  1667. fset := m.folderFiles[folder]
  1668. folderCfg := m.folderCfgs[folder]
  1669. ignores := m.folderIgnores[folder]
  1670. runner := m.folderRunners[folder]
  1671. m.fmut.RUnlock()
  1672. mtimefs := fset.MtimeFS()
  1673. for i := range subDirs {
  1674. sub := osutil.NativeFilename(subDirs[i])
  1675. if sub == "" {
  1676. // A blank subdirs means to scan the entire folder. We can trim
  1677. // the subDirs list and go on our way.
  1678. subDirs = nil
  1679. break
  1680. }
  1681. subDirs[i] = sub
  1682. }
  1683. // Check if the ignore patterns changed as part of scanning this folder.
  1684. // If they did we should schedule a pull of the folder so that we
  1685. // request things we might have suddenly become unignored and so on.
  1686. oldHash := ignores.Hash()
  1687. defer func() {
  1688. if ignores.Hash() != oldHash {
  1689. l.Debugln("Folder", folder, "ignore patterns changed; triggering puller")
  1690. runner.IgnoresUpdated()
  1691. }
  1692. }()
  1693. if err := runner.CheckHealth(); err != nil {
  1694. return err
  1695. }
  1696. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  1697. err = fmt.Errorf("loading ignores: %v", err)
  1698. runner.setError(err)
  1699. return err
  1700. }
  1701. // Clean the list of subitems to ensure that we start at a known
  1702. // directory, and don't scan subdirectories of things we've already
  1703. // scanned.
  1704. subDirs = unifySubs(subDirs, func(f string) bool {
  1705. _, ok := fset.Get(protocol.LocalDeviceID, f)
  1706. return ok
  1707. })
  1708. runner.setState(FolderScanning)
  1709. fchan := scanner.Walk(ctx, scanner.Config{
  1710. Folder: folderCfg.ID,
  1711. Subs: subDirs,
  1712. Matcher: ignores,
  1713. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1714. CurrentFiler: cFiler{m, folder},
  1715. Filesystem: mtimefs,
  1716. IgnorePerms: folderCfg.IgnorePerms,
  1717. AutoNormalize: folderCfg.AutoNormalize,
  1718. Hashers: m.numHashers(folder),
  1719. ShortID: m.shortID,
  1720. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1721. UseLargeBlocks: folderCfg.UseLargeBlocks,
  1722. })
  1723. if err := runner.CheckHealth(); err != nil {
  1724. return err
  1725. }
  1726. batch := make([]protocol.FileInfo, 0, maxBatchSizeFiles)
  1727. batchSizeBytes := 0
  1728. changes := 0
  1729. // Schedule a pull after scanning, but only if we actually detected any
  1730. // changes.
  1731. defer func() {
  1732. if changes > 0 {
  1733. runner.SchedulePull()
  1734. }
  1735. }()
  1736. for f := range fchan {
  1737. if len(batch) == maxBatchSizeFiles || batchSizeBytes > maxBatchSizeBytes {
  1738. if err := runner.CheckHealth(); err != nil {
  1739. l.Debugln("Stopping scan of folder %s due to: %s", folderCfg.Description(), err)
  1740. return err
  1741. }
  1742. m.updateLocalsFromScanning(folder, batch)
  1743. batch = batch[:0]
  1744. batchSizeBytes = 0
  1745. }
  1746. batch = append(batch, f)
  1747. batchSizeBytes += f.ProtoSize()
  1748. changes++
  1749. }
  1750. if err := runner.CheckHealth(); err != nil {
  1751. l.Debugln("Stopping scan of folder %s due to: %s", folderCfg.Description(), err)
  1752. return err
  1753. } else if len(batch) > 0 {
  1754. m.updateLocalsFromScanning(folder, batch)
  1755. }
  1756. if len(subDirs) == 0 {
  1757. // If we have no specific subdirectories to traverse, set it to one
  1758. // empty prefix so we traverse the entire folder contents once.
  1759. subDirs = []string{""}
  1760. }
  1761. // Do a scan of the database for each prefix, to check for deleted and
  1762. // ignored files.
  1763. batch = batch[:0]
  1764. batchSizeBytes = 0
  1765. for _, sub := range subDirs {
  1766. var iterError error
  1767. fset.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  1768. f := fi.(db.FileInfoTruncated)
  1769. if len(batch) == maxBatchSizeFiles || batchSizeBytes > maxBatchSizeBytes {
  1770. if err := runner.CheckHealth(); err != nil {
  1771. iterError = err
  1772. return false
  1773. }
  1774. m.updateLocalsFromScanning(folder, batch)
  1775. batch = batch[:0]
  1776. batchSizeBytes = 0
  1777. }
  1778. switch {
  1779. case !f.IsInvalid() && ignores.Match(f.Name).IsIgnored():
  1780. // File was valid at last pass but has been ignored. Set invalid bit.
  1781. l.Debugln("setting invalid bit on ignored", f)
  1782. nf := f.ConvertToInvalidFileInfo(m.id.Short())
  1783. batch = append(batch, nf)
  1784. batchSizeBytes += nf.ProtoSize()
  1785. changes++
  1786. case f.IsInvalid() && !ignores.Match(f.Name).IsIgnored():
  1787. // Successfully scanned items are already un-ignored during
  1788. // the scan, so check whether it is deleted.
  1789. fallthrough
  1790. case !f.IsInvalid() && !f.IsDeleted():
  1791. // The file is valid and not deleted. Lets check if it's
  1792. // still here.
  1793. // Simply stating it wont do as there are tons of corner
  1794. // cases (e.g. parent dir->simlink, missing permissions)
  1795. if !osutil.IsDeleted(mtimefs, f.Name) {
  1796. return true
  1797. }
  1798. nf := protocol.FileInfo{
  1799. Name: f.Name,
  1800. Type: f.Type,
  1801. Size: 0,
  1802. ModifiedS: f.ModifiedS,
  1803. ModifiedNs: f.ModifiedNs,
  1804. ModifiedBy: m.id.Short(),
  1805. Deleted: true,
  1806. Version: f.Version.Update(m.shortID),
  1807. }
  1808. // We do not want to override the global version
  1809. // with the deleted file. Keeping only our local
  1810. // counter makes sure we are in conflict with any
  1811. // other existing versions, which will be resolved
  1812. // by the normal pulling mechanisms.
  1813. if f.IsInvalid() {
  1814. nf.Version = nf.Version.DropOthers(m.shortID)
  1815. }
  1816. batch = append(batch, nf)
  1817. batchSizeBytes += nf.ProtoSize()
  1818. changes++
  1819. }
  1820. return true
  1821. })
  1822. if iterError != nil {
  1823. l.Debugln("Stopping scan of folder %s due to: %s", folderCfg.Description(), iterError)
  1824. return iterError
  1825. }
  1826. }
  1827. if err := runner.CheckHealth(); err != nil {
  1828. l.Debugln("Stopping scan of folder %s due to: %s", folderCfg.Description(), err)
  1829. return err
  1830. } else if len(batch) > 0 {
  1831. m.updateLocalsFromScanning(folder, batch)
  1832. }
  1833. m.folderStatRef(folder).ScanCompleted()
  1834. runner.setState(FolderIdle)
  1835. return nil
  1836. }
  1837. func (m *Model) DelayScan(folder string, next time.Duration) {
  1838. m.fmut.Lock()
  1839. runner, ok := m.folderRunners[folder]
  1840. m.fmut.Unlock()
  1841. if !ok {
  1842. return
  1843. }
  1844. runner.DelayScan(next)
  1845. }
  1846. // numHashers returns the number of hasher routines to use for a given folder,
  1847. // taking into account configuration and available CPU cores.
  1848. func (m *Model) numHashers(folder string) int {
  1849. m.fmut.Lock()
  1850. folderCfg := m.folderCfgs[folder]
  1851. numFolders := len(m.folderCfgs)
  1852. m.fmut.Unlock()
  1853. if folderCfg.Hashers > 0 {
  1854. // Specific value set in the config, use that.
  1855. return folderCfg.Hashers
  1856. }
  1857. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1858. // Interactive operating systems; don't load the system too heavily by
  1859. // default.
  1860. return 1
  1861. }
  1862. // For other operating systems and architectures, lets try to get some
  1863. // work done... Divide the available CPU cores among the configured
  1864. // folders.
  1865. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1866. return perFolder
  1867. }
  1868. return 1
  1869. }
  1870. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1871. // the given peer device
  1872. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1873. var message protocol.ClusterConfig
  1874. m.fmut.RLock()
  1875. folderFiles := m.folderFiles
  1876. m.fmut.RUnlock()
  1877. var fs *db.FileSet
  1878. for _, folderCfg := range m.cfg.FolderList() {
  1879. protocolFolder := protocol.Folder{
  1880. ID: folderCfg.ID,
  1881. Label: folderCfg.Label,
  1882. ReadOnly: folderCfg.Type == config.FolderTypeSendOnly,
  1883. IgnorePermissions: folderCfg.IgnorePerms,
  1884. IgnoreDelete: folderCfg.IgnoreDelete,
  1885. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1886. Paused: folderCfg.Paused,
  1887. }
  1888. if !folderCfg.Paused {
  1889. fs = folderFiles[folderCfg.ID]
  1890. }
  1891. for _, device := range folderCfg.Devices {
  1892. deviceCfg, _ := m.cfg.Device(device.DeviceID)
  1893. protocolDevice := protocol.Device{
  1894. ID: deviceCfg.DeviceID,
  1895. Name: deviceCfg.Name,
  1896. Addresses: deviceCfg.Addresses,
  1897. Compression: deviceCfg.Compression,
  1898. CertName: deviceCfg.CertName,
  1899. Introducer: deviceCfg.Introducer,
  1900. }
  1901. if !folderCfg.Paused {
  1902. if deviceCfg.DeviceID == m.id {
  1903. protocolDevice.IndexID = fs.IndexID(protocol.LocalDeviceID)
  1904. protocolDevice.MaxSequence = fs.Sequence(protocol.LocalDeviceID)
  1905. } else {
  1906. protocolDevice.IndexID = fs.IndexID(deviceCfg.DeviceID)
  1907. protocolDevice.MaxSequence = fs.Sequence(deviceCfg.DeviceID)
  1908. }
  1909. }
  1910. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1911. }
  1912. message.Folders = append(message.Folders, protocolFolder)
  1913. }
  1914. return message
  1915. }
  1916. func (m *Model) State(folder string) (string, time.Time, error) {
  1917. m.fmut.RLock()
  1918. runner, ok := m.folderRunners[folder]
  1919. m.fmut.RUnlock()
  1920. if !ok {
  1921. // The returned error should be an actual folder error, so returning
  1922. // errors.New("does not exist") or similar here would be
  1923. // inappropriate.
  1924. return "", time.Time{}, nil
  1925. }
  1926. state, changed, err := runner.getState()
  1927. return state.String(), changed, err
  1928. }
  1929. func (m *Model) PullErrors(folder string) ([]FileError, error) {
  1930. m.fmut.RLock()
  1931. defer m.fmut.RUnlock()
  1932. if err := m.checkFolderRunningLocked(folder); err != nil {
  1933. return nil, err
  1934. }
  1935. return m.folderRunners[folder].PullErrors(), nil
  1936. }
  1937. func (m *Model) WatchError(folder string) error {
  1938. m.fmut.RLock()
  1939. defer m.fmut.RUnlock()
  1940. if err := m.checkFolderRunningLocked(folder); err != nil {
  1941. return err
  1942. }
  1943. return m.folderRunners[folder].WatchError()
  1944. }
  1945. func (m *Model) Override(folder string) {
  1946. m.fmut.RLock()
  1947. fs, ok := m.folderFiles[folder]
  1948. runner := m.folderRunners[folder]
  1949. m.fmut.RUnlock()
  1950. if !ok {
  1951. return
  1952. }
  1953. runner.setState(FolderScanning)
  1954. batch := make([]protocol.FileInfo, 0, maxBatchSizeFiles)
  1955. batchSizeBytes := 0
  1956. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1957. need := fi.(protocol.FileInfo)
  1958. if len(batch) == maxBatchSizeFiles || batchSizeBytes > maxBatchSizeBytes {
  1959. m.updateLocalsFromScanning(folder, batch)
  1960. batch = batch[:0]
  1961. batchSizeBytes = 0
  1962. }
  1963. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1964. // Don't override invalid (e.g. ignored) files
  1965. if ok && have.Invalid {
  1966. return true
  1967. }
  1968. if !ok || have.Name != need.Name {
  1969. // We are missing the file
  1970. need.Deleted = true
  1971. need.Blocks = nil
  1972. need.Version = need.Version.Update(m.shortID)
  1973. need.Size = 0
  1974. } else {
  1975. // We have the file, replace with our version
  1976. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1977. need = have
  1978. }
  1979. need.Sequence = 0
  1980. batch = append(batch, need)
  1981. batchSizeBytes += need.ProtoSize()
  1982. return true
  1983. })
  1984. if len(batch) > 0 {
  1985. m.updateLocalsFromScanning(folder, batch)
  1986. }
  1987. runner.setState(FolderIdle)
  1988. }
  1989. // CurrentSequence returns the change version for the given folder.
  1990. // This is guaranteed to increment if the contents of the local folder has
  1991. // changed.
  1992. func (m *Model) CurrentSequence(folder string) (int64, bool) {
  1993. m.fmut.RLock()
  1994. fs, ok := m.folderFiles[folder]
  1995. m.fmut.RUnlock()
  1996. if !ok {
  1997. // The folder might not exist, since this can be called with a user
  1998. // specified folder name from the REST interface.
  1999. return 0, false
  2000. }
  2001. return fs.Sequence(protocol.LocalDeviceID), true
  2002. }
  2003. // RemoteSequence returns the change version for the given folder, as
  2004. // sent by remote peers. This is guaranteed to increment if the contents of
  2005. // the remote or global folder has changed.
  2006. func (m *Model) RemoteSequence(folder string) (int64, bool) {
  2007. m.fmut.RLock()
  2008. defer m.fmut.RUnlock()
  2009. fs, ok := m.folderFiles[folder]
  2010. if !ok {
  2011. // The folder might not exist, since this can be called with a user
  2012. // specified folder name from the REST interface.
  2013. return 0, false
  2014. }
  2015. var ver int64
  2016. for device := range m.folderDevices[folder] {
  2017. ver += fs.Sequence(device)
  2018. }
  2019. return ver, true
  2020. }
  2021. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  2022. m.fmut.RLock()
  2023. files, ok := m.folderFiles[folder]
  2024. m.fmut.RUnlock()
  2025. if !ok {
  2026. return nil
  2027. }
  2028. output := make(map[string]interface{})
  2029. sep := string(filepath.Separator)
  2030. prefix = osutil.NativeFilename(prefix)
  2031. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  2032. prefix = prefix + sep
  2033. }
  2034. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  2035. f := fi.(db.FileInfoTruncated)
  2036. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  2037. return true
  2038. }
  2039. f.Name = strings.Replace(f.Name, prefix, "", 1)
  2040. var dir, base string
  2041. if f.IsDirectory() && !f.IsSymlink() {
  2042. dir = f.Name
  2043. } else {
  2044. dir = filepath.Dir(f.Name)
  2045. base = filepath.Base(f.Name)
  2046. }
  2047. if levels > -1 && strings.Count(f.Name, sep) > levels {
  2048. return true
  2049. }
  2050. last := output
  2051. if dir != "." {
  2052. for _, path := range strings.Split(dir, sep) {
  2053. directory, ok := last[path]
  2054. if !ok {
  2055. newdir := make(map[string]interface{})
  2056. last[path] = newdir
  2057. last = newdir
  2058. } else {
  2059. last = directory.(map[string]interface{})
  2060. }
  2061. }
  2062. }
  2063. if !dirsonly && base != "" {
  2064. last[base] = []interface{}{
  2065. f.ModTime(), f.FileSize(),
  2066. }
  2067. }
  2068. return true
  2069. })
  2070. return output
  2071. }
  2072. func (m *Model) GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error) {
  2073. fcfg, ok := m.cfg.Folder(folder)
  2074. if !ok {
  2075. return nil, errFolderMissing
  2076. }
  2077. files := make(map[string][]versioner.FileVersion)
  2078. filesystem := fcfg.Filesystem()
  2079. err := filesystem.Walk(".stversions", func(path string, f fs.FileInfo, err error) error {
  2080. // Skip root (which is ok to be a symlink)
  2081. if path == ".stversions" {
  2082. return nil
  2083. }
  2084. // Ignore symlinks
  2085. if f.IsSymlink() {
  2086. return fs.SkipDir
  2087. }
  2088. // No records for directories
  2089. if f.IsDir() {
  2090. return nil
  2091. }
  2092. // Strip .stversions prefix.
  2093. path = strings.TrimPrefix(path, ".stversions"+string(fs.PathSeparator))
  2094. name, tag := versioner.UntagFilename(path)
  2095. // Something invalid
  2096. if name == "" || tag == "" {
  2097. return nil
  2098. }
  2099. name = osutil.NormalizedFilename(name)
  2100. versionTime, err := time.ParseInLocation(versioner.TimeFormat, tag, locationLocal)
  2101. if err != nil {
  2102. return nil
  2103. }
  2104. files[name] = append(files[name], versioner.FileVersion{
  2105. VersionTime: versionTime.Truncate(time.Second),
  2106. ModTime: f.ModTime().Truncate(time.Second),
  2107. Size: f.Size(),
  2108. })
  2109. return nil
  2110. })
  2111. if err != nil {
  2112. return nil, err
  2113. }
  2114. return files, nil
  2115. }
  2116. func (m *Model) RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]string, error) {
  2117. fcfg, ok := m.cfg.Folder(folder)
  2118. if !ok {
  2119. return nil, errFolderMissing
  2120. }
  2121. filesystem := fcfg.Filesystem()
  2122. ver := fcfg.Versioner()
  2123. restore := make(map[string]string)
  2124. errors := make(map[string]string)
  2125. // Validation
  2126. for file, version := range versions {
  2127. file = osutil.NativeFilename(file)
  2128. tag := version.In(locationLocal).Truncate(time.Second).Format(versioner.TimeFormat)
  2129. versionedTaggedFilename := filepath.Join(".stversions", versioner.TagFilename(file, tag))
  2130. // Check that the thing we've been asked to restore is actually a file
  2131. // and that it exists.
  2132. if info, err := filesystem.Lstat(versionedTaggedFilename); err != nil {
  2133. errors[file] = err.Error()
  2134. continue
  2135. } else if !info.IsRegular() {
  2136. errors[file] = "not a file"
  2137. continue
  2138. }
  2139. // Check that the target location of where we are supposed to restore
  2140. // either does not exist, or is actually a file.
  2141. if info, err := filesystem.Lstat(file); err == nil && !info.IsRegular() {
  2142. errors[file] = "cannot replace a non-file"
  2143. continue
  2144. } else if err != nil && !fs.IsNotExist(err) {
  2145. errors[file] = err.Error()
  2146. continue
  2147. }
  2148. restore[file] = versionedTaggedFilename
  2149. }
  2150. // Execution
  2151. var err error
  2152. for target, source := range restore {
  2153. err = nil
  2154. if _, serr := filesystem.Lstat(target); serr == nil {
  2155. if ver != nil {
  2156. err = osutil.InWritableDir(ver.Archive, filesystem, target)
  2157. } else {
  2158. err = osutil.InWritableDir(filesystem.Remove, filesystem, target)
  2159. }
  2160. }
  2161. filesystem.MkdirAll(filepath.Dir(target), 0755)
  2162. if err == nil {
  2163. err = osutil.Copy(filesystem, source, target)
  2164. }
  2165. if err != nil {
  2166. errors[target] = err.Error()
  2167. continue
  2168. }
  2169. }
  2170. // Trigger scan
  2171. if !fcfg.FSWatcherEnabled {
  2172. m.ScanFolder(folder)
  2173. }
  2174. return errors, nil
  2175. }
  2176. func (m *Model) Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) []Availability {
  2177. // The slightly unusual locking sequence here is because we need to hold
  2178. // pmut for the duration (as the value returned from foldersFiles can
  2179. // get heavily modified on Close()), but also must acquire fmut before
  2180. // pmut. (The locks can be *released* in any order.)
  2181. m.fmut.RLock()
  2182. m.pmut.RLock()
  2183. defer m.pmut.RUnlock()
  2184. fs, ok := m.folderFiles[folder]
  2185. devices := m.folderDevices[folder]
  2186. m.fmut.RUnlock()
  2187. if !ok {
  2188. return nil
  2189. }
  2190. var availabilities []Availability
  2191. next:
  2192. for _, device := range fs.Availability(file.Name) {
  2193. for _, pausedFolder := range m.remotePausedFolders[device] {
  2194. if pausedFolder == folder {
  2195. continue next
  2196. }
  2197. }
  2198. _, ok := m.conn[device]
  2199. if ok {
  2200. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  2201. }
  2202. }
  2203. for device := range devices {
  2204. if m.deviceDownloads[device].Has(folder, file.Name, file.Version, int32(block.Offset/int64(file.BlockSize()))) {
  2205. availabilities = append(availabilities, Availability{ID: device, FromTemporary: true})
  2206. }
  2207. }
  2208. return availabilities
  2209. }
  2210. // BringToFront bumps the given files priority in the job queue.
  2211. func (m *Model) BringToFront(folder, file string) {
  2212. m.pmut.RLock()
  2213. defer m.pmut.RUnlock()
  2214. runner, ok := m.folderRunners[folder]
  2215. if ok {
  2216. runner.BringToFront(file)
  2217. }
  2218. }
  2219. func (m *Model) ResetFolder(folder string) {
  2220. l.Infof("Cleaning data for folder %q", folder)
  2221. db.DropFolder(m.db, folder)
  2222. }
  2223. func (m *Model) String() string {
  2224. return fmt.Sprintf("model@%p", m)
  2225. }
  2226. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  2227. return nil
  2228. }
  2229. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  2230. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  2231. // Go through the folder configs and figure out if we need to restart or not.
  2232. fromFolders := mapFolders(from.Folders)
  2233. toFolders := mapFolders(to.Folders)
  2234. for folderID, cfg := range toFolders {
  2235. if _, ok := fromFolders[folderID]; !ok {
  2236. // A folder was added.
  2237. if cfg.Paused {
  2238. l.Infoln("Paused folder", cfg.Description())
  2239. cfg.CreateRoot()
  2240. } else {
  2241. l.Infoln("Adding folder", cfg.Description())
  2242. m.AddFolder(cfg)
  2243. m.StartFolder(folderID)
  2244. }
  2245. }
  2246. }
  2247. for folderID, fromCfg := range fromFolders {
  2248. toCfg, ok := toFolders[folderID]
  2249. if !ok {
  2250. // The folder was removed.
  2251. m.RemoveFolder(fromCfg)
  2252. continue
  2253. }
  2254. // This folder exists on both sides. Settings might have changed.
  2255. // Check if anything differs that requires a restart.
  2256. if !reflect.DeepEqual(fromCfg.RequiresRestartOnly(), toCfg.RequiresRestartOnly()) {
  2257. m.RestartFolder(toCfg)
  2258. }
  2259. // Emit the folder pause/resume event
  2260. if fromCfg.Paused != toCfg.Paused {
  2261. eventType := events.FolderResumed
  2262. if toCfg.Paused {
  2263. eventType = events.FolderPaused
  2264. }
  2265. events.Default.Log(eventType, map[string]string{"id": toCfg.ID, "label": toCfg.Label})
  2266. }
  2267. }
  2268. // Removing a device. We actually don't need to do anything.
  2269. // Because folder config has changed (since the device lists do not match)
  2270. // Folders for that had device got "restarted", which involves killing
  2271. // connections to all devices that we were sharing the folder with.
  2272. // At some point model.Close() will get called for that device which will
  2273. // clean residue device state that is not part of any folder.
  2274. // Pausing a device, unpausing is handled by the connection service.
  2275. fromDevices := from.DeviceMap()
  2276. toDevices := to.DeviceMap()
  2277. for deviceID, toCfg := range toDevices {
  2278. fromCfg, ok := fromDevices[deviceID]
  2279. if !ok || fromCfg.Paused == toCfg.Paused {
  2280. continue
  2281. }
  2282. if toCfg.Paused {
  2283. l.Infoln("Pausing", deviceID)
  2284. m.close(deviceID)
  2285. events.Default.Log(events.DevicePaused, map[string]string{"device": deviceID.String()})
  2286. } else {
  2287. events.Default.Log(events.DeviceResumed, map[string]string{"device": deviceID.String()})
  2288. }
  2289. }
  2290. // Some options don't require restart as those components handle it fine
  2291. // by themselves. Compare the options structs containing only the
  2292. // attributes that require restart and act apprioriately.
  2293. if !reflect.DeepEqual(from.Options.RequiresRestartOnly(), to.Options.RequiresRestartOnly()) {
  2294. l.Debugln(m, "requires restart, options differ")
  2295. return false
  2296. }
  2297. return true
  2298. }
  2299. // checkFolderRunningLocked returns nil if the folder is up and running and a
  2300. // descriptive error if not.
  2301. // Need to hold (read) lock on m.fmut when calling this.
  2302. func (m *Model) checkFolderRunningLocked(folder string) error {
  2303. _, ok := m.folderRunners[folder]
  2304. if ok {
  2305. return nil
  2306. }
  2307. if cfg, ok := m.cfg.Folder(folder); !ok {
  2308. return errFolderMissing
  2309. } else if cfg.Paused {
  2310. return ErrFolderPaused
  2311. }
  2312. return errFolderNotRunning
  2313. }
  2314. // checkFolderDeviceStatusLocked first checks the folder and then whether the
  2315. // given device is connected and shares this folder.
  2316. // Need to hold (read) lock on both m.fmut and m.pmut when calling this.
  2317. func (m *Model) checkDeviceFolderConnectedLocked(device protocol.DeviceID, folder string) error {
  2318. if err := m.checkFolderRunningLocked(folder); err != nil {
  2319. return err
  2320. }
  2321. if cfg, ok := m.cfg.Device(device); !ok {
  2322. return errDeviceUnknown
  2323. } else if cfg.Paused {
  2324. return errDevicePaused
  2325. }
  2326. if _, ok := m.conn[device]; !ok {
  2327. return errors.New("device is not connected")
  2328. }
  2329. if !m.folderDevices.has(device, folder) {
  2330. return errors.New("folder is not shared with device")
  2331. }
  2332. return nil
  2333. }
  2334. // mapFolders returns a map of folder ID to folder configuration for the given
  2335. // slice of folder configurations.
  2336. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  2337. m := make(map[string]config.FolderConfiguration, len(folders))
  2338. for _, cfg := range folders {
  2339. m[cfg.ID] = cfg
  2340. }
  2341. return m
  2342. }
  2343. // mapDevices returns a map of device ID to nothing for the given slice of
  2344. // device IDs.
  2345. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  2346. m := make(map[protocol.DeviceID]struct{}, len(devices))
  2347. for _, dev := range devices {
  2348. m[dev] = struct{}{}
  2349. }
  2350. return m
  2351. }
  2352. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  2353. // Returns the resulting slice, plus how much elements are left to skip or
  2354. // copy to satisfy the values which were provided, given the slice is not
  2355. // big enough.
  2356. func getChunk(data []string, skip, get int) ([]string, int, int) {
  2357. l := len(data)
  2358. if l <= skip {
  2359. return []string{}, skip - l, get
  2360. } else if l < skip+get {
  2361. return data[skip:l], 0, get - (l - skip)
  2362. }
  2363. return data[skip : skip+get], 0, 0
  2364. }
  2365. func closeRawConn(conn io.Closer) error {
  2366. if conn, ok := conn.(*tls.Conn); ok {
  2367. // If the underlying connection is a *tls.Conn, Close() does more
  2368. // than it says on the tin. Specifically, it sends a TLS alert
  2369. // message, which might block forever if the connection is dead
  2370. // and we don't have a deadline set.
  2371. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  2372. }
  2373. return conn.Close()
  2374. }
  2375. func stringSliceWithout(ss []string, s string) []string {
  2376. for i := range ss {
  2377. if ss[i] == s {
  2378. copy(ss[i:], ss[i+1:])
  2379. ss = ss[:len(ss)-1]
  2380. return ss
  2381. }
  2382. }
  2383. return ss
  2384. }
  2385. func readOffsetIntoBuf(fs fs.Filesystem, file string, offset int64, buf []byte) error {
  2386. fd, err := fs.Open(file)
  2387. if err != nil {
  2388. l.Debugln("readOffsetIntoBuf.Open", file, err)
  2389. return err
  2390. }
  2391. defer fd.Close()
  2392. _, err = fd.ReadAt(buf, offset)
  2393. if err != nil {
  2394. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  2395. }
  2396. return err
  2397. }
  2398. // The exists function is expected to return true for all known paths
  2399. // (excluding "" and ".")
  2400. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  2401. if len(dirs) == 0 {
  2402. return nil
  2403. }
  2404. sort.Strings(dirs)
  2405. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  2406. return nil
  2407. }
  2408. prev := "./" // Anything that can't be parent of a clean path
  2409. for i := 0; i < len(dirs); {
  2410. dir, err := fs.Canonicalize(dirs[i])
  2411. if err != nil {
  2412. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  2413. dirs = append(dirs[:i], dirs[i+1:]...)
  2414. continue
  2415. }
  2416. if dir == prev || strings.HasPrefix(dir, prev+string(fs.PathSeparator)) {
  2417. dirs = append(dirs[:i], dirs[i+1:]...)
  2418. continue
  2419. }
  2420. parent := filepath.Dir(dir)
  2421. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  2422. dir = parent
  2423. parent = filepath.Dir(dir)
  2424. }
  2425. dirs[i] = dir
  2426. prev = dir
  2427. i++
  2428. }
  2429. return dirs
  2430. }
  2431. // makeForgetUpdate takes an index update and constructs a download progress update
  2432. // causing to forget any progress for files which we've just been sent.
  2433. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  2434. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  2435. for _, file := range files {
  2436. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  2437. continue
  2438. }
  2439. updates = append(updates, protocol.FileDownloadProgressUpdate{
  2440. Name: file.Name,
  2441. Version: file.Version,
  2442. UpdateType: protocol.UpdateTypeForget,
  2443. })
  2444. }
  2445. return updates
  2446. }
  2447. // folderDeviceSet is a set of (folder, deviceID) pairs
  2448. type folderDeviceSet map[string]map[protocol.DeviceID]struct{}
  2449. // set adds the (dev, folder) pair to the set
  2450. func (s folderDeviceSet) set(dev protocol.DeviceID, folder string) {
  2451. devs, ok := s[folder]
  2452. if !ok {
  2453. devs = make(map[protocol.DeviceID]struct{})
  2454. s[folder] = devs
  2455. }
  2456. devs[dev] = struct{}{}
  2457. }
  2458. // has returns true if the (dev, folder) pair is in the set
  2459. func (s folderDeviceSet) has(dev protocol.DeviceID, folder string) bool {
  2460. _, ok := s[folder][dev]
  2461. return ok
  2462. }
  2463. // hasDevice returns true if the device is set on any folder
  2464. func (s folderDeviceSet) hasDevice(dev protocol.DeviceID) bool {
  2465. for _, devices := range s {
  2466. if _, ok := devices[dev]; ok {
  2467. return true
  2468. }
  2469. }
  2470. return false
  2471. }
  2472. // sortedDevices returns the list of devices for a given folder, sorted
  2473. func (s folderDeviceSet) sortedDevices(folder string) []protocol.DeviceID {
  2474. devs := make([]protocol.DeviceID, 0, len(s[folder]))
  2475. for dev := range s[folder] {
  2476. devs = append(devs, dev)
  2477. }
  2478. sort.Sort(protocol.DeviceIDs(devs))
  2479. return devs
  2480. }