model.go 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407
  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 http://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bufio"
  9. "bytes"
  10. "crypto/tls"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "os"
  17. "path/filepath"
  18. "reflect"
  19. "runtime"
  20. "sort"
  21. "strings"
  22. stdsync "sync"
  23. "time"
  24. "github.com/syncthing/syncthing/lib/config"
  25. "github.com/syncthing/syncthing/lib/connections"
  26. "github.com/syncthing/syncthing/lib/db"
  27. "github.com/syncthing/syncthing/lib/events"
  28. "github.com/syncthing/syncthing/lib/ignore"
  29. "github.com/syncthing/syncthing/lib/osutil"
  30. "github.com/syncthing/syncthing/lib/protocol"
  31. "github.com/syncthing/syncthing/lib/scanner"
  32. "github.com/syncthing/syncthing/lib/stats"
  33. "github.com/syncthing/syncthing/lib/symlinks"
  34. "github.com/syncthing/syncthing/lib/sync"
  35. "github.com/syncthing/syncthing/lib/versioner"
  36. "github.com/thejerf/suture"
  37. )
  38. // How many files to send in each Index/IndexUpdate message.
  39. const (
  40. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  41. indexBatchSize = 1000 // Either way, don't include more files than this
  42. )
  43. type service interface {
  44. BringToFront(string)
  45. DelayScan(d time.Duration)
  46. IndexUpdated() // Remote index was updated notification
  47. Jobs() ([]string, []string) // In progress, Queued
  48. Scan(subs []string) error
  49. Serve()
  50. Stop()
  51. getState() (folderState, time.Time, error)
  52. setState(state folderState)
  53. clearError()
  54. setError(err error)
  55. }
  56. type Availability struct {
  57. ID protocol.DeviceID `json:"id"`
  58. FromTemporary bool `json:"fromTemporary"`
  59. }
  60. type Model struct {
  61. *suture.Supervisor
  62. cfg *config.Wrapper
  63. db *db.Instance
  64. finder *db.BlockFinder
  65. progressEmitter *ProgressEmitter
  66. id protocol.DeviceID
  67. shortID protocol.ShortID
  68. cacheIgnoredFiles bool
  69. protectedFiles []string
  70. deviceName string
  71. clientName string
  72. clientVersion string
  73. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  74. folderFiles map[string]*db.FileSet // folder -> files
  75. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  76. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  77. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  78. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  79. folderRunners map[string]service // folder -> puller or scanner
  80. folderRunnerTokens map[string][]suture.ServiceToken // folder -> tokens for puller or scanner
  81. folderStatRefs map[string]*stats.FolderStatisticsReference // folder -> statsRef
  82. fmut sync.RWMutex // protects the above
  83. conn map[protocol.DeviceID]connections.Connection
  84. helloMessages map[protocol.DeviceID]protocol.HelloResult
  85. deviceClusterConf map[protocol.DeviceID]protocol.ClusterConfig
  86. devicePaused map[protocol.DeviceID]bool
  87. deviceDownloads map[protocol.DeviceID]*deviceDownloadState
  88. pmut sync.RWMutex // protects the above
  89. }
  90. type folderFactory func(*Model, config.FolderConfiguration, versioner.Versioner) service
  91. var (
  92. symlinkWarning = stdsync.Once{}
  93. folderFactories = make(map[config.FolderType]folderFactory, 0)
  94. )
  95. // errors returned by the CheckFolderHealth method
  96. var (
  97. errFolderPathEmpty = errors.New("folder path empty")
  98. errFolderPathMissing = errors.New("folder path missing")
  99. errFolderMarkerMissing = errors.New("folder marker missing")
  100. errHomeDiskNoSpace = errors.New("home disk has insufficient free space")
  101. errFolderNoSpace = errors.New("folder has insufficient free space")
  102. errUnsupportedSymlink = errors.New("symlink not supported")
  103. errInvalidFilename = errors.New("filename is invalid")
  104. )
  105. // NewModel creates and starts a new model. The model starts in read-only mode,
  106. // where it sends index information to connected peers and responds to requests
  107. // for file data without altering the local folder in any way.
  108. func NewModel(cfg *config.Wrapper, id protocol.DeviceID, deviceName, clientName, clientVersion string, ldb *db.Instance, protectedFiles []string) *Model {
  109. m := &Model{
  110. Supervisor: suture.New("model", suture.Spec{
  111. Log: func(line string) {
  112. l.Debugln(line)
  113. },
  114. }),
  115. cfg: cfg,
  116. db: ldb,
  117. finder: db.NewBlockFinder(ldb),
  118. progressEmitter: NewProgressEmitter(cfg),
  119. id: id,
  120. shortID: id.Short(),
  121. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  122. protectedFiles: protectedFiles,
  123. deviceName: deviceName,
  124. clientName: clientName,
  125. clientVersion: clientVersion,
  126. folderCfgs: make(map[string]config.FolderConfiguration),
  127. folderFiles: make(map[string]*db.FileSet),
  128. folderDevices: make(map[string][]protocol.DeviceID),
  129. deviceFolders: make(map[protocol.DeviceID][]string),
  130. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  131. folderIgnores: make(map[string]*ignore.Matcher),
  132. folderRunners: make(map[string]service),
  133. folderRunnerTokens: make(map[string][]suture.ServiceToken),
  134. folderStatRefs: make(map[string]*stats.FolderStatisticsReference),
  135. conn: make(map[protocol.DeviceID]connections.Connection),
  136. helloMessages: make(map[protocol.DeviceID]protocol.HelloResult),
  137. deviceClusterConf: make(map[protocol.DeviceID]protocol.ClusterConfig),
  138. devicePaused: make(map[protocol.DeviceID]bool),
  139. deviceDownloads: make(map[protocol.DeviceID]*deviceDownloadState),
  140. fmut: sync.NewRWMutex(),
  141. pmut: sync.NewRWMutex(),
  142. }
  143. if cfg.Options().ProgressUpdateIntervalS > -1 {
  144. go m.progressEmitter.Serve()
  145. }
  146. return m
  147. }
  148. // StartDeadlockDetector starts a deadlock detector on the models locks which
  149. // causes panics in case the locks cannot be acquired in the given timeout
  150. // period.
  151. func (m *Model) StartDeadlockDetector(timeout time.Duration) {
  152. l.Infof("Starting deadlock detector with %v timeout", timeout)
  153. deadlockDetect(m.fmut, timeout)
  154. deadlockDetect(m.pmut, timeout)
  155. }
  156. // StartFolder constructs the folder service and starts it.
  157. func (m *Model) StartFolder(folder string) {
  158. m.fmut.Lock()
  159. cfg, ok := m.folderCfgs[folder]
  160. if !ok {
  161. panic("cannot start nonexistent folder " + folder)
  162. }
  163. _, ok = m.folderRunners[folder]
  164. if ok {
  165. panic("cannot start already running folder " + folder)
  166. }
  167. folderFactory, ok := folderFactories[cfg.Type]
  168. if !ok {
  169. panic(fmt.Sprintf("unknown folder type 0x%x", cfg.Type))
  170. }
  171. fs := m.folderFiles[folder]
  172. v, ok := fs.Sequence(protocol.LocalDeviceID), true
  173. indexHasFiles := ok && v > 0
  174. if !indexHasFiles {
  175. // It's a blank folder, so this may the first time we're looking at
  176. // it. Attempt to create and tag with our marker as appropriate. We
  177. // don't really do anything with errors at this point except warn -
  178. // if these things don't work, we still want to start the folder and
  179. // it'll show up as errored later.
  180. if _, err := os.Stat(cfg.Path()); os.IsNotExist(err) {
  181. if err := osutil.MkdirAll(cfg.Path(), 0700); err != nil {
  182. l.Warnln("Creating folder:", err)
  183. }
  184. }
  185. if err := cfg.CreateMarker(); err != nil {
  186. l.Warnln("Creating folder marker:", err)
  187. }
  188. }
  189. var ver versioner.Versioner
  190. if len(cfg.Versioning.Type) > 0 {
  191. versionerFactory, ok := versioner.Factories[cfg.Versioning.Type]
  192. if !ok {
  193. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  194. }
  195. ver = versionerFactory(folder, cfg.Path(), cfg.Versioning.Params)
  196. if service, ok := ver.(suture.Service); ok {
  197. // The versioner implements the suture.Service interface, so
  198. // expects to be run in the background in addition to being called
  199. // when files are going to be archived.
  200. token := m.Add(service)
  201. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  202. }
  203. }
  204. p := folderFactory(m, cfg, ver)
  205. m.folderRunners[folder] = p
  206. m.warnAboutOverwritingProtectedFiles(folder)
  207. token := m.Add(p)
  208. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  209. m.fmut.Unlock()
  210. l.Infoln("Ready to synchronize", folder, fmt.Sprintf("(%s)", cfg.Type))
  211. }
  212. func (m *Model) warnAboutOverwritingProtectedFiles(folder string) {
  213. if m.folderCfgs[folder].Type == config.FolderTypeReadOnly {
  214. return
  215. }
  216. folderLocation := m.folderCfgs[folder].Path()
  217. ignores := m.folderIgnores[folder]
  218. var filesAtRisk []string
  219. for _, protectedFilePath := range m.protectedFiles {
  220. // check if file is synced in this folder
  221. if !strings.HasPrefix(protectedFilePath, folderLocation) {
  222. continue
  223. }
  224. // check if file is ignored
  225. if ignores.Match(protectedFilePath).IsIgnored() {
  226. continue
  227. }
  228. filesAtRisk = append(filesAtRisk, protectedFilePath)
  229. }
  230. if len(filesAtRisk) > 0 {
  231. l.Warnln("Some protected files may be overwritten and cause issues. See http://docs.syncthing.net/users/config.html#syncing-configuration-files for more information. The at risk files are:", strings.Join(filesAtRisk, ", "))
  232. }
  233. }
  234. func (m *Model) RemoveFolder(folder string) {
  235. m.fmut.Lock()
  236. m.pmut.Lock()
  237. // Stop the services running for this folder
  238. for _, id := range m.folderRunnerTokens[folder] {
  239. m.Remove(id)
  240. }
  241. // Close connections to affected devices
  242. for _, dev := range m.folderDevices[folder] {
  243. if conn, ok := m.conn[dev]; ok {
  244. closeRawConn(conn)
  245. }
  246. }
  247. // Clean up our config maps
  248. delete(m.folderCfgs, folder)
  249. delete(m.folderFiles, folder)
  250. delete(m.folderDevices, folder)
  251. delete(m.folderIgnores, folder)
  252. delete(m.folderRunners, folder)
  253. delete(m.folderRunnerTokens, folder)
  254. delete(m.folderStatRefs, folder)
  255. for dev, folders := range m.deviceFolders {
  256. m.deviceFolders[dev] = stringSliceWithout(folders, folder)
  257. }
  258. // Remove it from the database
  259. db.DropFolder(m.db, folder)
  260. m.pmut.Unlock()
  261. m.fmut.Unlock()
  262. }
  263. type ConnectionInfo struct {
  264. protocol.Statistics
  265. Connected bool
  266. Paused bool
  267. Address string
  268. ClientVersion string
  269. Type string
  270. }
  271. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  272. return json.Marshal(map[string]interface{}{
  273. "at": info.At,
  274. "inBytesTotal": info.InBytesTotal,
  275. "outBytesTotal": info.OutBytesTotal,
  276. "connected": info.Connected,
  277. "paused": info.Paused,
  278. "address": info.Address,
  279. "clientVersion": info.ClientVersion,
  280. "type": info.Type,
  281. })
  282. }
  283. // ConnectionStats returns a map with connection statistics for each device.
  284. func (m *Model) ConnectionStats() map[string]interface{} {
  285. m.pmut.RLock()
  286. m.fmut.RLock()
  287. res := make(map[string]interface{})
  288. devs := m.cfg.Devices()
  289. conns := make(map[string]ConnectionInfo, len(devs))
  290. for device := range devs {
  291. hello := m.helloMessages[device]
  292. versionString := hello.ClientVersion
  293. if hello.ClientName != "syncthing" {
  294. versionString = hello.ClientName + " " + hello.ClientVersion
  295. }
  296. ci := ConnectionInfo{
  297. ClientVersion: strings.TrimSpace(versionString),
  298. Paused: m.devicePaused[device],
  299. }
  300. if conn, ok := m.conn[device]; ok {
  301. ci.Type = conn.Type
  302. ci.Connected = ok
  303. ci.Statistics = conn.Statistics()
  304. if addr := conn.RemoteAddr(); addr != nil {
  305. ci.Address = addr.String()
  306. }
  307. }
  308. conns[device.String()] = ci
  309. }
  310. res["connections"] = conns
  311. m.fmut.RUnlock()
  312. m.pmut.RUnlock()
  313. in, out := protocol.TotalInOut()
  314. res["total"] = ConnectionInfo{
  315. Statistics: protocol.Statistics{
  316. At: time.Now(),
  317. InBytesTotal: in,
  318. OutBytesTotal: out,
  319. },
  320. }
  321. return res
  322. }
  323. // DeviceStatistics returns statistics about each device
  324. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  325. var res = make(map[string]stats.DeviceStatistics)
  326. for id := range m.cfg.Devices() {
  327. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  328. }
  329. return res
  330. }
  331. // FolderStatistics returns statistics about each folder
  332. func (m *Model) FolderStatistics() map[string]stats.FolderStatistics {
  333. var res = make(map[string]stats.FolderStatistics)
  334. for id := range m.cfg.Folders() {
  335. res[id] = m.folderStatRef(id).GetStatistics()
  336. }
  337. return res
  338. }
  339. // Completion returns the completion status, in percent, for the given device
  340. // and folder.
  341. func (m *Model) Completion(device protocol.DeviceID, folder string) float64 {
  342. m.fmut.RLock()
  343. rf, ok := m.folderFiles[folder]
  344. m.fmut.RUnlock()
  345. if !ok {
  346. return 0 // Folder doesn't exist, so we hardly have any of it
  347. }
  348. _, _, tot := rf.GlobalSize()
  349. if tot == 0 {
  350. return 100 // Folder is empty, so we have all of it
  351. }
  352. m.pmut.RLock()
  353. counts := m.deviceDownloads[device].GetBlockCounts(folder)
  354. m.pmut.RUnlock()
  355. var need, fileNeed, downloaded int64
  356. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  357. ft := f.(db.FileInfoTruncated)
  358. // This might might be more than it really is, because some blocks can be of a smaller size.
  359. downloaded = int64(counts[ft.Name] * protocol.BlockSize)
  360. fileNeed = ft.Size - downloaded
  361. if fileNeed < 0 {
  362. fileNeed = 0
  363. }
  364. need += fileNeed
  365. return true
  366. })
  367. needRatio := float64(need) / float64(tot)
  368. completionPct := 100 * (1 - needRatio)
  369. l.Debugf("%v Completion(%s, %q): %f (%d / %d = %f)", m, device, folder, completionPct, need, tot, needRatio)
  370. return completionPct
  371. }
  372. func sizeOfFile(f db.FileIntf) (files, deleted int, bytes int64) {
  373. if !f.IsDeleted() {
  374. files++
  375. } else {
  376. deleted++
  377. }
  378. bytes += f.FileSize()
  379. return
  380. }
  381. // GlobalSize returns the number of files, deleted files and total bytes for all
  382. // files in the global model.
  383. func (m *Model) GlobalSize(folder string) (nfiles, deleted int, bytes int64) {
  384. m.fmut.RLock()
  385. defer m.fmut.RUnlock()
  386. if rf, ok := m.folderFiles[folder]; ok {
  387. nfiles, deleted, bytes = rf.GlobalSize()
  388. }
  389. return
  390. }
  391. // LocalSize returns the number of files, deleted files and total bytes for all
  392. // files in the local folder.
  393. func (m *Model) LocalSize(folder string) (nfiles, deleted int, bytes int64) {
  394. m.fmut.RLock()
  395. defer m.fmut.RUnlock()
  396. if rf, ok := m.folderFiles[folder]; ok {
  397. nfiles, deleted, bytes = rf.LocalSize()
  398. }
  399. return
  400. }
  401. // NeedSize returns the number and total size of currently needed files.
  402. func (m *Model) NeedSize(folder string) (nfiles int, bytes int64) {
  403. m.fmut.RLock()
  404. defer m.fmut.RUnlock()
  405. if rf, ok := m.folderFiles[folder]; ok {
  406. ignores := m.folderIgnores[folder]
  407. cfg := m.folderCfgs[folder]
  408. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  409. if shouldIgnore(f, ignores, cfg.IgnoreDelete) {
  410. return true
  411. }
  412. fs, de, by := sizeOfFile(f)
  413. nfiles += fs + de
  414. bytes += by
  415. return true
  416. })
  417. }
  418. bytes -= m.progressEmitter.BytesCompleted(folder)
  419. l.Debugf("%v NeedSize(%q): %d %d", m, folder, nfiles, bytes)
  420. return
  421. }
  422. // NeedFolderFiles returns paginated list of currently needed files in
  423. // progress, queued, and to be queued on next puller iteration, as well as the
  424. // total number of files currently needed.
  425. func (m *Model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated, int) {
  426. m.fmut.RLock()
  427. defer m.fmut.RUnlock()
  428. total := 0
  429. rf, ok := m.folderFiles[folder]
  430. if !ok {
  431. return nil, nil, nil, 0
  432. }
  433. var progress, queued, rest []db.FileInfoTruncated
  434. var seen map[string]struct{}
  435. skip := (page - 1) * perpage
  436. get := perpage
  437. runner, ok := m.folderRunners[folder]
  438. if ok {
  439. allProgressNames, allQueuedNames := runner.Jobs()
  440. var progressNames, queuedNames []string
  441. progressNames, skip, get = getChunk(allProgressNames, skip, get)
  442. queuedNames, skip, get = getChunk(allQueuedNames, skip, get)
  443. progress = make([]db.FileInfoTruncated, len(progressNames))
  444. queued = make([]db.FileInfoTruncated, len(queuedNames))
  445. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  446. for i, name := range progressNames {
  447. if f, ok := rf.GetGlobalTruncated(name); ok {
  448. progress[i] = f
  449. seen[name] = struct{}{}
  450. }
  451. }
  452. for i, name := range queuedNames {
  453. if f, ok := rf.GetGlobalTruncated(name); ok {
  454. queued[i] = f
  455. seen[name] = struct{}{}
  456. }
  457. }
  458. }
  459. rest = make([]db.FileInfoTruncated, 0, perpage)
  460. ignores := m.folderIgnores[folder]
  461. cfg := m.folderCfgs[folder]
  462. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  463. if shouldIgnore(f, ignores, cfg.IgnoreDelete) {
  464. return true
  465. }
  466. total++
  467. if skip > 0 {
  468. skip--
  469. return true
  470. }
  471. if get > 0 {
  472. ft := f.(db.FileInfoTruncated)
  473. if _, ok := seen[ft.Name]; !ok {
  474. rest = append(rest, ft)
  475. get--
  476. }
  477. }
  478. return true
  479. })
  480. return progress, queued, rest, total
  481. }
  482. // Index is called when a new device is connected and we receive their full index.
  483. // Implements the protocol.Model interface.
  484. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  485. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  486. if !m.folderSharedWith(folder, deviceID) {
  487. l.Debugf("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.", folder, deviceID)
  488. return
  489. }
  490. m.fmut.RLock()
  491. files, ok := m.folderFiles[folder]
  492. runner := m.folderRunners[folder]
  493. m.fmut.RUnlock()
  494. if runner != nil {
  495. // Runner may legitimately not be set if this is the "cleanup" Index
  496. // message at startup.
  497. defer runner.IndexUpdated()
  498. }
  499. if !ok {
  500. l.Fatalf("Index for nonexistent folder %q", folder)
  501. }
  502. m.pmut.RLock()
  503. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  504. m.pmut.RUnlock()
  505. files.Replace(deviceID, fs)
  506. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  507. "device": deviceID.String(),
  508. "folder": folder,
  509. "items": len(fs),
  510. "version": files.Sequence(deviceID),
  511. })
  512. }
  513. // IndexUpdate is called for incremental updates to connected devices' indexes.
  514. // Implements the protocol.Model interface.
  515. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  516. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  517. if !m.folderSharedWith(folder, deviceID) {
  518. l.Debugf("Update 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.", folder, deviceID)
  519. return
  520. }
  521. m.fmut.RLock()
  522. files := m.folderFiles[folder]
  523. runner, ok := m.folderRunners[folder]
  524. m.fmut.RUnlock()
  525. if !ok {
  526. l.Fatalf("IndexUpdate for nonexistent folder %q", folder)
  527. }
  528. m.pmut.RLock()
  529. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  530. m.pmut.RUnlock()
  531. files.Update(deviceID, fs)
  532. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  533. "device": deviceID.String(),
  534. "folder": folder,
  535. "items": len(fs),
  536. "version": files.Sequence(deviceID),
  537. })
  538. runner.IndexUpdated()
  539. }
  540. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  541. m.fmut.RLock()
  542. defer m.fmut.RUnlock()
  543. return m.folderSharedWithUnlocked(folder, deviceID)
  544. }
  545. func (m *Model) folderSharedWithUnlocked(folder string, deviceID protocol.DeviceID) bool {
  546. for _, nfolder := range m.deviceFolders[deviceID] {
  547. if nfolder == folder {
  548. return true
  549. }
  550. }
  551. return false
  552. }
  553. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfig) {
  554. // Check the peer device's announced folders against our own. Emits events
  555. // for folders that we don't expect (unknown or not shared).
  556. // Also, collect a list of folders we do share, and if he's interested in
  557. // temporary indexes, subscribe the connection.
  558. tempIndexFolders := make([]string, 0, len(cm.Folders))
  559. m.pmut.RLock()
  560. conn, ok := m.conn[deviceID]
  561. m.pmut.RUnlock()
  562. if !ok {
  563. panic("bug: ClusterConfig called on closed or nonexistent connection")
  564. }
  565. dbLocation := filepath.Dir(m.db.Location())
  566. m.fmut.Lock()
  567. for _, folder := range cm.Folders {
  568. if !m.folderSharedWithUnlocked(folder.ID, deviceID) {
  569. events.Default.Log(events.FolderRejected, map[string]string{
  570. "folder": folder.ID,
  571. "folderLabel": folder.Label,
  572. "device": deviceID.String(),
  573. })
  574. l.Infof("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.", folder.ID, deviceID)
  575. continue
  576. }
  577. if !folder.DisableTempIndexes {
  578. tempIndexFolders = append(tempIndexFolders, folder.ID)
  579. }
  580. fs := m.folderFiles[folder.ID]
  581. myIndexID := fs.IndexID(protocol.LocalDeviceID)
  582. mySequence := fs.Sequence(protocol.LocalDeviceID)
  583. var startSequence int64
  584. for _, dev := range folder.Devices {
  585. if bytes.Equal(dev.ID, m.id[:]) {
  586. // This is the other side's description of what it knows
  587. // about us. Lets check to see if we can start sending index
  588. // updates directly or need to send the index from start...
  589. if dev.IndexID == myIndexID {
  590. // They say they've seen our index ID before, so we can
  591. // send a delta update only.
  592. if dev.MaxSequence > mySequence {
  593. // Safety check. They claim to have more or newer
  594. // index data than we have - either we have lost
  595. // index data, or reset the index without resetting
  596. // the IndexID, or something else weird has
  597. // happened. We send a full index to reset the
  598. // situation.
  599. l.Infof("Device %v folder %q is delta index compatible, but seems out of sync with reality", deviceID, folder.ID)
  600. startSequence = 0
  601. continue
  602. }
  603. l.Infof("Device %v folder %q is delta index compatible (mlv=%d)", deviceID, folder.ID, dev.MaxSequence)
  604. startSequence = dev.MaxSequence
  605. } else if dev.IndexID != 0 {
  606. // They say they've seen an index ID from us, but it's
  607. // not the right one. Either they are confused or we
  608. // must have reset our database since last talking to
  609. // them. We'll start with a full index transfer.
  610. l.Infof("Device %v folder %q has mismatching index ID for us (%v != %v)", deviceID, folder.ID, dev.IndexID, myIndexID)
  611. startSequence = 0
  612. }
  613. } else if bytes.Equal(dev.ID, deviceID[:]) && dev.IndexID != 0 {
  614. // This is the other side's description of themselves. We
  615. // check to see that it matches the IndexID we have on file,
  616. // otherwise we drop our old index data and expect to get a
  617. // completely new set.
  618. theirIndexID := fs.IndexID(deviceID)
  619. if dev.IndexID == 0 {
  620. // They're not announcing an index ID. This means they
  621. // do not support delta indexes and we should clear any
  622. // information we have from them before accepting their
  623. // index, which will presumably be a full index.
  624. fs.Replace(deviceID, nil)
  625. } else if dev.IndexID != theirIndexID {
  626. // The index ID we have on file is not what they're
  627. // announcing. They must have reset their database and
  628. // will probably send us a full index. We drop any
  629. // information we have and remember this new index ID
  630. // instead.
  631. l.Infof("Device %v folder %q has a new index ID (%v)", deviceID, folder.ID, dev.IndexID)
  632. fs.Replace(deviceID, nil)
  633. fs.SetIndexID(deviceID, dev.IndexID)
  634. } else {
  635. // They're sending a recognized index ID and will most
  636. // likely use delta indexes. We might already have files
  637. // that we need to pull so let the folder runner know
  638. // that it should recheck the index data.
  639. if runner := m.folderRunners[folder.ID]; runner != nil {
  640. defer runner.IndexUpdated()
  641. }
  642. }
  643. }
  644. }
  645. go sendIndexes(conn, folder.ID, fs, m.folderIgnores[folder.ID], startSequence, dbLocation)
  646. }
  647. m.fmut.Unlock()
  648. // This breaks if we send multiple CM messages during the same connection.
  649. if len(tempIndexFolders) > 0 {
  650. m.pmut.RLock()
  651. conn, ok := m.conn[deviceID]
  652. m.pmut.RUnlock()
  653. // In case we've got ClusterConfig, and the connection disappeared
  654. // from infront of our nose.
  655. if ok {
  656. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  657. }
  658. }
  659. var changed bool
  660. if m.cfg.Devices()[deviceID].Introducer {
  661. // This device is an introducer. Go through the announced lists of folders
  662. // and devices and add what we are missing.
  663. for _, folder := range cm.Folders {
  664. if _, ok := m.folderDevices[folder.ID]; !ok {
  665. continue
  666. }
  667. nextDevice:
  668. for _, device := range folder.Devices {
  669. var id protocol.DeviceID
  670. copy(id[:], device.ID)
  671. if _, ok := m.cfg.Devices()[id]; !ok {
  672. // The device is currently unknown. Add it to the config.
  673. addresses := []string{"dynamic"}
  674. for _, addr := range device.Addresses {
  675. if addr != "dynamic" {
  676. addresses = append(addresses, addr)
  677. }
  678. }
  679. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  680. newDeviceCfg := config.DeviceConfiguration{
  681. DeviceID: id,
  682. Name: device.Name,
  683. Compression: m.cfg.Devices()[deviceID].Compression,
  684. Addresses: addresses,
  685. CertName: device.CertName,
  686. }
  687. // The introducers' introducers are also our introducers.
  688. if device.Introducer {
  689. l.Infof("Device %v is now also an introducer", id)
  690. newDeviceCfg.Introducer = true
  691. }
  692. m.cfg.SetDevice(newDeviceCfg)
  693. changed = true
  694. }
  695. for _, er := range m.deviceFolders[id] {
  696. if er == folder.ID {
  697. // We already share the folder with this device, so
  698. // nothing to do.
  699. continue nextDevice
  700. }
  701. }
  702. // We don't yet share this folder with this device. Add the device
  703. // to sharing list of the folder.
  704. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  705. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  706. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  707. folderCfg := m.cfg.Folders()[folder.ID]
  708. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  709. DeviceID: id,
  710. })
  711. m.cfg.SetFolder(folderCfg)
  712. changed = true
  713. }
  714. }
  715. }
  716. if changed {
  717. m.cfg.Save()
  718. }
  719. }
  720. // Close removes the peer from the model and closes the underlying connection if possible.
  721. // Implements the protocol.Model interface.
  722. func (m *Model) Close(device protocol.DeviceID, err error) {
  723. l.Infof("Connection to %s closed: %v", device, err)
  724. events.Default.Log(events.DeviceDisconnected, map[string]string{
  725. "id": device.String(),
  726. "error": err.Error(),
  727. })
  728. m.pmut.Lock()
  729. conn, ok := m.conn[device]
  730. if ok {
  731. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  732. closeRawConn(conn)
  733. }
  734. delete(m.conn, device)
  735. delete(m.helloMessages, device)
  736. delete(m.deviceClusterConf, device)
  737. delete(m.deviceDownloads, device)
  738. m.pmut.Unlock()
  739. }
  740. // Request returns the specified data segment by reading it from local disk.
  741. // Implements the protocol.Model interface.
  742. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, fromTemporary bool, buf []byte) error {
  743. if offset < 0 {
  744. return protocol.ErrInvalid
  745. }
  746. if !m.folderSharedWith(folder, deviceID) {
  747. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  748. return protocol.ErrNoSuchFile
  749. }
  750. if deviceID != protocol.LocalDeviceID {
  751. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, len(buf), fromTemporary)
  752. }
  753. m.fmut.RLock()
  754. folderCfg := m.folderCfgs[folder]
  755. folderPath := folderCfg.Path()
  756. folderIgnores := m.folderIgnores[folder]
  757. m.fmut.RUnlock()
  758. // filepath.Join() returns a filepath.Clean()ed path, which (quoting the
  759. // docs for clarity here):
  760. //
  761. // Clean returns the shortest path name equivalent to path by purely lexical
  762. // processing. It applies the following rules iteratively until no further
  763. // processing can be done:
  764. //
  765. // 1. Replace multiple Separator elements with a single one.
  766. // 2. Eliminate each . path name element (the current directory).
  767. // 3. Eliminate each inner .. path name element (the parent directory)
  768. // along with the non-.. element that precedes it.
  769. // 4. Eliminate .. elements that begin a rooted path:
  770. // that is, replace "/.." by "/" at the beginning of a path,
  771. // assuming Separator is '/'.
  772. fn := filepath.Join(folderPath, name)
  773. if !strings.HasPrefix(fn, folderPath) {
  774. // Request tries to escape!
  775. l.Debugf("%v Invalid REQ(in) tries to escape: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  776. return protocol.ErrInvalid
  777. }
  778. if folderIgnores != nil {
  779. // "rn" becomes the relative name of the file within the folder. This is
  780. // different than the original "name" parameter in that it's been
  781. // cleaned from any possible funny business.
  782. if rn, err := filepath.Rel(folderPath, fn); err != nil {
  783. return err
  784. } else if folderIgnores.Match(rn).IsIgnored() {
  785. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  786. return protocol.ErrNoSuchFile
  787. }
  788. }
  789. if info, err := os.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  790. target, _, err := symlinks.Read(fn)
  791. if err != nil {
  792. l.Debugln("symlinks.Read:", err)
  793. if os.IsNotExist(err) {
  794. return protocol.ErrNoSuchFile
  795. }
  796. return protocol.ErrGeneric
  797. }
  798. if _, err := strings.NewReader(target).ReadAt(buf, offset); err != nil {
  799. l.Debugln("symlink.Reader.ReadAt", err)
  800. return protocol.ErrGeneric
  801. }
  802. return nil
  803. }
  804. // Only check temp files if the flag is set, and if we are set to advertise
  805. // the temp indexes.
  806. if fromTemporary && !folderCfg.DisableTempIndexes {
  807. tempFn := filepath.Join(folderPath, defTempNamer.TempName(name))
  808. if err := readOffsetIntoBuf(tempFn, offset, buf); err == nil {
  809. return nil
  810. }
  811. // Fall through to reading from a non-temp file, just incase the temp
  812. // file has finished downloading.
  813. }
  814. err := readOffsetIntoBuf(fn, offset, buf)
  815. if os.IsNotExist(err) {
  816. return protocol.ErrNoSuchFile
  817. } else if err != nil {
  818. return protocol.ErrGeneric
  819. }
  820. return nil
  821. }
  822. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  823. m.fmut.RLock()
  824. fs, ok := m.folderFiles[folder]
  825. m.fmut.RUnlock()
  826. if !ok {
  827. return protocol.FileInfo{}, false
  828. }
  829. f, ok := fs.Get(protocol.LocalDeviceID, file)
  830. return f, ok
  831. }
  832. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  833. m.fmut.RLock()
  834. fs, ok := m.folderFiles[folder]
  835. m.fmut.RUnlock()
  836. if !ok {
  837. return protocol.FileInfo{}, false
  838. }
  839. f, ok := fs.GetGlobal(file)
  840. return f, ok
  841. }
  842. type cFiler struct {
  843. m *Model
  844. r string
  845. }
  846. // Implements scanner.CurrentFiler
  847. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  848. return cf.m.CurrentFolderFile(cf.r, file)
  849. }
  850. // ConnectedTo returns true if we are connected to the named device.
  851. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  852. m.pmut.RLock()
  853. _, ok := m.conn[deviceID]
  854. m.pmut.RUnlock()
  855. if ok {
  856. m.deviceWasSeen(deviceID)
  857. }
  858. return ok
  859. }
  860. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  861. var lines []string
  862. m.fmut.RLock()
  863. cfg, ok := m.folderCfgs[folder]
  864. m.fmut.RUnlock()
  865. if !ok {
  866. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  867. }
  868. if !cfg.HasMarker() {
  869. return lines, nil, fmt.Errorf("Folder %s stopped", folder)
  870. }
  871. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  872. if err != nil {
  873. if os.IsNotExist(err) {
  874. return lines, nil, nil
  875. }
  876. l.Warnln("Loading .stignore:", err)
  877. return lines, nil, err
  878. }
  879. defer fd.Close()
  880. scanner := bufio.NewScanner(fd)
  881. for scanner.Scan() {
  882. lines = append(lines, strings.TrimSpace(scanner.Text()))
  883. }
  884. m.fmut.RLock()
  885. patterns := m.folderIgnores[folder].Patterns()
  886. m.fmut.RUnlock()
  887. return lines, patterns, nil
  888. }
  889. func (m *Model) SetIgnores(folder string, content []string) error {
  890. cfg, ok := m.folderCfgs[folder]
  891. if !ok {
  892. return fmt.Errorf("Folder %s does not exist", folder)
  893. }
  894. path := filepath.Join(cfg.Path(), ".stignore")
  895. fd, err := osutil.CreateAtomic(path, 0644)
  896. if err != nil {
  897. l.Warnln("Saving .stignore:", err)
  898. return err
  899. }
  900. for _, line := range content {
  901. fmt.Fprintln(fd, line)
  902. }
  903. if err := fd.Close(); err != nil {
  904. l.Warnln("Saving .stignore:", err)
  905. return err
  906. }
  907. osutil.HideFile(path)
  908. return m.ScanFolder(folder)
  909. }
  910. // OnHello is called when an device connects to us.
  911. // This allows us to extract some information from the Hello message
  912. // and add it to a list of known devices ahead of any checks.
  913. func (m *Model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloResult) {
  914. for deviceID := range m.cfg.Devices() {
  915. if deviceID == remoteID {
  916. // Existing device, we will get the hello message in AddConnection
  917. // hence do not persist any state here, as the connection might
  918. // get killed before AddConnection
  919. return
  920. }
  921. }
  922. if !m.cfg.IgnoredDevice(remoteID) {
  923. events.Default.Log(events.DeviceRejected, map[string]string{
  924. "name": hello.DeviceName,
  925. "device": remoteID.String(),
  926. "address": addr.String(),
  927. })
  928. }
  929. }
  930. // GetHello is called when we are about to connect to some remote device.
  931. func (m *Model) GetHello(protocol.DeviceID) protocol.HelloIntf {
  932. return &protocol.Hello{
  933. DeviceName: m.deviceName,
  934. ClientName: m.clientName,
  935. ClientVersion: m.clientVersion,
  936. }
  937. }
  938. // AddConnection adds a new peer connection to the model. An initial index will
  939. // be sent to the connected peer, thereafter index updates whenever the local
  940. // folder changes.
  941. func (m *Model) AddConnection(conn connections.Connection, hello protocol.HelloResult) {
  942. deviceID := conn.ID()
  943. m.pmut.Lock()
  944. if _, ok := m.conn[deviceID]; ok {
  945. panic("add existing device")
  946. }
  947. m.conn[deviceID] = conn
  948. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  949. m.helloMessages[deviceID] = hello
  950. event := map[string]string{
  951. "id": deviceID.String(),
  952. "deviceName": hello.DeviceName,
  953. "clientName": hello.ClientName,
  954. "clientVersion": hello.ClientVersion,
  955. "type": conn.Type,
  956. }
  957. addr := conn.RemoteAddr()
  958. if addr != nil {
  959. event["addr"] = addr.String()
  960. }
  961. events.Default.Log(events.DeviceConnected, event)
  962. l.Infof(`Device %s client is "%s %s" named "%s"`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName)
  963. conn.Start()
  964. cm := m.generateClusterConfig(deviceID)
  965. conn.ClusterConfig(cm)
  966. m.pmut.Unlock()
  967. device, ok := m.cfg.Devices()[deviceID]
  968. if ok && (device.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) {
  969. device.Name = hello.DeviceName
  970. m.cfg.SetDevice(device)
  971. m.cfg.Save()
  972. }
  973. m.deviceWasSeen(deviceID)
  974. }
  975. func (m *Model) PauseDevice(device protocol.DeviceID) {
  976. m.pmut.Lock()
  977. m.devicePaused[device] = true
  978. _, ok := m.conn[device]
  979. m.pmut.Unlock()
  980. if ok {
  981. m.Close(device, errors.New("device paused"))
  982. }
  983. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  984. }
  985. func (m *Model) DownloadProgress(device protocol.DeviceID, folder string, updates []protocol.FileDownloadProgressUpdate) {
  986. if !m.folderSharedWith(folder, device) {
  987. return
  988. }
  989. m.fmut.RLock()
  990. cfg, ok := m.folderCfgs[folder]
  991. m.fmut.RUnlock()
  992. if !ok || cfg.Type == config.FolderTypeReadOnly || cfg.DisableTempIndexes {
  993. return
  994. }
  995. m.pmut.RLock()
  996. m.deviceDownloads[device].Update(folder, updates)
  997. state := m.deviceDownloads[device].GetBlockCounts(folder)
  998. m.pmut.RUnlock()
  999. events.Default.Log(events.RemoteDownloadProgress, map[string]interface{}{
  1000. "device": device.String(),
  1001. "folder": folder,
  1002. "state": state,
  1003. })
  1004. }
  1005. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  1006. m.pmut.Lock()
  1007. m.devicePaused[device] = false
  1008. m.pmut.Unlock()
  1009. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  1010. }
  1011. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  1012. m.pmut.Lock()
  1013. paused := m.devicePaused[device]
  1014. m.pmut.Unlock()
  1015. return paused
  1016. }
  1017. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  1018. m.fmut.Lock()
  1019. defer m.fmut.Unlock()
  1020. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  1021. return sr
  1022. }
  1023. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  1024. m.deviceStatRefs[deviceID] = sr
  1025. return sr
  1026. }
  1027. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  1028. m.deviceStatRef(deviceID).WasSeen()
  1029. }
  1030. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  1031. m.fmut.Lock()
  1032. defer m.fmut.Unlock()
  1033. sr, ok := m.folderStatRefs[folder]
  1034. if !ok {
  1035. sr = stats.NewFolderStatisticsReference(m.db, folder)
  1036. m.folderStatRefs[folder] = sr
  1037. }
  1038. return sr
  1039. }
  1040. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  1041. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  1042. }
  1043. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, startSequence int64, dbLocation string) {
  1044. deviceID := conn.ID()
  1045. name := conn.Name()
  1046. var err error
  1047. l.Debugf("sendIndexes for %s-%s/%q starting (slv=%d)", deviceID, name, folder, startSequence)
  1048. defer l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  1049. minSequence, err := sendIndexTo(startSequence, conn, folder, fs, ignores, dbLocation)
  1050. // Subscribe to LocalIndexUpdated (we have new information to send) and
  1051. // DeviceDisconnected (it might be us who disconnected, so we should
  1052. // exit).
  1053. sub := events.Default.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  1054. defer events.Default.Unsubscribe(sub)
  1055. for err == nil {
  1056. if conn.Closed() {
  1057. // Our work is done.
  1058. return
  1059. }
  1060. // While we have sent a sequence at least equal to the one
  1061. // currently in the database, wait for the local index to update. The
  1062. // local index may update for other folders than the one we are
  1063. // sending for.
  1064. if fs.Sequence(protocol.LocalDeviceID) <= minSequence {
  1065. sub.Poll(time.Minute)
  1066. continue
  1067. }
  1068. minSequence, err = sendIndexTo(minSequence, conn, folder, fs, ignores, dbLocation)
  1069. // Wait a short amount of time before entering the next loop. If there
  1070. // are continuous changes happening to the local index, this gives us
  1071. // time to batch them up a little.
  1072. time.Sleep(250 * time.Millisecond)
  1073. }
  1074. }
  1075. func sendIndexTo(minSequence int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, dbLocation string) (int64, error) {
  1076. deviceID := conn.ID()
  1077. name := conn.Name()
  1078. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1079. currentBatchSize := 0
  1080. initial := minSequence == 0
  1081. maxSequence := minSequence
  1082. var err error
  1083. sorter := NewIndexSorter(dbLocation)
  1084. defer sorter.Close()
  1085. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1086. f := fi.(protocol.FileInfo)
  1087. if f.Sequence <= minSequence {
  1088. return true
  1089. }
  1090. if f.Sequence > maxSequence {
  1091. maxSequence = f.Sequence
  1092. }
  1093. sorter.Append(f)
  1094. return true
  1095. })
  1096. sorter.Sorted(func(f protocol.FileInfo) bool {
  1097. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  1098. if initial {
  1099. if err = conn.Index(folder, batch); err != nil {
  1100. return false
  1101. }
  1102. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  1103. initial = false
  1104. } else {
  1105. if err = conn.IndexUpdate(folder, batch); err != nil {
  1106. return false
  1107. }
  1108. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  1109. }
  1110. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  1111. currentBatchSize = 0
  1112. }
  1113. batch = append(batch, f)
  1114. currentBatchSize += f.ProtoSize()
  1115. return true
  1116. })
  1117. if initial && err == nil {
  1118. err = conn.Index(folder, batch)
  1119. if err == nil {
  1120. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  1121. }
  1122. } else if len(batch) > 0 && err == nil {
  1123. err = conn.IndexUpdate(folder, batch)
  1124. if err == nil {
  1125. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  1126. }
  1127. }
  1128. return maxSequence, err
  1129. }
  1130. func (m *Model) updateLocalsFromScanning(folder string, fs []protocol.FileInfo) {
  1131. m.updateLocals(folder, fs)
  1132. // Fire the LocalChangeDetected event to notify listeners about local
  1133. // updates.
  1134. m.fmut.RLock()
  1135. path := m.folderCfgs[folder].Path()
  1136. m.fmut.RUnlock()
  1137. m.localChangeDetected(folder, path, fs)
  1138. }
  1139. func (m *Model) updateLocalsFromPulling(folder string, fs []protocol.FileInfo) {
  1140. m.updateLocals(folder, fs)
  1141. }
  1142. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  1143. m.fmut.RLock()
  1144. files := m.folderFiles[folder]
  1145. m.fmut.RUnlock()
  1146. if files == nil {
  1147. // The folder doesn't exist.
  1148. return
  1149. }
  1150. files.Update(protocol.LocalDeviceID, fs)
  1151. filenames := make([]string, len(fs))
  1152. for i, file := range fs {
  1153. filenames[i] = file.Name
  1154. }
  1155. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1156. "folder": folder,
  1157. "items": len(fs),
  1158. "filenames": filenames,
  1159. "version": files.Sequence(protocol.LocalDeviceID),
  1160. })
  1161. }
  1162. func (m *Model) localChangeDetected(folder, path string, files []protocol.FileInfo) {
  1163. // For windows paths, strip unwanted chars from the front
  1164. path = strings.Replace(path, `\\?\`, "", 1)
  1165. for _, file := range files {
  1166. objType := "file"
  1167. action := "modified"
  1168. // If our local vector is version 1 AND it is the only version
  1169. // vector so far seen for this file then it is a new file. Else if
  1170. // it is > 1 it's not new, and if it is 1 but another shortId
  1171. // version vector exists then it is new for us but created elsewhere
  1172. // so the file is still not new but modified by us. Only if it is
  1173. // truly new do we change this to 'added', else we leave it as
  1174. // 'modified'.
  1175. if len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1 {
  1176. action = "added"
  1177. }
  1178. if file.IsDirectory() {
  1179. objType = "dir"
  1180. }
  1181. if file.IsDeleted() {
  1182. action = "deleted"
  1183. }
  1184. // The full file path, adjusted to the local path separator character.
  1185. path := filepath.Join(path, filepath.FromSlash(file.Name))
  1186. events.Default.Log(events.LocalChangeDetected, map[string]string{
  1187. "folder": folder,
  1188. "action": action,
  1189. "type": objType,
  1190. "path": path,
  1191. })
  1192. }
  1193. }
  1194. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  1195. m.pmut.RLock()
  1196. nc, ok := m.conn[deviceID]
  1197. m.pmut.RUnlock()
  1198. if !ok {
  1199. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1200. }
  1201. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x ft=%t", m, deviceID, folder, name, offset, size, hash, fromTemporary)
  1202. return nc.Request(folder, name, offset, size, hash, fromTemporary)
  1203. }
  1204. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  1205. if len(cfg.ID) == 0 {
  1206. panic("cannot add empty folder id")
  1207. }
  1208. m.fmut.Lock()
  1209. m.folderCfgs[cfg.ID] = cfg
  1210. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  1211. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  1212. for i, device := range cfg.Devices {
  1213. m.folderDevices[cfg.ID][i] = device.DeviceID
  1214. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  1215. }
  1216. ignores := ignore.New(m.cacheIgnoredFiles)
  1217. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1218. l.Warnln("Loading ignores:", err)
  1219. }
  1220. m.folderIgnores[cfg.ID] = ignores
  1221. m.fmut.Unlock()
  1222. }
  1223. func (m *Model) ScanFolders() map[string]error {
  1224. m.fmut.RLock()
  1225. folders := make([]string, 0, len(m.folderCfgs))
  1226. for folder := range m.folderCfgs {
  1227. folders = append(folders, folder)
  1228. }
  1229. m.fmut.RUnlock()
  1230. errors := make(map[string]error, len(m.folderCfgs))
  1231. errorsMut := sync.NewMutex()
  1232. wg := sync.NewWaitGroup()
  1233. wg.Add(len(folders))
  1234. for _, folder := range folders {
  1235. folder := folder
  1236. go func() {
  1237. err := m.ScanFolder(folder)
  1238. if err != nil {
  1239. errorsMut.Lock()
  1240. errors[folder] = err
  1241. errorsMut.Unlock()
  1242. // Potentially sets the error twice, once in the scanner just
  1243. // by doing a check, and once here, if the error returned is
  1244. // the same one as returned by CheckFolderHealth, though
  1245. // duplicate set is handled by setError.
  1246. m.fmut.RLock()
  1247. srv := m.folderRunners[folder]
  1248. m.fmut.RUnlock()
  1249. srv.setError(err)
  1250. }
  1251. wg.Done()
  1252. }()
  1253. }
  1254. wg.Wait()
  1255. return errors
  1256. }
  1257. func (m *Model) ScanFolder(folder string) error {
  1258. return m.ScanFolderSubdirs(folder, nil)
  1259. }
  1260. func (m *Model) ScanFolderSubdirs(folder string, subs []string) error {
  1261. m.fmut.Lock()
  1262. runner, ok := m.folderRunners[folder]
  1263. m.fmut.Unlock()
  1264. // Folders are added to folderRunners only when they are started. We can't
  1265. // scan them before they have started, so that's what we need to check for
  1266. // here.
  1267. if !ok {
  1268. return errors.New("no such folder")
  1269. }
  1270. return runner.Scan(subs)
  1271. }
  1272. func (m *Model) internalScanFolderSubdirs(folder string, subDirs []string) error {
  1273. for i, sub := range subDirs {
  1274. sub = osutil.NativeFilename(sub)
  1275. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1276. return errors.New("invalid subpath")
  1277. }
  1278. subDirs[i] = sub
  1279. }
  1280. m.fmut.Lock()
  1281. fs := m.folderFiles[folder]
  1282. folderCfg := m.folderCfgs[folder]
  1283. ignores := m.folderIgnores[folder]
  1284. runner, ok := m.folderRunners[folder]
  1285. m.fmut.Unlock()
  1286. // Check if the ignore patterns changed as part of scanning this folder.
  1287. // If they did we should schedule a pull of the folder so that we
  1288. // request things we might have suddenly become unignored and so on.
  1289. oldHash := ignores.Hash()
  1290. defer func() {
  1291. if ignores.Hash() != oldHash {
  1292. l.Debugln("Folder", folder, "ignore patterns changed; triggering puller")
  1293. runner.IndexUpdated()
  1294. }
  1295. }()
  1296. // Folders are added to folderRunners only when they are started. We can't
  1297. // scan them before they have started, so that's what we need to check for
  1298. // here.
  1299. if !ok {
  1300. return errors.New("no such folder")
  1301. }
  1302. if err := m.CheckFolderHealth(folder); err != nil {
  1303. runner.setError(err)
  1304. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1305. return err
  1306. }
  1307. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1308. err = fmt.Errorf("loading ignores: %v", err)
  1309. runner.setError(err)
  1310. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1311. return err
  1312. }
  1313. // Clean the list of subitems to ensure that we start at a known
  1314. // directory, and don't scan subdirectories of things we've already
  1315. // scanned.
  1316. subDirs = unifySubs(subDirs, func(f string) bool {
  1317. _, ok := fs.Get(protocol.LocalDeviceID, f)
  1318. return ok
  1319. })
  1320. // The cancel channel is closed whenever we return (such as from an error),
  1321. // to signal the potentially still running walker to stop.
  1322. cancel := make(chan struct{})
  1323. defer close(cancel)
  1324. runner.setState(FolderScanning)
  1325. fchan, err := scanner.Walk(scanner.Config{
  1326. Folder: folderCfg.ID,
  1327. Dir: folderCfg.Path(),
  1328. Subs: subDirs,
  1329. Matcher: ignores,
  1330. BlockSize: protocol.BlockSize,
  1331. TempNamer: defTempNamer,
  1332. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1333. CurrentFiler: cFiler{m, folder},
  1334. MtimeRepo: db.NewVirtualMtimeRepo(m.db, folderCfg.ID),
  1335. IgnorePerms: folderCfg.IgnorePerms,
  1336. AutoNormalize: folderCfg.AutoNormalize,
  1337. Hashers: m.numHashers(folder),
  1338. ShortID: m.shortID,
  1339. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1340. Cancel: cancel,
  1341. })
  1342. if err != nil {
  1343. // The error we get here is likely an OS level error, which might not be
  1344. // as readable as our health check errors. Check if we can get a health
  1345. // check error first, and use that if it's available.
  1346. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1347. err = ferr
  1348. }
  1349. runner.setError(err)
  1350. return err
  1351. }
  1352. batchSizeFiles := 100
  1353. batchSizeBlocks := 2048 // about 256 MB
  1354. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1355. blocksHandled := 0
  1356. for f := range fchan {
  1357. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1358. if err := m.CheckFolderHealth(folder); err != nil {
  1359. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1360. return err
  1361. }
  1362. m.updateLocalsFromScanning(folder, batch)
  1363. batch = batch[:0]
  1364. blocksHandled = 0
  1365. }
  1366. batch = append(batch, f)
  1367. blocksHandled += len(f.Blocks)
  1368. }
  1369. if err := m.CheckFolderHealth(folder); err != nil {
  1370. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1371. return err
  1372. } else if len(batch) > 0 {
  1373. m.updateLocalsFromScanning(folder, batch)
  1374. }
  1375. if len(subDirs) == 0 {
  1376. // If we have no specific subdirectories to traverse, set it to one
  1377. // empty prefix so we traverse the entire folder contents once.
  1378. subDirs = []string{""}
  1379. }
  1380. // Do a scan of the database for each prefix, to check for deleted files.
  1381. batch = batch[:0]
  1382. for _, sub := range subDirs {
  1383. var iterError error
  1384. fs.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  1385. f := fi.(db.FileInfoTruncated)
  1386. if !f.IsDeleted() {
  1387. if len(batch) == batchSizeFiles {
  1388. if err := m.CheckFolderHealth(folder); err != nil {
  1389. iterError = err
  1390. return false
  1391. }
  1392. m.updateLocalsFromScanning(folder, batch)
  1393. batch = batch[:0]
  1394. }
  1395. if !f.IsInvalid() && (ignores.Match(f.Name).IsIgnored() || symlinkInvalid(folder, f)) {
  1396. // File has been ignored or an unsupported symlink. Set invalid bit.
  1397. l.Debugln("setting invalid bit on ignored", f)
  1398. nf := protocol.FileInfo{
  1399. Name: f.Name,
  1400. Type: f.Type,
  1401. Size: f.Size,
  1402. Modified: f.Modified,
  1403. Permissions: f.Permissions,
  1404. NoPermissions: f.NoPermissions,
  1405. Invalid: true,
  1406. Version: f.Version, // The file is still the same, so don't bump version
  1407. }
  1408. batch = append(batch, nf)
  1409. } else if _, err := osutil.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1410. // File has been deleted.
  1411. // We don't specifically verify that the error is
  1412. // os.IsNotExist because there is a corner case when a
  1413. // directory is suddenly transformed into a file. When that
  1414. // happens, files that were in the directory (that is now a
  1415. // file) are deleted but will return a confusing error ("not a
  1416. // directory") when we try to Lstat() them.
  1417. nf := protocol.FileInfo{
  1418. Name: f.Name,
  1419. Type: f.Type,
  1420. Size: f.Size,
  1421. Modified: f.Modified,
  1422. Deleted: true,
  1423. Version: f.Version.Update(m.shortID),
  1424. }
  1425. batch = append(batch, nf)
  1426. }
  1427. }
  1428. return true
  1429. })
  1430. if iterError != nil {
  1431. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1432. return iterError
  1433. }
  1434. }
  1435. if err := m.CheckFolderHealth(folder); err != nil {
  1436. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1437. return err
  1438. } else if len(batch) > 0 {
  1439. m.updateLocalsFromScanning(folder, batch)
  1440. }
  1441. m.folderStatRef(folder).ScanCompleted()
  1442. runner.setState(FolderIdle)
  1443. return nil
  1444. }
  1445. func (m *Model) DelayScan(folder string, next time.Duration) {
  1446. m.fmut.Lock()
  1447. runner, ok := m.folderRunners[folder]
  1448. m.fmut.Unlock()
  1449. if !ok {
  1450. return
  1451. }
  1452. runner.DelayScan(next)
  1453. }
  1454. // numHashers returns the number of hasher routines to use for a given folder,
  1455. // taking into account configuration and available CPU cores.
  1456. func (m *Model) numHashers(folder string) int {
  1457. m.fmut.Lock()
  1458. folderCfg := m.folderCfgs[folder]
  1459. numFolders := len(m.folderCfgs)
  1460. m.fmut.Unlock()
  1461. if folderCfg.Hashers > 0 {
  1462. // Specific value set in the config, use that.
  1463. return folderCfg.Hashers
  1464. }
  1465. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1466. // Interactive operating systems; don't load the system too heavily by
  1467. // default.
  1468. return 1
  1469. }
  1470. // For other operating systems and architectures, lets try to get some
  1471. // work done... Divide the available CPU cores among the configured
  1472. // folders.
  1473. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1474. return perFolder
  1475. }
  1476. return 1
  1477. }
  1478. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1479. // the given peer device
  1480. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1481. var message protocol.ClusterConfig
  1482. m.fmut.RLock()
  1483. for _, folder := range m.deviceFolders[device] {
  1484. folderCfg := m.cfg.Folders()[folder]
  1485. fs := m.folderFiles[folder]
  1486. protocolFolder := protocol.Folder{
  1487. ID: folder,
  1488. Label: folderCfg.Label,
  1489. ReadOnly: folderCfg.Type == config.FolderTypeReadOnly,
  1490. IgnorePermissions: folderCfg.IgnorePerms,
  1491. IgnoreDelete: folderCfg.IgnoreDelete,
  1492. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1493. }
  1494. for _, device := range m.folderDevices[folder] {
  1495. // DeviceID is a value type, but with an underlying array. Copy it
  1496. // so we don't grab aliases to the same array later on in device[:]
  1497. device := device
  1498. // TODO: Set read only bit when relevant, and when we have per device
  1499. // access controls.
  1500. deviceCfg := m.cfg.Devices()[device]
  1501. var indexID protocol.IndexID
  1502. var maxSequence int64
  1503. if device == m.id {
  1504. indexID = fs.IndexID(protocol.LocalDeviceID)
  1505. maxSequence = fs.Sequence(protocol.LocalDeviceID)
  1506. } else {
  1507. indexID = fs.IndexID(device)
  1508. maxSequence = fs.Sequence(device)
  1509. }
  1510. protocolDevice := protocol.Device{
  1511. ID: device[:],
  1512. Name: deviceCfg.Name,
  1513. Addresses: deviceCfg.Addresses,
  1514. Compression: deviceCfg.Compression,
  1515. CertName: deviceCfg.CertName,
  1516. Introducer: deviceCfg.Introducer,
  1517. IndexID: indexID,
  1518. MaxSequence: maxSequence,
  1519. }
  1520. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1521. }
  1522. message.Folders = append(message.Folders, protocolFolder)
  1523. }
  1524. m.fmut.RUnlock()
  1525. return message
  1526. }
  1527. func (m *Model) State(folder string) (string, time.Time, error) {
  1528. m.fmut.RLock()
  1529. runner, ok := m.folderRunners[folder]
  1530. m.fmut.RUnlock()
  1531. if !ok {
  1532. // The returned error should be an actual folder error, so returning
  1533. // errors.New("does not exist") or similar here would be
  1534. // inappropriate.
  1535. return "", time.Time{}, nil
  1536. }
  1537. state, changed, err := runner.getState()
  1538. return state.String(), changed, err
  1539. }
  1540. func (m *Model) Override(folder string) {
  1541. m.fmut.RLock()
  1542. fs, ok := m.folderFiles[folder]
  1543. runner := m.folderRunners[folder]
  1544. m.fmut.RUnlock()
  1545. if !ok {
  1546. return
  1547. }
  1548. runner.setState(FolderScanning)
  1549. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1550. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1551. need := fi.(protocol.FileInfo)
  1552. if len(batch) == indexBatchSize {
  1553. m.updateLocalsFromScanning(folder, batch)
  1554. batch = batch[:0]
  1555. }
  1556. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1557. if !ok || have.Name != need.Name {
  1558. // We are missing the file
  1559. need.Deleted = true
  1560. need.Blocks = nil
  1561. need.Version = need.Version.Update(m.shortID)
  1562. } else {
  1563. // We have the file, replace with our version
  1564. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1565. need = have
  1566. }
  1567. need.Sequence = 0
  1568. batch = append(batch, need)
  1569. return true
  1570. })
  1571. if len(batch) > 0 {
  1572. m.updateLocalsFromScanning(folder, batch)
  1573. }
  1574. runner.setState(FolderIdle)
  1575. }
  1576. // CurrentSequence returns the change version for the given folder.
  1577. // This is guaranteed to increment if the contents of the local folder has
  1578. // changed.
  1579. func (m *Model) CurrentSequence(folder string) (int64, bool) {
  1580. m.fmut.RLock()
  1581. fs, ok := m.folderFiles[folder]
  1582. m.fmut.RUnlock()
  1583. if !ok {
  1584. // The folder might not exist, since this can be called with a user
  1585. // specified folder name from the REST interface.
  1586. return 0, false
  1587. }
  1588. return fs.Sequence(protocol.LocalDeviceID), true
  1589. }
  1590. // RemoteSequence returns the change version for the given folder, as
  1591. // sent by remote peers. This is guaranteed to increment if the contents of
  1592. // the remote or global folder has changed.
  1593. func (m *Model) RemoteSequence(folder string) (int64, bool) {
  1594. m.fmut.RLock()
  1595. defer m.fmut.RUnlock()
  1596. fs, ok := m.folderFiles[folder]
  1597. if !ok {
  1598. // The folder might not exist, since this can be called with a user
  1599. // specified folder name from the REST interface.
  1600. return 0, false
  1601. }
  1602. var ver int64
  1603. for _, n := range m.folderDevices[folder] {
  1604. ver += fs.Sequence(n)
  1605. }
  1606. return ver, true
  1607. }
  1608. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1609. m.fmut.RLock()
  1610. files, ok := m.folderFiles[folder]
  1611. m.fmut.RUnlock()
  1612. if !ok {
  1613. return nil
  1614. }
  1615. output := make(map[string]interface{})
  1616. sep := string(filepath.Separator)
  1617. prefix = osutil.NativeFilename(prefix)
  1618. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1619. prefix = prefix + sep
  1620. }
  1621. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1622. f := fi.(db.FileInfoTruncated)
  1623. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1624. return true
  1625. }
  1626. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1627. var dir, base string
  1628. if f.IsDirectory() && !f.IsSymlink() {
  1629. dir = f.Name
  1630. } else {
  1631. dir = filepath.Dir(f.Name)
  1632. base = filepath.Base(f.Name)
  1633. }
  1634. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1635. return true
  1636. }
  1637. last := output
  1638. if dir != "." {
  1639. for _, path := range strings.Split(dir, sep) {
  1640. directory, ok := last[path]
  1641. if !ok {
  1642. newdir := make(map[string]interface{})
  1643. last[path] = newdir
  1644. last = newdir
  1645. } else {
  1646. last = directory.(map[string]interface{})
  1647. }
  1648. }
  1649. }
  1650. if !dirsonly && base != "" {
  1651. last[base] = []interface{}{
  1652. time.Unix(f.Modified, 0), f.FileSize(),
  1653. }
  1654. }
  1655. return true
  1656. })
  1657. return output
  1658. }
  1659. func (m *Model) Availability(folder, file string, version protocol.Vector, block protocol.BlockInfo) []Availability {
  1660. // Acquire this lock first, as the value returned from foldersFiles can
  1661. // get heavily modified on Close()
  1662. m.pmut.RLock()
  1663. defer m.pmut.RUnlock()
  1664. m.fmut.RLock()
  1665. fs, ok := m.folderFiles[folder]
  1666. devices := m.folderDevices[folder]
  1667. m.fmut.RUnlock()
  1668. if !ok {
  1669. return nil
  1670. }
  1671. var availabilities []Availability
  1672. for _, device := range fs.Availability(file) {
  1673. _, ok := m.conn[device]
  1674. if ok {
  1675. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  1676. }
  1677. }
  1678. for _, device := range devices {
  1679. if m.deviceDownloads[device].Has(folder, file, version, int32(block.Offset/protocol.BlockSize)) {
  1680. availabilities = append(availabilities, Availability{ID: device, FromTemporary: true})
  1681. }
  1682. }
  1683. return availabilities
  1684. }
  1685. // BringToFront bumps the given files priority in the job queue.
  1686. func (m *Model) BringToFront(folder, file string) {
  1687. m.pmut.RLock()
  1688. defer m.pmut.RUnlock()
  1689. runner, ok := m.folderRunners[folder]
  1690. if ok {
  1691. runner.BringToFront(file)
  1692. }
  1693. }
  1694. // CheckFolderHealth checks the folder for common errors and returns the
  1695. // current folder error, or nil if the folder is healthy.
  1696. func (m *Model) CheckFolderHealth(id string) error {
  1697. folder, ok := m.cfg.Folders()[id]
  1698. if !ok {
  1699. return errors.New("folder does not exist")
  1700. }
  1701. // Check for folder errors, with the most serious and specific first and
  1702. // generic ones like out of space on the home disk later. Note the
  1703. // inverted error flow (err==nil checks) here.
  1704. err := m.checkFolderPath(folder)
  1705. if err == nil {
  1706. err = m.checkFolderFreeSpace(folder)
  1707. }
  1708. if err == nil {
  1709. err = m.checkHomeDiskFree()
  1710. }
  1711. // Set or clear the error on the runner, which also does logging and
  1712. // generates events and stuff.
  1713. m.runnerExchangeError(folder, err)
  1714. return err
  1715. }
  1716. // checkFolderPath returns nil if the folder path exists and has the marker file.
  1717. func (m *Model) checkFolderPath(folder config.FolderConfiguration) error {
  1718. if folder.Path() == "" {
  1719. return errFolderPathEmpty
  1720. }
  1721. if fi, err := os.Stat(folder.Path()); err != nil || !fi.IsDir() {
  1722. return errFolderPathMissing
  1723. }
  1724. if !folder.HasMarker() {
  1725. return errFolderMarkerMissing
  1726. }
  1727. return nil
  1728. }
  1729. // checkFolderFreeSpace returns nil if the folder has the required amount of
  1730. // free space, or if folder free space checking is disabled.
  1731. func (m *Model) checkFolderFreeSpace(folder config.FolderConfiguration) error {
  1732. if folder.MinDiskFreePct <= 0 {
  1733. return nil
  1734. }
  1735. free, err := osutil.DiskFreePercentage(folder.Path())
  1736. if err == nil && free < folder.MinDiskFreePct {
  1737. return errFolderNoSpace
  1738. }
  1739. return nil
  1740. }
  1741. // checkHomeDiskFree returns nil if the home disk has the required amount of
  1742. // free space, or if home disk free space checking is disabled.
  1743. func (m *Model) checkHomeDiskFree() error {
  1744. minFree := m.cfg.Options().MinHomeDiskFreePct
  1745. if minFree <= 0 {
  1746. return nil
  1747. }
  1748. free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath())
  1749. if err == nil && free < minFree {
  1750. return errHomeDiskNoSpace
  1751. }
  1752. return nil
  1753. }
  1754. // runnerExchangeError sets the given error (which way be nil) on the folder
  1755. // runner. If the error differs from any previous error, logging and events
  1756. // happen.
  1757. func (m *Model) runnerExchangeError(folder config.FolderConfiguration, err error) {
  1758. m.fmut.RLock()
  1759. runner, runnerExists := m.folderRunners[folder.ID]
  1760. m.fmut.RUnlock()
  1761. var oldErr error
  1762. if runnerExists {
  1763. _, _, oldErr = runner.getState()
  1764. }
  1765. if err != nil {
  1766. if oldErr != nil && oldErr.Error() != err.Error() {
  1767. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1768. } else if oldErr == nil {
  1769. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1770. }
  1771. if runnerExists {
  1772. runner.setError(err)
  1773. }
  1774. } else if oldErr != nil {
  1775. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1776. if runnerExists {
  1777. runner.clearError()
  1778. }
  1779. }
  1780. }
  1781. func (m *Model) ResetFolder(folder string) {
  1782. l.Infof("Cleaning data for folder %q", folder)
  1783. db.DropFolder(m.db, folder)
  1784. }
  1785. func (m *Model) String() string {
  1786. return fmt.Sprintf("model@%p", m)
  1787. }
  1788. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1789. return nil
  1790. }
  1791. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1792. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1793. // Go through the folder configs and figure out if we need to restart or not.
  1794. fromFolders := mapFolders(from.Folders)
  1795. toFolders := mapFolders(to.Folders)
  1796. for folderID, cfg := range toFolders {
  1797. if _, ok := fromFolders[folderID]; !ok {
  1798. // A folder was added.
  1799. l.Debugln(m, "adding folder", folderID)
  1800. m.AddFolder(cfg)
  1801. m.StartFolder(folderID)
  1802. // Drop connections to all devices that can now share the new
  1803. // folder.
  1804. m.pmut.Lock()
  1805. for _, dev := range cfg.DeviceIDs() {
  1806. if conn, ok := m.conn[dev]; ok {
  1807. closeRawConn(conn)
  1808. }
  1809. }
  1810. m.pmut.Unlock()
  1811. }
  1812. }
  1813. for folderID, fromCfg := range fromFolders {
  1814. toCfg, ok := toFolders[folderID]
  1815. if !ok {
  1816. // The folder was removed.
  1817. m.RemoveFolder(folderID)
  1818. continue
  1819. }
  1820. // This folder exists on both sides. Compare the device lists, as we
  1821. // can handle adding a device (but not currently removing one).
  1822. fromDevs := mapDevices(fromCfg.DeviceIDs())
  1823. toDevs := mapDevices(toCfg.DeviceIDs())
  1824. for dev := range fromDevs {
  1825. if _, ok := toDevs[dev]; !ok {
  1826. // A device was removed. Requires restart.
  1827. l.Debugln(m, "requires restart, removing device", dev, "from folder", folderID)
  1828. return false
  1829. }
  1830. }
  1831. for dev := range toDevs {
  1832. if _, ok := fromDevs[dev]; !ok {
  1833. // A device was added. Handle it!
  1834. m.fmut.Lock()
  1835. m.pmut.Lock()
  1836. m.folderCfgs[folderID] = toCfg
  1837. m.folderDevices[folderID] = append(m.folderDevices[folderID], dev)
  1838. m.deviceFolders[dev] = append(m.deviceFolders[dev], folderID)
  1839. // If we already have a connection to this device, we should
  1840. // disconnect it so that we start sharing the folder with it.
  1841. // We close the underlying connection and let the normal error
  1842. // handling kick in to clean up and reconnect.
  1843. if conn, ok := m.conn[dev]; ok {
  1844. closeRawConn(conn)
  1845. }
  1846. m.pmut.Unlock()
  1847. m.fmut.Unlock()
  1848. }
  1849. }
  1850. // Check if anything else differs, apart from the device list and label.
  1851. fromCfg.Devices = nil
  1852. toCfg.Devices = nil
  1853. fromCfg.Label = ""
  1854. toCfg.Label = ""
  1855. if !reflect.DeepEqual(fromCfg, toCfg) {
  1856. l.Debugln(m, "requires restart, folder", folderID, "configuration differs")
  1857. return false
  1858. }
  1859. }
  1860. // Removing a device requires restart
  1861. toDevs := mapDeviceCfgs(from.Devices)
  1862. for _, dev := range from.Devices {
  1863. if _, ok := toDevs[dev.DeviceID]; !ok {
  1864. l.Debugln(m, "requires restart, device", dev.DeviceID, "was removed")
  1865. return false
  1866. }
  1867. }
  1868. // Some options don't require restart as those components handle it fine
  1869. // by themselves.
  1870. from.Options.URAccepted = to.Options.URAccepted
  1871. from.Options.URUniqueID = to.Options.URUniqueID
  1872. from.Options.ListenAddresses = to.Options.ListenAddresses
  1873. from.Options.RelaysEnabled = to.Options.RelaysEnabled
  1874. from.Options.UnackedNotificationIDs = to.Options.UnackedNotificationIDs
  1875. // All of the other generic options require restart. Or at least they may;
  1876. // removing this check requires going through those options carefully and
  1877. // making sure there are individual services that handle them correctly.
  1878. // This code is the "original" requires-restart check and protects other
  1879. // components that haven't yet been converted to VerifyConfig/CommitConfig
  1880. // handling.
  1881. if !reflect.DeepEqual(from.Options, to.Options) {
  1882. l.Debugln(m, "requires restart, options differ")
  1883. return false
  1884. }
  1885. return true
  1886. }
  1887. // mapFolders returns a map of folder ID to folder configuration for the given
  1888. // slice of folder configurations.
  1889. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1890. m := make(map[string]config.FolderConfiguration, len(folders))
  1891. for _, cfg := range folders {
  1892. m[cfg.ID] = cfg
  1893. }
  1894. return m
  1895. }
  1896. // mapDevices returns a map of device ID to nothing for the given slice of
  1897. // device IDs.
  1898. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1899. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1900. for _, dev := range devices {
  1901. m[dev] = struct{}{}
  1902. }
  1903. return m
  1904. }
  1905. // mapDeviceCfgs returns a map of device ID to nothing for the given slice of
  1906. // device configurations.
  1907. func mapDeviceCfgs(devices []config.DeviceConfiguration) map[protocol.DeviceID]struct{} {
  1908. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1909. for _, dev := range devices {
  1910. m[dev.DeviceID] = struct{}{}
  1911. }
  1912. return m
  1913. }
  1914. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1915. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1916. symlinkWarning.Do(func() {
  1917. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1918. })
  1919. // Need to type switch for the concrete type to be able to access fields...
  1920. var name string
  1921. switch fi := fi.(type) {
  1922. case protocol.FileInfo:
  1923. name = fi.Name
  1924. case db.FileInfoTruncated:
  1925. name = fi.Name
  1926. }
  1927. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1928. return true
  1929. }
  1930. return false
  1931. }
  1932. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1933. // Returns the resulting slice, plus how much elements are left to skip or
  1934. // copy to satisfy the values which were provided, given the slice is not
  1935. // big enough.
  1936. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1937. l := len(data)
  1938. if l <= skip {
  1939. return []string{}, skip - l, get
  1940. } else if l < skip+get {
  1941. return data[skip:l], 0, get - (l - skip)
  1942. }
  1943. return data[skip : skip+get], 0, 0
  1944. }
  1945. func closeRawConn(conn io.Closer) error {
  1946. if conn, ok := conn.(*tls.Conn); ok {
  1947. // If the underlying connection is a *tls.Conn, Close() does more
  1948. // than it says on the tin. Specifically, it sends a TLS alert
  1949. // message, which might block forever if the connection is dead
  1950. // and we don't have a deadline set.
  1951. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1952. }
  1953. return conn.Close()
  1954. }
  1955. func stringSliceWithout(ss []string, s string) []string {
  1956. for i := range ss {
  1957. if ss[i] == s {
  1958. copy(ss[i:], ss[i+1:])
  1959. ss = ss[:len(ss)-1]
  1960. return ss
  1961. }
  1962. }
  1963. return ss
  1964. }
  1965. func readOffsetIntoBuf(file string, offset int64, buf []byte) error {
  1966. fd, err := os.Open(file)
  1967. if err != nil {
  1968. l.Debugln("readOffsetIntoBuf.Open", file, err)
  1969. return err
  1970. }
  1971. defer fd.Close()
  1972. _, err = fd.ReadAt(buf, offset)
  1973. if err != nil {
  1974. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  1975. }
  1976. return err
  1977. }
  1978. // The exists function is expected to return true for all known paths
  1979. // (excluding "" and ".")
  1980. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  1981. subs := trimUntilParentKnown(dirs, exists)
  1982. sort.Strings(subs)
  1983. return simplifySortedPaths(subs)
  1984. }
  1985. func trimUntilParentKnown(dirs []string, exists func(dir string) bool) []string {
  1986. var subs []string
  1987. for _, sub := range dirs {
  1988. for sub != "" && sub != ".stfolder" && sub != ".stignore" {
  1989. sub = filepath.Clean(sub)
  1990. parent := filepath.Dir(sub)
  1991. if parent == "." || exists(parent) {
  1992. break
  1993. }
  1994. sub = parent
  1995. if sub == "." || sub == string(filepath.Separator) {
  1996. // Shortcut. We are going to scan the full folder, so we can
  1997. // just return an empty list of subs at this point.
  1998. return nil
  1999. }
  2000. }
  2001. if sub == "" {
  2002. return nil
  2003. }
  2004. subs = append(subs, sub)
  2005. }
  2006. return subs
  2007. }
  2008. func simplifySortedPaths(subs []string) []string {
  2009. var cleaned []string
  2010. next:
  2011. for _, sub := range subs {
  2012. for _, existing := range cleaned {
  2013. if sub == existing || strings.HasPrefix(sub, existing+string(os.PathSeparator)) {
  2014. continue next
  2015. }
  2016. }
  2017. cleaned = append(cleaned, sub)
  2018. }
  2019. return cleaned
  2020. }
  2021. // makeForgetUpdate takes an index update and constructs a download progress update
  2022. // causing to forget any progress for files which we've just been sent.
  2023. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  2024. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  2025. for _, file := range files {
  2026. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  2027. continue
  2028. }
  2029. updates = append(updates, protocol.FileDownloadProgressUpdate{
  2030. Name: file.Name,
  2031. Version: file.Version,
  2032. UpdateType: protocol.UpdateTypeForget,
  2033. })
  2034. }
  2035. return updates
  2036. }
  2037. // shouldIgnore returns true when a file should be excluded from processing
  2038. func shouldIgnore(file db.FileIntf, matcher *ignore.Matcher, ignoreDelete bool) bool {
  2039. // We check things in a certain order here...
  2040. switch {
  2041. case ignoreDelete && file.IsDeleted():
  2042. // ignoreDelete first because it's a very cheap test so a win if it
  2043. // succeeds, and we might in the long run accumulate quite a few
  2044. // deleted files.
  2045. return true
  2046. case matcher.Match(file.FileName()).IsIgnored():
  2047. // ignore patterns second because ignoring them is a valid way to
  2048. // silence warnings about them being invalid and so on.
  2049. return true
  2050. }
  2051. return false
  2052. }