model.go 55 KB

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