model.go 64 KB

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