model.go 54 KB

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