model.go 67 KB

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