model.go 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  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. )
  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.ClusterConfig),
  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.FileSize()
  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) {
  473. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  474. if !m.folderSharedWith(folder, deviceID) {
  475. 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)
  476. return
  477. }
  478. m.fmut.RLock()
  479. cfg := m.folderCfgs[folder]
  480. files, ok := m.folderFiles[folder]
  481. runner := m.folderRunners[folder]
  482. ignores := m.folderIgnores[folder]
  483. m.fmut.RUnlock()
  484. if runner != nil {
  485. // Runner may legitimately not be set if this is the "cleanup" Index
  486. // message at startup.
  487. defer runner.IndexUpdated()
  488. }
  489. if !ok {
  490. l.Fatalf("Index for nonexistent folder %q", folder)
  491. }
  492. m.pmut.RLock()
  493. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  494. m.pmut.RUnlock()
  495. fs = filterIndex(folder, fs, cfg.IgnoreDelete, ignores)
  496. files.Replace(deviceID, fs)
  497. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  498. "device": deviceID.String(),
  499. "folder": folder,
  500. "items": len(fs),
  501. "version": files.LocalVersion(deviceID),
  502. })
  503. }
  504. // IndexUpdate is called for incremental updates to connected devices' indexes.
  505. // Implements the protocol.Model interface.
  506. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  507. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  508. if !m.folderSharedWith(folder, deviceID) {
  509. 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)
  510. return
  511. }
  512. m.fmut.RLock()
  513. files := m.folderFiles[folder]
  514. cfg := m.folderCfgs[folder]
  515. runner, ok := m.folderRunners[folder]
  516. ignores := m.folderIgnores[folder]
  517. m.fmut.RUnlock()
  518. if !ok {
  519. l.Fatalf("IndexUpdate for nonexistent folder %q", folder)
  520. }
  521. m.pmut.RLock()
  522. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  523. m.pmut.RUnlock()
  524. fs = filterIndex(folder, fs, cfg.IgnoreDelete, ignores)
  525. files.Update(deviceID, fs)
  526. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  527. "device": deviceID.String(),
  528. "folder": folder,
  529. "items": len(fs),
  530. "version": files.LocalVersion(deviceID),
  531. })
  532. runner.IndexUpdated()
  533. }
  534. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  535. m.fmut.RLock()
  536. defer m.fmut.RUnlock()
  537. return m.folderSharedWithUnlocked(folder, deviceID)
  538. }
  539. func (m *Model) folderSharedWithUnlocked(folder string, deviceID protocol.DeviceID) bool {
  540. for _, nfolder := range m.deviceFolders[deviceID] {
  541. if nfolder == folder {
  542. return true
  543. }
  544. }
  545. return false
  546. }
  547. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfig) {
  548. // Check the peer device's announced folders against our own. Emits events
  549. // for folders that we don't expect (unknown or not shared).
  550. // Also, collect a list of folders we do share, and if he's interested in
  551. // temporary indexes, subscribe the connection.
  552. tempIndexFolders := make([]string, 0, len(cm.Folders))
  553. m.pmut.RLock()
  554. conn := m.conn[deviceID]
  555. m.pmut.RUnlock()
  556. m.fmut.Lock()
  557. for _, folder := range cm.Folders {
  558. if !m.folderSharedWithUnlocked(folder.ID, deviceID) {
  559. events.Default.Log(events.FolderRejected, map[string]string{
  560. "folder": folder.ID,
  561. "folderLabel": folder.Label,
  562. "device": deviceID.String(),
  563. })
  564. 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)
  565. continue
  566. }
  567. if !folder.DisableTempIndexes {
  568. tempIndexFolders = append(tempIndexFolders, folder.ID)
  569. }
  570. fs := m.folderFiles[folder.ID]
  571. myIndexID := fs.IndexID(protocol.LocalDeviceID)
  572. myLocalVersion := fs.LocalVersion(protocol.LocalDeviceID)
  573. var startLocalVersion int64
  574. for _, dev := range folder.Devices {
  575. if bytes.Equal(dev.ID, m.id[:]) {
  576. // This is the other side's description of what it knows
  577. // about us. Lets check to see if we can start sending index
  578. // updates directly or need to send the index from start...
  579. if dev.IndexID == myIndexID {
  580. // They say they've seen our index ID before, so we can
  581. // send a delta update only.
  582. if dev.MaxLocalVersion > myLocalVersion {
  583. // Safety check. They claim to have more or newer
  584. // index data than we have - either we have lost
  585. // index data, or reset the index without resetting
  586. // the IndexID, or something else weird has
  587. // happened. We send a full index to reset the
  588. // situation.
  589. l.Infof("Device %v folder %q is delta index compatible, but seems out of sync with reality", deviceID, folder.ID)
  590. startLocalVersion = 0
  591. continue
  592. }
  593. l.Infof("Device %v folder %q is delta index compatible (mlv=%d)", deviceID, folder.ID, dev.MaxLocalVersion)
  594. startLocalVersion = dev.MaxLocalVersion
  595. } else if dev.IndexID != 0 {
  596. // They say they've seen an index ID from us, but it's
  597. // not the right one. Either they are confused or we
  598. // must have reset our database since last talking to
  599. // them. We'll start with a full index transfer.
  600. l.Infof("Device %v folder %q has mismatching index ID for us (%v != %v)", deviceID, folder.ID, dev.IndexID, myIndexID)
  601. startLocalVersion = 0
  602. }
  603. } else if bytes.Equal(dev.ID, deviceID[:]) && dev.IndexID != 0 {
  604. // This is the other side's description of themselves. We
  605. // check to see that it matches the IndexID we have on file,
  606. // otherwise we drop our old index data and expect to get a
  607. // completely new set.
  608. theirIndexID := fs.IndexID(deviceID)
  609. if dev.IndexID == 0 {
  610. // They're not announcing an index ID. This means they
  611. // do not support delta indexes and we should clear any
  612. // information we have from them before accepting their
  613. // index, which will presumably be a full index.
  614. fs.Replace(deviceID, nil)
  615. } else if dev.IndexID != theirIndexID {
  616. // The index ID we have on file is not what they're
  617. // announcing. They must have reset their database and
  618. // will probably send us a full index. We drop any
  619. // information we have and remember this new index ID
  620. // instead.
  621. l.Infof("Device %v folder %q has a new index ID (%v)", deviceID, folder.ID, dev.IndexID)
  622. fs.Replace(deviceID, nil)
  623. fs.SetIndexID(deviceID, dev.IndexID)
  624. }
  625. }
  626. }
  627. go sendIndexes(conn, folder.ID, fs, m.folderIgnores[folder.ID], startLocalVersion)
  628. }
  629. m.fmut.Unlock()
  630. // This breaks if we send multiple CM messages during the same connection.
  631. if len(tempIndexFolders) > 0 {
  632. m.pmut.RLock()
  633. conn, ok := m.conn[deviceID]
  634. m.pmut.RUnlock()
  635. // In case we've got ClusterConfig, and the connection disappeared
  636. // from infront of our nose.
  637. if ok {
  638. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  639. }
  640. }
  641. var changed bool
  642. if m.cfg.Devices()[deviceID].Introducer {
  643. // This device is an introducer. Go through the announced lists of folders
  644. // and devices and add what we are missing.
  645. for _, folder := range cm.Folders {
  646. if _, ok := m.folderDevices[folder.ID]; !ok {
  647. continue
  648. }
  649. nextDevice:
  650. for _, device := range folder.Devices {
  651. var id protocol.DeviceID
  652. copy(id[:], device.ID)
  653. if _, ok := m.cfg.Devices()[id]; !ok {
  654. // The device is currently unknown. Add it to the config.
  655. addresses := []string{"dynamic"}
  656. for _, addr := range device.Addresses {
  657. if addr != "dynamic" {
  658. addresses = append(addresses, addr)
  659. }
  660. }
  661. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  662. newDeviceCfg := config.DeviceConfiguration{
  663. DeviceID: id,
  664. Name: device.Name,
  665. Compression: m.cfg.Devices()[deviceID].Compression,
  666. Addresses: addresses,
  667. CertName: device.CertName,
  668. }
  669. // The introducers' introducers are also our introducers.
  670. if device.Introducer {
  671. l.Infof("Device %v is now also an introducer", id)
  672. newDeviceCfg.Introducer = true
  673. }
  674. m.cfg.SetDevice(newDeviceCfg)
  675. changed = true
  676. }
  677. for _, er := range m.deviceFolders[id] {
  678. if er == folder.ID {
  679. // We already share the folder with this device, so
  680. // nothing to do.
  681. continue nextDevice
  682. }
  683. }
  684. // We don't yet share this folder with this device. Add the device
  685. // to sharing list of the folder.
  686. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  687. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  688. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  689. folderCfg := m.cfg.Folders()[folder.ID]
  690. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  691. DeviceID: id,
  692. })
  693. m.cfg.SetFolder(folderCfg)
  694. changed = true
  695. }
  696. }
  697. }
  698. if changed {
  699. m.cfg.Save()
  700. }
  701. }
  702. // Close removes the peer from the model and closes the underlying connection if possible.
  703. // Implements the protocol.Model interface.
  704. func (m *Model) Close(device protocol.DeviceID, err error) {
  705. l.Infof("Connection to %s closed: %v", device, err)
  706. events.Default.Log(events.DeviceDisconnected, map[string]string{
  707. "id": device.String(),
  708. "error": err.Error(),
  709. })
  710. m.pmut.Lock()
  711. conn, ok := m.conn[device]
  712. if ok {
  713. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  714. closeRawConn(conn)
  715. }
  716. delete(m.conn, device)
  717. delete(m.helloMessages, device)
  718. delete(m.deviceClusterConf, device)
  719. delete(m.deviceDownloads, device)
  720. m.pmut.Unlock()
  721. }
  722. // Request returns the specified data segment by reading it from local disk.
  723. // Implements the protocol.Model interface.
  724. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, fromTemporary bool, buf []byte) error {
  725. if offset < 0 {
  726. return protocol.ErrInvalid
  727. }
  728. if !m.folderSharedWith(folder, deviceID) {
  729. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  730. return protocol.ErrNoSuchFile
  731. }
  732. if deviceID != protocol.LocalDeviceID {
  733. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, len(buf), fromTemporary)
  734. }
  735. m.fmut.RLock()
  736. folderCfg := m.folderCfgs[folder]
  737. folderPath := folderCfg.Path()
  738. folderIgnores := m.folderIgnores[folder]
  739. m.fmut.RUnlock()
  740. // filepath.Join() returns a filepath.Clean()ed path, which (quoting the
  741. // docs for clarity here):
  742. //
  743. // Clean returns the shortest path name equivalent to path by purely lexical
  744. // processing. It applies the following rules iteratively until no further
  745. // processing can be done:
  746. //
  747. // 1. Replace multiple Separator elements with a single one.
  748. // 2. Eliminate each . path name element (the current directory).
  749. // 3. Eliminate each inner .. path name element (the parent directory)
  750. // along with the non-.. element that precedes it.
  751. // 4. Eliminate .. elements that begin a rooted path:
  752. // that is, replace "/.." by "/" at the beginning of a path,
  753. // assuming Separator is '/'.
  754. fn := filepath.Join(folderPath, name)
  755. if !strings.HasPrefix(fn, folderPath) {
  756. // Request tries to escape!
  757. l.Debugf("%v Invalid REQ(in) tries to escape: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  758. return protocol.ErrInvalid
  759. }
  760. if folderIgnores != nil {
  761. // "rn" becomes the relative name of the file within the folder. This is
  762. // different than the original "name" parameter in that it's been
  763. // cleaned from any possible funny business.
  764. if rn, err := filepath.Rel(folderPath, fn); err != nil {
  765. return err
  766. } else if folderIgnores.Match(rn).IsIgnored() {
  767. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  768. return protocol.ErrNoSuchFile
  769. }
  770. }
  771. if info, err := os.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  772. target, _, err := symlinks.Read(fn)
  773. if err != nil {
  774. l.Debugln("symlinks.Read:", err)
  775. if os.IsNotExist(err) {
  776. return protocol.ErrNoSuchFile
  777. }
  778. return protocol.ErrGeneric
  779. }
  780. if _, err := strings.NewReader(target).ReadAt(buf, offset); err != nil {
  781. l.Debugln("symlink.Reader.ReadAt", err)
  782. return protocol.ErrGeneric
  783. }
  784. return nil
  785. }
  786. // Only check temp files if the flag is set, and if we are set to advertise
  787. // the temp indexes.
  788. if fromTemporary && !folderCfg.DisableTempIndexes {
  789. tempFn := filepath.Join(folderPath, defTempNamer.TempName(name))
  790. if err := readOffsetIntoBuf(tempFn, offset, buf); err == nil {
  791. return nil
  792. }
  793. // Fall through to reading from a non-temp file, just incase the temp
  794. // file has finished downloading.
  795. }
  796. err := readOffsetIntoBuf(fn, offset, buf)
  797. if os.IsNotExist(err) {
  798. return protocol.ErrNoSuchFile
  799. } else if err != nil {
  800. return protocol.ErrGeneric
  801. }
  802. return nil
  803. }
  804. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  805. m.fmut.RLock()
  806. fs, ok := m.folderFiles[folder]
  807. m.fmut.RUnlock()
  808. if !ok {
  809. return protocol.FileInfo{}, false
  810. }
  811. f, ok := fs.Get(protocol.LocalDeviceID, file)
  812. return f, ok
  813. }
  814. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  815. m.fmut.RLock()
  816. fs, ok := m.folderFiles[folder]
  817. m.fmut.RUnlock()
  818. if !ok {
  819. return protocol.FileInfo{}, false
  820. }
  821. f, ok := fs.GetGlobal(file)
  822. return f, ok
  823. }
  824. type cFiler struct {
  825. m *Model
  826. r string
  827. }
  828. // Implements scanner.CurrentFiler
  829. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  830. return cf.m.CurrentFolderFile(cf.r, file)
  831. }
  832. // ConnectedTo returns true if we are connected to the named device.
  833. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  834. m.pmut.RLock()
  835. _, ok := m.conn[deviceID]
  836. m.pmut.RUnlock()
  837. if ok {
  838. m.deviceWasSeen(deviceID)
  839. }
  840. return ok
  841. }
  842. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  843. var lines []string
  844. m.fmut.RLock()
  845. cfg, ok := m.folderCfgs[folder]
  846. m.fmut.RUnlock()
  847. if !ok {
  848. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  849. }
  850. if !cfg.HasMarker() {
  851. return lines, nil, fmt.Errorf("Folder %s stopped", folder)
  852. }
  853. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  854. if err != nil {
  855. if os.IsNotExist(err) {
  856. return lines, nil, nil
  857. }
  858. l.Warnln("Loading .stignore:", err)
  859. return lines, nil, err
  860. }
  861. defer fd.Close()
  862. scanner := bufio.NewScanner(fd)
  863. for scanner.Scan() {
  864. lines = append(lines, strings.TrimSpace(scanner.Text()))
  865. }
  866. m.fmut.RLock()
  867. patterns := m.folderIgnores[folder].Patterns()
  868. m.fmut.RUnlock()
  869. return lines, patterns, nil
  870. }
  871. func (m *Model) SetIgnores(folder string, content []string) error {
  872. cfg, ok := m.folderCfgs[folder]
  873. if !ok {
  874. return fmt.Errorf("Folder %s does not exist", folder)
  875. }
  876. path := filepath.Join(cfg.Path(), ".stignore")
  877. fd, err := osutil.CreateAtomic(path, 0644)
  878. if err != nil {
  879. l.Warnln("Saving .stignore:", err)
  880. return err
  881. }
  882. for _, line := range content {
  883. fmt.Fprintln(fd, line)
  884. }
  885. if err := fd.Close(); err != nil {
  886. l.Warnln("Saving .stignore:", err)
  887. return err
  888. }
  889. osutil.HideFile(path)
  890. return m.ScanFolder(folder)
  891. }
  892. // OnHello is called when an device connects to us.
  893. // This allows us to extract some information from the Hello message
  894. // and add it to a list of known devices ahead of any checks.
  895. func (m *Model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloResult) {
  896. for deviceID := range m.cfg.Devices() {
  897. if deviceID == remoteID {
  898. // Existing device, we will get the hello message in AddConnection
  899. // hence do not persist any state here, as the connection might
  900. // get killed before AddConnection
  901. return
  902. }
  903. }
  904. if !m.cfg.IgnoredDevice(remoteID) {
  905. events.Default.Log(events.DeviceRejected, map[string]string{
  906. "name": hello.DeviceName,
  907. "device": remoteID.String(),
  908. "address": addr.String(),
  909. })
  910. }
  911. }
  912. // GetHello is called when we are about to connect to some remote device.
  913. func (m *Model) GetHello(protocol.DeviceID) protocol.HelloIntf {
  914. return &protocol.Hello{
  915. DeviceName: m.deviceName,
  916. ClientName: m.clientName,
  917. ClientVersion: m.clientVersion,
  918. }
  919. }
  920. // AddConnection adds a new peer connection to the model. An initial index will
  921. // be sent to the connected peer, thereafter index updates whenever the local
  922. // folder changes.
  923. func (m *Model) AddConnection(conn connections.Connection, hello protocol.HelloResult) {
  924. deviceID := conn.ID()
  925. m.pmut.Lock()
  926. if _, ok := m.conn[deviceID]; ok {
  927. panic("add existing device")
  928. }
  929. m.conn[deviceID] = conn
  930. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  931. m.helloMessages[deviceID] = hello
  932. event := map[string]string{
  933. "id": deviceID.String(),
  934. "deviceName": hello.DeviceName,
  935. "clientName": hello.ClientName,
  936. "clientVersion": hello.ClientVersion,
  937. "type": conn.Type,
  938. }
  939. addr := conn.RemoteAddr()
  940. if addr != nil {
  941. event["addr"] = addr.String()
  942. }
  943. events.Default.Log(events.DeviceConnected, event)
  944. l.Infof(`Device %s client is "%s %s" named "%s"`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName)
  945. conn.Start()
  946. cm := m.generateClusterConfig(deviceID)
  947. conn.ClusterConfig(cm)
  948. m.pmut.Unlock()
  949. device, ok := m.cfg.Devices()[deviceID]
  950. if ok && (device.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) {
  951. device.Name = hello.DeviceName
  952. m.cfg.SetDevice(device)
  953. m.cfg.Save()
  954. }
  955. m.deviceWasSeen(deviceID)
  956. }
  957. func (m *Model) PauseDevice(device protocol.DeviceID) {
  958. m.pmut.Lock()
  959. m.devicePaused[device] = true
  960. _, ok := m.conn[device]
  961. m.pmut.Unlock()
  962. if ok {
  963. m.Close(device, errors.New("device paused"))
  964. }
  965. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  966. }
  967. func (m *Model) DownloadProgress(device protocol.DeviceID, folder string, updates []protocol.FileDownloadProgressUpdate) {
  968. if !m.folderSharedWith(folder, device) {
  969. return
  970. }
  971. m.fmut.RLock()
  972. cfg, ok := m.folderCfgs[folder]
  973. m.fmut.RUnlock()
  974. if !ok || cfg.Type == config.FolderTypeReadOnly || cfg.DisableTempIndexes {
  975. return
  976. }
  977. m.pmut.RLock()
  978. m.deviceDownloads[device].Update(folder, updates)
  979. state := m.deviceDownloads[device].GetBlockCounts(folder)
  980. m.pmut.RUnlock()
  981. events.Default.Log(events.RemoteDownloadProgress, map[string]interface{}{
  982. "device": device.String(),
  983. "folder": folder,
  984. "state": state,
  985. })
  986. }
  987. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  988. m.pmut.Lock()
  989. m.devicePaused[device] = false
  990. m.pmut.Unlock()
  991. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  992. }
  993. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  994. m.pmut.Lock()
  995. paused := m.devicePaused[device]
  996. m.pmut.Unlock()
  997. return paused
  998. }
  999. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  1000. m.fmut.Lock()
  1001. defer m.fmut.Unlock()
  1002. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  1003. return sr
  1004. }
  1005. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  1006. m.deviceStatRefs[deviceID] = sr
  1007. return sr
  1008. }
  1009. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  1010. m.deviceStatRef(deviceID).WasSeen()
  1011. }
  1012. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  1013. m.fmut.Lock()
  1014. defer m.fmut.Unlock()
  1015. sr, ok := m.folderStatRefs[folder]
  1016. if !ok {
  1017. sr = stats.NewFolderStatisticsReference(m.db, folder)
  1018. m.folderStatRefs[folder] = sr
  1019. }
  1020. return sr
  1021. }
  1022. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  1023. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  1024. }
  1025. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, startLocalVersion int64) {
  1026. deviceID := conn.ID()
  1027. name := conn.Name()
  1028. var err error
  1029. l.Debugf("sendIndexes for %s-%s/%q starting (slv=%d)", deviceID, name, folder, startLocalVersion)
  1030. defer l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  1031. minLocalVer, err := sendIndexTo(startLocalVersion, conn, folder, fs, ignores)
  1032. // Subscribe to LocalIndexUpdated (we have new information to send) and
  1033. // DeviceDisconnected (it might be us who disconnected, so we should
  1034. // exit).
  1035. sub := events.Default.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  1036. defer events.Default.Unsubscribe(sub)
  1037. for err == nil {
  1038. if conn.Closed() {
  1039. // Our work is done.
  1040. return
  1041. }
  1042. // While we have sent a localVersion at least equal to the one
  1043. // currently in the database, wait for the local index to update. The
  1044. // local index may update for other folders than the one we are
  1045. // sending for.
  1046. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  1047. sub.Poll(time.Minute)
  1048. continue
  1049. }
  1050. minLocalVer, err = sendIndexTo(minLocalVer, conn, folder, fs, ignores)
  1051. // Wait a short amount of time before entering the next loop. If there
  1052. // are continuous changes happening to the local index, this gives us
  1053. // time to batch them up a little.
  1054. time.Sleep(250 * time.Millisecond)
  1055. }
  1056. }
  1057. func sendIndexTo(minLocalVer int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) (int64, error) {
  1058. deviceID := conn.ID()
  1059. name := conn.Name()
  1060. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1061. currentBatchSize := 0
  1062. initial := minLocalVer == 0
  1063. maxLocalVer := minLocalVer
  1064. var err error
  1065. sorter := NewIndexSorter()
  1066. defer sorter.Close()
  1067. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1068. f := fi.(protocol.FileInfo)
  1069. if f.LocalVersion <= minLocalVer {
  1070. return true
  1071. }
  1072. if f.LocalVersion > maxLocalVer {
  1073. maxLocalVer = f.LocalVersion
  1074. }
  1075. if ignores.Match(f.Name).IsIgnored() || symlinkInvalid(folder, f) {
  1076. l.Debugln("not sending update for ignored/unsupported symlink", f)
  1077. return true
  1078. }
  1079. sorter.Append(f)
  1080. return true
  1081. })
  1082. sorter.Sorted(func(f protocol.FileInfo) bool {
  1083. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  1084. if initial {
  1085. if err = conn.Index(folder, batch); err != nil {
  1086. return false
  1087. }
  1088. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  1089. initial = false
  1090. } else {
  1091. if err = conn.IndexUpdate(folder, batch); err != nil {
  1092. return false
  1093. }
  1094. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  1095. }
  1096. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  1097. currentBatchSize = 0
  1098. }
  1099. batch = append(batch, f)
  1100. currentBatchSize += f.ProtoSize()
  1101. return true
  1102. })
  1103. if initial && err == nil {
  1104. err = conn.Index(folder, batch)
  1105. if err == nil {
  1106. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  1107. }
  1108. } else if len(batch) > 0 && err == nil {
  1109. err = conn.IndexUpdate(folder, batch)
  1110. if err == nil {
  1111. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  1112. }
  1113. }
  1114. return maxLocalVer, err
  1115. }
  1116. func (m *Model) updateLocalsFromScanning(folder string, fs []protocol.FileInfo) {
  1117. m.updateLocals(folder, fs)
  1118. // Fire the LocalChangeDetected event to notify listeners about local
  1119. // updates.
  1120. m.fmut.RLock()
  1121. path := m.folderCfgs[folder].Path()
  1122. m.fmut.RUnlock()
  1123. m.localChangeDetected(folder, path, fs)
  1124. }
  1125. func (m *Model) updateLocalsFromPulling(folder string, fs []protocol.FileInfo) {
  1126. m.updateLocals(folder, fs)
  1127. }
  1128. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  1129. m.fmut.RLock()
  1130. files := m.folderFiles[folder]
  1131. m.fmut.RUnlock()
  1132. if files == nil {
  1133. // The folder doesn't exist.
  1134. return
  1135. }
  1136. files.Update(protocol.LocalDeviceID, fs)
  1137. filenames := make([]string, len(fs))
  1138. for i, file := range fs {
  1139. filenames[i] = file.Name
  1140. }
  1141. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1142. "folder": folder,
  1143. "items": len(fs),
  1144. "filenames": filenames,
  1145. "version": files.LocalVersion(protocol.LocalDeviceID),
  1146. })
  1147. }
  1148. func (m *Model) localChangeDetected(folder, path string, files []protocol.FileInfo) {
  1149. // For windows paths, strip unwanted chars from the front
  1150. path = strings.Replace(path, `\\?\`, "", 1)
  1151. for _, file := range files {
  1152. objType := "file"
  1153. action := "modified"
  1154. // If our local vector is version 1 AND it is the only version
  1155. // vector so far seen for this file then it is a new file. Else if
  1156. // it is > 1 it's not new, and if it is 1 but another shortId
  1157. // version vector exists then it is new for us but created elsewhere
  1158. // so the file is still not new but modified by us. Only if it is
  1159. // truly new do we change this to 'added', else we leave it as
  1160. // 'modified'.
  1161. if len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1 {
  1162. action = "added"
  1163. }
  1164. if file.IsDirectory() {
  1165. objType = "dir"
  1166. }
  1167. if file.IsDeleted() {
  1168. action = "deleted"
  1169. }
  1170. // The full file path, adjusted to the local path separator character.
  1171. path := filepath.Join(path, filepath.FromSlash(file.Name))
  1172. events.Default.Log(events.LocalChangeDetected, map[string]string{
  1173. "folder": folder,
  1174. "action": action,
  1175. "type": objType,
  1176. "path": path,
  1177. })
  1178. }
  1179. }
  1180. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  1181. m.pmut.RLock()
  1182. nc, ok := m.conn[deviceID]
  1183. m.pmut.RUnlock()
  1184. if !ok {
  1185. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1186. }
  1187. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x ft=%t", m, deviceID, folder, name, offset, size, hash, fromTemporary)
  1188. return nc.Request(folder, name, offset, size, hash, fromTemporary)
  1189. }
  1190. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  1191. if len(cfg.ID) == 0 {
  1192. panic("cannot add empty folder id")
  1193. }
  1194. m.fmut.Lock()
  1195. m.folderCfgs[cfg.ID] = cfg
  1196. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  1197. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  1198. for i, device := range cfg.Devices {
  1199. m.folderDevices[cfg.ID][i] = device.DeviceID
  1200. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  1201. }
  1202. ignores := ignore.New(m.cacheIgnoredFiles)
  1203. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1204. l.Warnln("Loading ignores:", err)
  1205. }
  1206. m.folderIgnores[cfg.ID] = ignores
  1207. m.fmut.Unlock()
  1208. }
  1209. func (m *Model) ScanFolders() map[string]error {
  1210. m.fmut.RLock()
  1211. folders := make([]string, 0, len(m.folderCfgs))
  1212. for folder := range m.folderCfgs {
  1213. folders = append(folders, folder)
  1214. }
  1215. m.fmut.RUnlock()
  1216. errors := make(map[string]error, len(m.folderCfgs))
  1217. errorsMut := sync.NewMutex()
  1218. wg := sync.NewWaitGroup()
  1219. wg.Add(len(folders))
  1220. for _, folder := range folders {
  1221. folder := folder
  1222. go func() {
  1223. err := m.ScanFolder(folder)
  1224. if err != nil {
  1225. errorsMut.Lock()
  1226. errors[folder] = err
  1227. errorsMut.Unlock()
  1228. // Potentially sets the error twice, once in the scanner just
  1229. // by doing a check, and once here, if the error returned is
  1230. // the same one as returned by CheckFolderHealth, though
  1231. // duplicate set is handled by setError.
  1232. m.fmut.RLock()
  1233. srv := m.folderRunners[folder]
  1234. m.fmut.RUnlock()
  1235. srv.setError(err)
  1236. }
  1237. wg.Done()
  1238. }()
  1239. }
  1240. wg.Wait()
  1241. return errors
  1242. }
  1243. func (m *Model) ScanFolder(folder string) error {
  1244. return m.ScanFolderSubdirs(folder, nil)
  1245. }
  1246. func (m *Model) ScanFolderSubdirs(folder string, subs []string) error {
  1247. m.fmut.Lock()
  1248. runner, ok := m.folderRunners[folder]
  1249. m.fmut.Unlock()
  1250. // Folders are added to folderRunners only when they are started. We can't
  1251. // scan them before they have started, so that's what we need to check for
  1252. // here.
  1253. if !ok {
  1254. return errors.New("no such folder")
  1255. }
  1256. return runner.Scan(subs)
  1257. }
  1258. func (m *Model) internalScanFolderSubdirs(folder string, subDirs []string) error {
  1259. for i, sub := range subDirs {
  1260. sub = osutil.NativeFilename(sub)
  1261. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1262. return errors.New("invalid subpath")
  1263. }
  1264. subDirs[i] = sub
  1265. }
  1266. m.fmut.Lock()
  1267. fs := m.folderFiles[folder]
  1268. folderCfg := m.folderCfgs[folder]
  1269. ignores := m.folderIgnores[folder]
  1270. runner, ok := m.folderRunners[folder]
  1271. m.fmut.Unlock()
  1272. // Folders are added to folderRunners only when they are started. We can't
  1273. // scan them before they have started, so that's what we need to check for
  1274. // here.
  1275. if !ok {
  1276. return errors.New("no such folder")
  1277. }
  1278. if err := m.CheckFolderHealth(folder); err != nil {
  1279. runner.setError(err)
  1280. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1281. return err
  1282. }
  1283. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1284. err = fmt.Errorf("loading ignores: %v", err)
  1285. runner.setError(err)
  1286. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1287. return err
  1288. }
  1289. // Clean the list of subitems to ensure that we start at a known
  1290. // directory, and don't scan subdirectories of things we've already
  1291. // scanned.
  1292. subDirs = unifySubs(subDirs, func(f string) bool {
  1293. _, ok := fs.Get(protocol.LocalDeviceID, f)
  1294. return ok
  1295. })
  1296. // The cancel channel is closed whenever we return (such as from an error),
  1297. // to signal the potentially still running walker to stop.
  1298. cancel := make(chan struct{})
  1299. defer close(cancel)
  1300. runner.setState(FolderScanning)
  1301. fchan, err := scanner.Walk(scanner.Config{
  1302. Folder: folderCfg.ID,
  1303. Dir: folderCfg.Path(),
  1304. Subs: subDirs,
  1305. Matcher: ignores,
  1306. BlockSize: protocol.BlockSize,
  1307. TempNamer: defTempNamer,
  1308. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1309. CurrentFiler: cFiler{m, folder},
  1310. MtimeRepo: db.NewVirtualMtimeRepo(m.db, folderCfg.ID),
  1311. IgnorePerms: folderCfg.IgnorePerms,
  1312. AutoNormalize: folderCfg.AutoNormalize,
  1313. Hashers: m.numHashers(folder),
  1314. ShortID: m.shortID,
  1315. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1316. Cancel: cancel,
  1317. })
  1318. if err != nil {
  1319. // The error we get here is likely an OS level error, which might not be
  1320. // as readable as our health check errors. Check if we can get a health
  1321. // check error first, and use that if it's available.
  1322. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1323. err = ferr
  1324. }
  1325. runner.setError(err)
  1326. return err
  1327. }
  1328. batchSizeFiles := 100
  1329. batchSizeBlocks := 2048 // about 256 MB
  1330. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1331. blocksHandled := 0
  1332. for f := range fchan {
  1333. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1334. if err := m.CheckFolderHealth(folder); err != nil {
  1335. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1336. return err
  1337. }
  1338. m.updateLocalsFromScanning(folder, batch)
  1339. batch = batch[:0]
  1340. blocksHandled = 0
  1341. }
  1342. batch = append(batch, f)
  1343. blocksHandled += len(f.Blocks)
  1344. }
  1345. if err := m.CheckFolderHealth(folder); err != nil {
  1346. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1347. return err
  1348. } else if len(batch) > 0 {
  1349. m.updateLocalsFromScanning(folder, batch)
  1350. }
  1351. if len(subDirs) == 0 {
  1352. // If we have no specific subdirectories to traverse, set it to one
  1353. // empty prefix so we traverse the entire folder contents once.
  1354. subDirs = []string{""}
  1355. }
  1356. // Do a scan of the database for each prefix, to check for deleted files.
  1357. batch = batch[:0]
  1358. for _, sub := range subDirs {
  1359. var iterError error
  1360. fs.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  1361. f := fi.(db.FileInfoTruncated)
  1362. if !f.IsDeleted() {
  1363. if len(batch) == batchSizeFiles {
  1364. if err := m.CheckFolderHealth(folder); err != nil {
  1365. iterError = err
  1366. return false
  1367. }
  1368. m.updateLocalsFromScanning(folder, batch)
  1369. batch = batch[:0]
  1370. }
  1371. if !f.IsInvalid() && (ignores.Match(f.Name).IsIgnored() || symlinkInvalid(folder, f)) {
  1372. // File has been ignored or an unsupported symlink. Set invalid bit.
  1373. l.Debugln("setting invalid bit on ignored", f)
  1374. nf := protocol.FileInfo{
  1375. Name: f.Name,
  1376. Type: f.Type,
  1377. Size: f.Size,
  1378. Modified: f.Modified,
  1379. Permissions: f.Permissions,
  1380. NoPermissions: f.NoPermissions,
  1381. Invalid: true,
  1382. Version: f.Version, // The file is still the same, so don't bump version
  1383. }
  1384. batch = append(batch, nf)
  1385. } else if _, err := osutil.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1386. // File has been deleted.
  1387. // We don't specifically verify that the error is
  1388. // os.IsNotExist because there is a corner case when a
  1389. // directory is suddenly transformed into a file. When that
  1390. // happens, files that were in the directory (that is now a
  1391. // file) are deleted but will return a confusing error ("not a
  1392. // directory") when we try to Lstat() them.
  1393. nf := protocol.FileInfo{
  1394. Name: f.Name,
  1395. Type: f.Type,
  1396. Size: f.Size,
  1397. Modified: f.Modified,
  1398. Deleted: true,
  1399. Version: f.Version.Update(m.shortID),
  1400. }
  1401. batch = append(batch, nf)
  1402. }
  1403. }
  1404. return true
  1405. })
  1406. if iterError != nil {
  1407. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1408. return iterError
  1409. }
  1410. }
  1411. if err := m.CheckFolderHealth(folder); err != nil {
  1412. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1413. return err
  1414. } else if len(batch) > 0 {
  1415. m.updateLocalsFromScanning(folder, batch)
  1416. }
  1417. m.folderStatRef(folder).ScanCompleted()
  1418. runner.setState(FolderIdle)
  1419. return nil
  1420. }
  1421. func (m *Model) DelayScan(folder string, next time.Duration) {
  1422. m.fmut.Lock()
  1423. runner, ok := m.folderRunners[folder]
  1424. m.fmut.Unlock()
  1425. if !ok {
  1426. return
  1427. }
  1428. runner.DelayScan(next)
  1429. }
  1430. // numHashers returns the number of hasher routines to use for a given folder,
  1431. // taking into account configuration and available CPU cores.
  1432. func (m *Model) numHashers(folder string) int {
  1433. m.fmut.Lock()
  1434. folderCfg := m.folderCfgs[folder]
  1435. numFolders := len(m.folderCfgs)
  1436. m.fmut.Unlock()
  1437. if folderCfg.Hashers > 0 {
  1438. // Specific value set in the config, use that.
  1439. return folderCfg.Hashers
  1440. }
  1441. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1442. // Interactive operating systems; don't load the system too heavily by
  1443. // default.
  1444. return 1
  1445. }
  1446. // For other operating systems and architectures, lets try to get some
  1447. // work done... Divide the available CPU cores among the configured
  1448. // folders.
  1449. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1450. return perFolder
  1451. }
  1452. return 1
  1453. }
  1454. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1455. // the given peer device
  1456. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1457. var message protocol.ClusterConfig
  1458. m.fmut.RLock()
  1459. for _, folder := range m.deviceFolders[device] {
  1460. folderCfg := m.cfg.Folders()[folder]
  1461. fs := m.folderFiles[folder]
  1462. protocolFolder := protocol.Folder{
  1463. ID: folder,
  1464. Label: folderCfg.Label,
  1465. ReadOnly: folderCfg.Type == config.FolderTypeReadOnly,
  1466. IgnorePermissions: folderCfg.IgnorePerms,
  1467. IgnoreDelete: folderCfg.IgnoreDelete,
  1468. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1469. }
  1470. for _, device := range m.folderDevices[folder] {
  1471. // DeviceID is a value type, but with an underlying array. Copy it
  1472. // so we don't grab aliases to the same array later on in device[:]
  1473. device := device
  1474. // TODO: Set read only bit when relevant, and when we have per device
  1475. // access controls.
  1476. deviceCfg := m.cfg.Devices()[device]
  1477. var indexID protocol.IndexID
  1478. var maxLocalVersion int64
  1479. if device == m.id {
  1480. indexID = fs.IndexID(protocol.LocalDeviceID)
  1481. maxLocalVersion = fs.LocalVersion(protocol.LocalDeviceID)
  1482. } else {
  1483. indexID = fs.IndexID(device)
  1484. maxLocalVersion = fs.LocalVersion(device)
  1485. }
  1486. protocolDevice := protocol.Device{
  1487. ID: device[:],
  1488. Name: deviceCfg.Name,
  1489. Addresses: deviceCfg.Addresses,
  1490. Compression: deviceCfg.Compression,
  1491. CertName: deviceCfg.CertName,
  1492. Introducer: deviceCfg.Introducer,
  1493. IndexID: indexID,
  1494. MaxLocalVersion: maxLocalVersion,
  1495. }
  1496. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1497. }
  1498. message.Folders = append(message.Folders, protocolFolder)
  1499. }
  1500. m.fmut.RUnlock()
  1501. return message
  1502. }
  1503. func (m *Model) State(folder string) (string, time.Time, error) {
  1504. m.fmut.RLock()
  1505. runner, ok := m.folderRunners[folder]
  1506. m.fmut.RUnlock()
  1507. if !ok {
  1508. // The returned error should be an actual folder error, so returning
  1509. // errors.New("does not exist") or similar here would be
  1510. // inappropriate.
  1511. return "", time.Time{}, nil
  1512. }
  1513. state, changed, err := runner.getState()
  1514. return state.String(), changed, err
  1515. }
  1516. func (m *Model) Override(folder string) {
  1517. m.fmut.RLock()
  1518. fs, ok := m.folderFiles[folder]
  1519. runner := m.folderRunners[folder]
  1520. m.fmut.RUnlock()
  1521. if !ok {
  1522. return
  1523. }
  1524. runner.setState(FolderScanning)
  1525. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1526. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1527. need := fi.(protocol.FileInfo)
  1528. if len(batch) == indexBatchSize {
  1529. m.updateLocalsFromScanning(folder, batch)
  1530. batch = batch[:0]
  1531. }
  1532. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1533. if !ok || have.Name != need.Name {
  1534. // We are missing the file
  1535. need.Deleted = true
  1536. need.Blocks = nil
  1537. need.Version = need.Version.Update(m.shortID)
  1538. } else {
  1539. // We have the file, replace with our version
  1540. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1541. need = have
  1542. }
  1543. need.LocalVersion = 0
  1544. batch = append(batch, need)
  1545. return true
  1546. })
  1547. if len(batch) > 0 {
  1548. m.updateLocalsFromScanning(folder, batch)
  1549. }
  1550. runner.setState(FolderIdle)
  1551. }
  1552. // CurrentLocalVersion returns the change version for the given folder.
  1553. // This is guaranteed to increment if the contents of the local folder has
  1554. // changed.
  1555. func (m *Model) CurrentLocalVersion(folder string) (int64, bool) {
  1556. m.fmut.RLock()
  1557. fs, ok := m.folderFiles[folder]
  1558. m.fmut.RUnlock()
  1559. if !ok {
  1560. // The folder might not exist, since this can be called with a user
  1561. // specified folder name from the REST interface.
  1562. return 0, false
  1563. }
  1564. return fs.LocalVersion(protocol.LocalDeviceID), true
  1565. }
  1566. // RemoteLocalVersion returns the change version for the given folder, as
  1567. // sent by remote peers. This is guaranteed to increment if the contents of
  1568. // the remote or global folder has changed.
  1569. func (m *Model) RemoteLocalVersion(folder string) (int64, bool) {
  1570. m.fmut.RLock()
  1571. defer m.fmut.RUnlock()
  1572. fs, ok := m.folderFiles[folder]
  1573. if !ok {
  1574. // The folder might not exist, since this can be called with a user
  1575. // specified folder name from the REST interface.
  1576. return 0, false
  1577. }
  1578. var ver int64
  1579. for _, n := range m.folderDevices[folder] {
  1580. ver += fs.LocalVersion(n)
  1581. }
  1582. return ver, true
  1583. }
  1584. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1585. m.fmut.RLock()
  1586. files, ok := m.folderFiles[folder]
  1587. m.fmut.RUnlock()
  1588. if !ok {
  1589. return nil
  1590. }
  1591. output := make(map[string]interface{})
  1592. sep := string(filepath.Separator)
  1593. prefix = osutil.NativeFilename(prefix)
  1594. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1595. prefix = prefix + sep
  1596. }
  1597. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1598. f := fi.(db.FileInfoTruncated)
  1599. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1600. return true
  1601. }
  1602. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1603. var dir, base string
  1604. if f.IsDirectory() && !f.IsSymlink() {
  1605. dir = f.Name
  1606. } else {
  1607. dir = filepath.Dir(f.Name)
  1608. base = filepath.Base(f.Name)
  1609. }
  1610. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1611. return true
  1612. }
  1613. last := output
  1614. if dir != "." {
  1615. for _, path := range strings.Split(dir, sep) {
  1616. directory, ok := last[path]
  1617. if !ok {
  1618. newdir := make(map[string]interface{})
  1619. last[path] = newdir
  1620. last = newdir
  1621. } else {
  1622. last = directory.(map[string]interface{})
  1623. }
  1624. }
  1625. }
  1626. if !dirsonly && base != "" {
  1627. last[base] = []interface{}{
  1628. time.Unix(f.Modified, 0), f.FileSize(),
  1629. }
  1630. }
  1631. return true
  1632. })
  1633. return output
  1634. }
  1635. func (m *Model) Availability(folder, file string, version protocol.Vector, block protocol.BlockInfo) []Availability {
  1636. // Acquire this lock first, as the value returned from foldersFiles can
  1637. // get heavily modified on Close()
  1638. m.pmut.RLock()
  1639. defer m.pmut.RUnlock()
  1640. m.fmut.RLock()
  1641. fs, ok := m.folderFiles[folder]
  1642. devices := m.folderDevices[folder]
  1643. m.fmut.RUnlock()
  1644. if !ok {
  1645. return nil
  1646. }
  1647. var availabilities []Availability
  1648. for _, device := range fs.Availability(file) {
  1649. _, ok := m.conn[device]
  1650. if ok {
  1651. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  1652. }
  1653. }
  1654. for _, device := range devices {
  1655. if m.deviceDownloads[device].Has(folder, file, version, int32(block.Offset/protocol.BlockSize)) {
  1656. availabilities = append(availabilities, Availability{ID: device, FromTemporary: true})
  1657. }
  1658. }
  1659. return availabilities
  1660. }
  1661. // BringToFront bumps the given files priority in the job queue.
  1662. func (m *Model) BringToFront(folder, file string) {
  1663. m.pmut.RLock()
  1664. defer m.pmut.RUnlock()
  1665. runner, ok := m.folderRunners[folder]
  1666. if ok {
  1667. runner.BringToFront(file)
  1668. }
  1669. }
  1670. // CheckFolderHealth checks the folder for common errors and returns the
  1671. // current folder error, or nil if the folder is healthy.
  1672. func (m *Model) CheckFolderHealth(id string) error {
  1673. folder, ok := m.cfg.Folders()[id]
  1674. if !ok {
  1675. return errors.New("folder does not exist")
  1676. }
  1677. // Check for folder errors, with the most serious and specific first and
  1678. // generic ones like out of space on the home disk later. Note the
  1679. // inverted error flow (err==nil checks) here.
  1680. err := m.checkFolderPath(folder)
  1681. if err == nil {
  1682. err = m.checkFolderFreeSpace(folder)
  1683. }
  1684. if err == nil {
  1685. err = m.checkHomeDiskFree()
  1686. }
  1687. // Set or clear the error on the runner, which also does logging and
  1688. // generates events and stuff.
  1689. m.runnerExchangeError(folder, err)
  1690. return err
  1691. }
  1692. // checkFolderPath returns nil if the folder path exists and has the marker file.
  1693. func (m *Model) checkFolderPath(folder config.FolderConfiguration) error {
  1694. if folder.Path() == "" {
  1695. return errFolderPathEmpty
  1696. }
  1697. if fi, err := os.Stat(folder.Path()); err != nil || !fi.IsDir() {
  1698. return errFolderPathMissing
  1699. }
  1700. if !folder.HasMarker() {
  1701. return errFolderMarkerMissing
  1702. }
  1703. return nil
  1704. }
  1705. // checkFolderFreeSpace returns nil if the folder has the required amount of
  1706. // free space, or if folder free space checking is disabled.
  1707. func (m *Model) checkFolderFreeSpace(folder config.FolderConfiguration) error {
  1708. if folder.MinDiskFreePct <= 0 {
  1709. return nil
  1710. }
  1711. free, err := osutil.DiskFreePercentage(folder.Path())
  1712. if err == nil && free < folder.MinDiskFreePct {
  1713. return errFolderNoSpace
  1714. }
  1715. return nil
  1716. }
  1717. // checkHomeDiskFree returns nil if the home disk has the required amount of
  1718. // free space, or if home disk free space checking is disabled.
  1719. func (m *Model) checkHomeDiskFree() error {
  1720. minFree := m.cfg.Options().MinHomeDiskFreePct
  1721. if minFree <= 0 {
  1722. return nil
  1723. }
  1724. free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath())
  1725. if err == nil && free < minFree {
  1726. return errHomeDiskNoSpace
  1727. }
  1728. return nil
  1729. }
  1730. // runnerExchangeError sets the given error (which way be nil) on the folder
  1731. // runner. If the error differs from any previous error, logging and events
  1732. // happen.
  1733. func (m *Model) runnerExchangeError(folder config.FolderConfiguration, err error) {
  1734. m.fmut.RLock()
  1735. runner, runnerExists := m.folderRunners[folder.ID]
  1736. m.fmut.RUnlock()
  1737. var oldErr error
  1738. if runnerExists {
  1739. _, _, oldErr = runner.getState()
  1740. }
  1741. if err != nil {
  1742. if oldErr != nil && oldErr.Error() != err.Error() {
  1743. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1744. } else if oldErr == nil {
  1745. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1746. }
  1747. if runnerExists {
  1748. runner.setError(err)
  1749. }
  1750. } else if oldErr != nil {
  1751. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1752. if runnerExists {
  1753. runner.clearError()
  1754. }
  1755. }
  1756. }
  1757. func (m *Model) ResetFolder(folder string) {
  1758. l.Infof("Cleaning data for folder %q", folder)
  1759. db.DropFolder(m.db, folder)
  1760. }
  1761. func (m *Model) String() string {
  1762. return fmt.Sprintf("model@%p", m)
  1763. }
  1764. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1765. return nil
  1766. }
  1767. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1768. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1769. // Go through the folder configs and figure out if we need to restart or not.
  1770. fromFolders := mapFolders(from.Folders)
  1771. toFolders := mapFolders(to.Folders)
  1772. for folderID, cfg := range toFolders {
  1773. if _, ok := fromFolders[folderID]; !ok {
  1774. // A folder was added.
  1775. l.Debugln(m, "adding folder", folderID)
  1776. m.AddFolder(cfg)
  1777. m.StartFolder(folderID)
  1778. // Drop connections to all devices that can now share the new
  1779. // folder.
  1780. m.pmut.Lock()
  1781. for _, dev := range cfg.DeviceIDs() {
  1782. if conn, ok := m.conn[dev]; ok {
  1783. closeRawConn(conn)
  1784. }
  1785. }
  1786. m.pmut.Unlock()
  1787. }
  1788. }
  1789. for folderID, fromCfg := range fromFolders {
  1790. toCfg, ok := toFolders[folderID]
  1791. if !ok {
  1792. // The folder was removed.
  1793. m.RemoveFolder(folderID)
  1794. continue
  1795. }
  1796. // This folder exists on both sides. Compare the device lists, as we
  1797. // can handle adding a device (but not currently removing one).
  1798. fromDevs := mapDevices(fromCfg.DeviceIDs())
  1799. toDevs := mapDevices(toCfg.DeviceIDs())
  1800. for dev := range fromDevs {
  1801. if _, ok := toDevs[dev]; !ok {
  1802. // A device was removed. Requires restart.
  1803. l.Debugln(m, "requires restart, removing device", dev, "from folder", folderID)
  1804. return false
  1805. }
  1806. }
  1807. for dev := range toDevs {
  1808. if _, ok := fromDevs[dev]; !ok {
  1809. // A device was added. Handle it!
  1810. m.fmut.Lock()
  1811. m.pmut.Lock()
  1812. m.folderCfgs[folderID] = toCfg
  1813. m.folderDevices[folderID] = append(m.folderDevices[folderID], dev)
  1814. m.deviceFolders[dev] = append(m.deviceFolders[dev], folderID)
  1815. // If we already have a connection to this device, we should
  1816. // disconnect it so that we start sharing the folder with it.
  1817. // We close the underlying connection and let the normal error
  1818. // handling kick in to clean up and reconnect.
  1819. if conn, ok := m.conn[dev]; ok {
  1820. closeRawConn(conn)
  1821. }
  1822. m.pmut.Unlock()
  1823. m.fmut.Unlock()
  1824. }
  1825. }
  1826. // Check if anything else differs, apart from the device list and label.
  1827. fromCfg.Devices = nil
  1828. toCfg.Devices = nil
  1829. fromCfg.Label = ""
  1830. toCfg.Label = ""
  1831. if !reflect.DeepEqual(fromCfg, toCfg) {
  1832. l.Debugln(m, "requires restart, folder", folderID, "configuration differs")
  1833. return false
  1834. }
  1835. }
  1836. // Removing a device requires restart
  1837. toDevs := mapDeviceCfgs(from.Devices)
  1838. for _, dev := range from.Devices {
  1839. if _, ok := toDevs[dev.DeviceID]; !ok {
  1840. l.Debugln(m, "requires restart, device", dev.DeviceID, "was removed")
  1841. return false
  1842. }
  1843. }
  1844. // Some options don't require restart as those components handle it fine
  1845. // by themselves.
  1846. from.Options.URAccepted = to.Options.URAccepted
  1847. from.Options.URUniqueID = to.Options.URUniqueID
  1848. from.Options.ListenAddresses = to.Options.ListenAddresses
  1849. from.Options.RelaysEnabled = to.Options.RelaysEnabled
  1850. // All of the other generic options require restart. Or at least they may;
  1851. // removing this check requires going through those options carefully and
  1852. // making sure there are individual services that handle them correctly.
  1853. // This code is the "original" requires-restart check and protects other
  1854. // components that haven't yet been converted to VerifyConfig/CommitConfig
  1855. // handling.
  1856. if !reflect.DeepEqual(from.Options, to.Options) {
  1857. l.Debugln(m, "requires restart, options differ")
  1858. return false
  1859. }
  1860. return true
  1861. }
  1862. // mapFolders returns a map of folder ID to folder configuration for the given
  1863. // slice of folder configurations.
  1864. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1865. m := make(map[string]config.FolderConfiguration, len(folders))
  1866. for _, cfg := range folders {
  1867. m[cfg.ID] = cfg
  1868. }
  1869. return m
  1870. }
  1871. // mapDevices returns a map of device ID to nothing for the given slice of
  1872. // device IDs.
  1873. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1874. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1875. for _, dev := range devices {
  1876. m[dev] = struct{}{}
  1877. }
  1878. return m
  1879. }
  1880. // mapDeviceCfgs returns a map of device ID to nothing for the given slice of
  1881. // device configurations.
  1882. func mapDeviceCfgs(devices []config.DeviceConfiguration) map[protocol.DeviceID]struct{} {
  1883. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1884. for _, dev := range devices {
  1885. m[dev.DeviceID] = struct{}{}
  1886. }
  1887. return m
  1888. }
  1889. func filterIndex(folder string, fs []protocol.FileInfo, dropDeletes bool, ignores *ignore.Matcher) []protocol.FileInfo {
  1890. for i := 0; i < len(fs); {
  1891. if fs[i].IsDeleted() && dropDeletes {
  1892. l.Debugln("dropping update for undesired delete", fs[i])
  1893. fs[i] = fs[len(fs)-1]
  1894. fs = fs[:len(fs)-1]
  1895. } else if symlinkInvalid(folder, fs[i]) {
  1896. l.Debugln("dropping update for unsupported symlink", fs[i])
  1897. fs[i] = fs[len(fs)-1]
  1898. fs = fs[:len(fs)-1]
  1899. } else if ignores != nil && ignores.Match(fs[i].Name).IsIgnored() {
  1900. l.Debugln("dropping update for ignored item", fs[i])
  1901. fs[i] = fs[len(fs)-1]
  1902. fs = fs[:len(fs)-1]
  1903. } else {
  1904. i++
  1905. }
  1906. }
  1907. return fs
  1908. }
  1909. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1910. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1911. symlinkWarning.Do(func() {
  1912. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1913. })
  1914. // Need to type switch for the concrete type to be able to access fields...
  1915. var name string
  1916. switch fi := fi.(type) {
  1917. case protocol.FileInfo:
  1918. name = fi.Name
  1919. case db.FileInfoTruncated:
  1920. name = fi.Name
  1921. }
  1922. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1923. return true
  1924. }
  1925. return false
  1926. }
  1927. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1928. // Returns the resulting slice, plus how much elements are left to skip or
  1929. // copy to satisfy the values which were provided, given the slice is not
  1930. // big enough.
  1931. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1932. l := len(data)
  1933. if l <= skip {
  1934. return []string{}, skip - l, get
  1935. } else if l < skip+get {
  1936. return data[skip:l], 0, get - (l - skip)
  1937. }
  1938. return data[skip : skip+get], 0, 0
  1939. }
  1940. func closeRawConn(conn io.Closer) error {
  1941. if conn, ok := conn.(*tls.Conn); ok {
  1942. // If the underlying connection is a *tls.Conn, Close() does more
  1943. // than it says on the tin. Specifically, it sends a TLS alert
  1944. // message, which might block forever if the connection is dead
  1945. // and we don't have a deadline set.
  1946. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1947. }
  1948. return conn.Close()
  1949. }
  1950. func stringSliceWithout(ss []string, s string) []string {
  1951. for i := range ss {
  1952. if ss[i] == s {
  1953. copy(ss[i:], ss[i+1:])
  1954. ss = ss[:len(ss)-1]
  1955. return ss
  1956. }
  1957. }
  1958. return ss
  1959. }
  1960. func readOffsetIntoBuf(file string, offset int64, buf []byte) error {
  1961. fd, err := os.Open(file)
  1962. if err != nil {
  1963. l.Debugln("readOffsetIntoBuf.Open", file, err)
  1964. return err
  1965. }
  1966. defer fd.Close()
  1967. _, err = fd.ReadAt(buf, offset)
  1968. if err != nil {
  1969. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  1970. }
  1971. return err
  1972. }
  1973. // The exists function is expected to return true for all known paths
  1974. // (excluding "" and ".")
  1975. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  1976. subs := trimUntilParentKnown(dirs, exists)
  1977. sort.Strings(subs)
  1978. return simplifySortedPaths(subs)
  1979. }
  1980. func trimUntilParentKnown(dirs []string, exists func(dir string) bool) []string {
  1981. var subs []string
  1982. for _, sub := range dirs {
  1983. for sub != "" && sub != ".stfolder" && sub != ".stignore" {
  1984. sub = filepath.Clean(sub)
  1985. parent := filepath.Dir(sub)
  1986. if parent == "." || exists(parent) {
  1987. break
  1988. }
  1989. sub = parent
  1990. if sub == "." || sub == string(filepath.Separator) {
  1991. // Shortcut. We are going to scan the full folder, so we can
  1992. // just return an empty list of subs at this point.
  1993. return nil
  1994. }
  1995. }
  1996. if sub == "" {
  1997. return nil
  1998. }
  1999. subs = append(subs, sub)
  2000. }
  2001. return subs
  2002. }
  2003. func simplifySortedPaths(subs []string) []string {
  2004. var cleaned []string
  2005. next:
  2006. for _, sub := range subs {
  2007. for _, existing := range cleaned {
  2008. if sub == existing || strings.HasPrefix(sub, existing+string(os.PathSeparator)) {
  2009. continue next
  2010. }
  2011. }
  2012. cleaned = append(cleaned, sub)
  2013. }
  2014. return cleaned
  2015. }
  2016. // makeForgetUpdate takes an index update and constructs a download progress update
  2017. // causing to forget any progress for files which we've just been sent.
  2018. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  2019. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  2020. for _, file := range files {
  2021. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  2022. continue
  2023. }
  2024. updates = append(updates, protocol.FileDownloadProgressUpdate{
  2025. Name: file.Name,
  2026. Version: file.Version,
  2027. UpdateType: protocol.UpdateTypeForget,
  2028. })
  2029. }
  2030. return updates
  2031. }