model.go 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  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. "clientName": cm.ClientName,
  506. "clientVersion": cm.ClientVersion,
  507. }
  508. if conn, ok := m.conn[deviceID]; ok {
  509. event["type"] = conn.Type.String()
  510. addr := conn.RemoteAddr()
  511. if addr != nil {
  512. event["addr"] = addr.String()
  513. }
  514. }
  515. m.pmut.Unlock()
  516. events.Default.Log(events.DeviceConnected, event)
  517. l.Infof(`Device %s client is "%s %s"`, deviceID, cm.ClientName, cm.ClientVersion)
  518. var changed bool
  519. if name := cm.GetOption("name"); name != "" {
  520. l.Infof("Device %s name is %q", deviceID, name)
  521. device, ok := m.cfg.Devices()[deviceID]
  522. if ok && device.Name == "" {
  523. device.Name = name
  524. m.cfg.SetDevice(device)
  525. changed = true
  526. }
  527. }
  528. if m.cfg.Devices()[deviceID].Introducer {
  529. // This device is an introducer. Go through the announced lists of folders
  530. // and devices and add what we are missing.
  531. for _, folder := range cm.Folders {
  532. // If we don't have this folder yet, skip it. Ideally, we'd
  533. // offer up something in the GUI to create the folder, but for the
  534. // moment we only handle folders that we already have.
  535. if _, ok := m.folderDevices[folder.ID]; !ok {
  536. continue
  537. }
  538. nextDevice:
  539. for _, device := range folder.Devices {
  540. var id protocol.DeviceID
  541. copy(id[:], device.ID)
  542. if _, ok := m.cfg.Devices()[id]; !ok {
  543. // The device is currently unknown. Add it to the config.
  544. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  545. newDeviceCfg := config.DeviceConfiguration{
  546. DeviceID: id,
  547. Compression: m.cfg.Devices()[deviceID].Compression,
  548. Addresses: []string{"dynamic"},
  549. }
  550. // The introducers' introducers are also our introducers.
  551. if device.Flags&protocol.FlagIntroducer != 0 {
  552. l.Infof("Device %v is now also an introducer", id)
  553. newDeviceCfg.Introducer = true
  554. }
  555. m.cfg.SetDevice(newDeviceCfg)
  556. changed = true
  557. }
  558. for _, er := range m.deviceFolders[id] {
  559. if er == folder.ID {
  560. // We already share the folder with this device, so
  561. // nothing to do.
  562. continue nextDevice
  563. }
  564. }
  565. // We don't yet share this folder with this device. Add the device
  566. // to sharing list of the folder.
  567. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  568. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  569. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  570. folderCfg := m.cfg.Folders()[folder.ID]
  571. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  572. DeviceID: id,
  573. })
  574. m.cfg.SetFolder(folderCfg)
  575. changed = true
  576. }
  577. }
  578. }
  579. if changed {
  580. m.cfg.Save()
  581. }
  582. }
  583. // Close removes the peer from the model and closes the underlying connection if possible.
  584. // Implements the protocol.Model interface.
  585. func (m *Model) Close(device protocol.DeviceID, err error) {
  586. l.Infof("Connection to %s closed: %v", device, err)
  587. events.Default.Log(events.DeviceDisconnected, map[string]string{
  588. "id": device.String(),
  589. "error": err.Error(),
  590. })
  591. m.pmut.Lock()
  592. m.fmut.RLock()
  593. for _, folder := range m.deviceFolders[device] {
  594. m.folderFiles[folder].Replace(device, nil)
  595. }
  596. m.fmut.RUnlock()
  597. conn, ok := m.conn[device]
  598. if ok {
  599. closeRawConn(conn)
  600. }
  601. delete(m.conn, device)
  602. delete(m.deviceVer, device)
  603. m.pmut.Unlock()
  604. }
  605. // Request returns the specified data segment by reading it from local disk.
  606. // Implements the protocol.Model interface.
  607. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, flags uint32, options []protocol.Option, buf []byte) error {
  608. if offset < 0 {
  609. return protocol.ErrNoSuchFile
  610. }
  611. if !m.folderSharedWith(folder, deviceID) {
  612. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  613. return protocol.ErrNoSuchFile
  614. }
  615. if flags != 0 {
  616. // We don't currently support or expect any flags.
  617. return fmt.Errorf("protocol error: unknown flags 0x%x in Request message", flags)
  618. }
  619. // Verify that the requested file exists in the local model. We only need
  620. // to validate this file if we haven't done so recently, so we keep a
  621. // cache of successfull results. "Recently" can be quite a long time, as
  622. // we remove validation cache entries when we detect local changes. If
  623. // we're out of sync here and the file actually doesn't exist any more, or
  624. // has shrunk or something, then we'll anyway get a read error that we
  625. // pass on to the other side.
  626. m.rvmut.RLock()
  627. validated := m.reqValidationCache[folder+"/"+name]
  628. m.rvmut.RUnlock()
  629. if time.Since(validated) > reqValidationTime {
  630. m.fmut.RLock()
  631. folderFiles, ok := m.folderFiles[folder]
  632. m.fmut.RUnlock()
  633. if !ok {
  634. l.Warnf("Request from %s for file %s in nonexistent folder %q", deviceID, name, folder)
  635. return protocol.ErrNoSuchFile
  636. }
  637. // This call is really expensive for large files, as we load the full
  638. // block list which may be megabytes and megabytes of data to allocate
  639. // space for, read, and deserialize.
  640. lf, ok := folderFiles.Get(protocol.LocalDeviceID, name)
  641. if !ok {
  642. return protocol.ErrNoSuchFile
  643. }
  644. if lf.IsInvalid() || lf.IsDeleted() {
  645. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d; invalid: %v", m, deviceID, folder, name, offset, len(buf), lf)
  646. return protocol.ErrInvalid
  647. }
  648. if offset > lf.Size() {
  649. l.Debugf("%v REQ(in; nonexistent): %s: %q o=%d s=%d", m, deviceID, name, offset, len(buf))
  650. return protocol.ErrNoSuchFile
  651. }
  652. m.rvmut.Lock()
  653. m.reqValidationCache[folder+"/"+name] = time.Now()
  654. if len(m.reqValidationCache) > reqValidationCacheSize {
  655. // Don't let the cache grow infinitely
  656. for name, validated := range m.reqValidationCache {
  657. if time.Since(validated) > time.Minute {
  658. delete(m.reqValidationCache, name)
  659. }
  660. }
  661. if len(m.reqValidationCache) > reqValidationCacheSize*9/10 {
  662. // The first clean didn't help much, we're still over 90%
  663. // full; we may have synced a lot of files lately. Prune the
  664. // cache more aggressively by removing every other item so we
  665. // don't get stuck doing useless cache cleaning.
  666. i := 0
  667. for name := range m.reqValidationCache {
  668. if i%2 == 0 {
  669. delete(m.reqValidationCache, name)
  670. }
  671. i++
  672. }
  673. }
  674. }
  675. m.rvmut.Unlock()
  676. }
  677. if deviceID != protocol.LocalDeviceID {
  678. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  679. }
  680. m.fmut.RLock()
  681. fn := filepath.Join(m.folderCfgs[folder].Path(), name)
  682. m.fmut.RUnlock()
  683. var reader io.ReaderAt
  684. var err error
  685. if info, err := os.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  686. target, _, err := symlinks.Read(fn)
  687. if err != nil {
  688. return err
  689. }
  690. reader = strings.NewReader(target)
  691. } else {
  692. // Cannot easily cache fd's because we might need to delete the file
  693. // at any moment.
  694. reader, err = os.Open(fn)
  695. if err != nil {
  696. return err
  697. }
  698. defer reader.(*os.File).Close()
  699. }
  700. _, err = reader.ReadAt(buf, offset)
  701. if err != nil {
  702. return err
  703. }
  704. return nil
  705. }
  706. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  707. m.fmut.RLock()
  708. fs, ok := m.folderFiles[folder]
  709. m.fmut.RUnlock()
  710. if !ok {
  711. return protocol.FileInfo{}, false
  712. }
  713. f, ok := fs.Get(protocol.LocalDeviceID, file)
  714. return f, ok
  715. }
  716. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  717. m.fmut.RLock()
  718. fs, ok := m.folderFiles[folder]
  719. m.fmut.RUnlock()
  720. if !ok {
  721. return protocol.FileInfo{}, false
  722. }
  723. f, ok := fs.GetGlobal(file)
  724. return f, ok
  725. }
  726. type cFiler struct {
  727. m *Model
  728. r string
  729. }
  730. // Implements scanner.CurrentFiler
  731. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  732. return cf.m.CurrentFolderFile(cf.r, file)
  733. }
  734. // ConnectedTo returns true if we are connected to the named device.
  735. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  736. m.pmut.RLock()
  737. _, ok := m.conn[deviceID]
  738. m.pmut.RUnlock()
  739. if ok {
  740. m.deviceWasSeen(deviceID)
  741. }
  742. return ok
  743. }
  744. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  745. var lines []string
  746. m.fmut.RLock()
  747. cfg, ok := m.folderCfgs[folder]
  748. m.fmut.RUnlock()
  749. if !ok {
  750. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  751. }
  752. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  753. if err != nil {
  754. if os.IsNotExist(err) {
  755. return lines, nil, nil
  756. }
  757. l.Warnln("Loading .stignore:", err)
  758. return lines, nil, err
  759. }
  760. defer fd.Close()
  761. scanner := bufio.NewScanner(fd)
  762. for scanner.Scan() {
  763. lines = append(lines, strings.TrimSpace(scanner.Text()))
  764. }
  765. m.fmut.RLock()
  766. patterns := m.folderIgnores[folder].Patterns()
  767. m.fmut.RUnlock()
  768. return lines, patterns, nil
  769. }
  770. func (m *Model) SetIgnores(folder string, content []string) error {
  771. cfg, ok := m.folderCfgs[folder]
  772. if !ok {
  773. return fmt.Errorf("Folder %s does not exist", folder)
  774. }
  775. path := filepath.Join(cfg.Path(), ".stignore")
  776. fd, err := osutil.CreateAtomic(path, 0644)
  777. if err != nil {
  778. l.Warnln("Saving .stignore:", err)
  779. return err
  780. }
  781. for _, line := range content {
  782. fmt.Fprintln(fd, line)
  783. }
  784. if err := fd.Close(); err != nil {
  785. l.Warnln("Saving .stignore:", err)
  786. return err
  787. }
  788. osutil.HideFile(path)
  789. return m.ScanFolder(folder)
  790. }
  791. // AddConnection adds a new peer connection to the model. An initial index will
  792. // be sent to the connected peer, thereafter index updates whenever the local
  793. // folder changes.
  794. func (m *Model) AddConnection(conn Connection) {
  795. deviceID := conn.ID()
  796. m.pmut.Lock()
  797. if _, ok := m.conn[deviceID]; ok {
  798. panic("add existing device")
  799. }
  800. m.conn[deviceID] = conn
  801. conn.Start()
  802. cm := m.clusterConfig(deviceID)
  803. conn.ClusterConfig(cm)
  804. m.fmut.RLock()
  805. for _, folder := range m.deviceFolders[deviceID] {
  806. fs := m.folderFiles[folder]
  807. go sendIndexes(conn, folder, fs, m.folderIgnores[folder])
  808. }
  809. m.fmut.RUnlock()
  810. m.pmut.Unlock()
  811. m.deviceWasSeen(deviceID)
  812. }
  813. func (m *Model) PauseDevice(device protocol.DeviceID) {
  814. m.pmut.Lock()
  815. m.devicePaused[device] = true
  816. _, ok := m.conn[device]
  817. m.pmut.Unlock()
  818. if ok {
  819. m.Close(device, errors.New("device paused"))
  820. }
  821. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  822. }
  823. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  824. m.pmut.Lock()
  825. m.devicePaused[device] = false
  826. m.pmut.Unlock()
  827. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  828. }
  829. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  830. m.pmut.Lock()
  831. paused := m.devicePaused[device]
  832. m.pmut.Unlock()
  833. return paused
  834. }
  835. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  836. m.fmut.Lock()
  837. defer m.fmut.Unlock()
  838. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  839. return sr
  840. }
  841. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  842. m.deviceStatRefs[deviceID] = sr
  843. return sr
  844. }
  845. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  846. m.deviceStatRef(deviceID).WasSeen()
  847. }
  848. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  849. m.fmut.Lock()
  850. defer m.fmut.Unlock()
  851. sr, ok := m.folderStatRefs[folder]
  852. if !ok {
  853. sr = stats.NewFolderStatisticsReference(m.db, folder)
  854. m.folderStatRefs[folder] = sr
  855. }
  856. return sr
  857. }
  858. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  859. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  860. }
  861. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) {
  862. deviceID := conn.ID()
  863. name := conn.Name()
  864. var err error
  865. l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder)
  866. defer l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  867. minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores)
  868. sub := events.Default.Subscribe(events.LocalIndexUpdated)
  869. defer events.Default.Unsubscribe(sub)
  870. for err == nil {
  871. // While we have sent a localVersion at least equal to the one
  872. // currently in the database, wait for the local index to update. The
  873. // local index may update for other folders than the one we are
  874. // sending for.
  875. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  876. sub.Poll(time.Minute)
  877. continue
  878. }
  879. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores)
  880. // Wait a short amount of time before entering the next loop. If there
  881. // are continous changes happening to the local index, this gives us
  882. // time to batch them up a little.
  883. time.Sleep(250 * time.Millisecond)
  884. }
  885. }
  886. func sendIndexTo(initial bool, minLocalVer int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) (int64, error) {
  887. deviceID := conn.ID()
  888. name := conn.Name()
  889. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  890. currentBatchSize := 0
  891. maxLocalVer := int64(0)
  892. var err error
  893. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  894. f := fi.(protocol.FileInfo)
  895. if f.LocalVersion <= minLocalVer {
  896. return true
  897. }
  898. if f.LocalVersion > maxLocalVer {
  899. maxLocalVer = f.LocalVersion
  900. }
  901. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  902. l.Debugln("not sending update for ignored/unsupported symlink", f)
  903. return true
  904. }
  905. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  906. if initial {
  907. if err = conn.Index(folder, batch, 0, nil); err != nil {
  908. return false
  909. }
  910. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  911. initial = false
  912. } else {
  913. if err = conn.IndexUpdate(folder, batch, 0, nil); err != nil {
  914. return false
  915. }
  916. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  917. }
  918. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  919. currentBatchSize = 0
  920. }
  921. batch = append(batch, f)
  922. currentBatchSize += indexPerFileSize + len(f.Blocks)*indexPerBlockSize
  923. return true
  924. })
  925. if initial && err == nil {
  926. err = conn.Index(folder, batch, 0, nil)
  927. if err == nil {
  928. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  929. }
  930. } else if len(batch) > 0 && err == nil {
  931. err = conn.IndexUpdate(folder, batch, 0, nil)
  932. if err == nil {
  933. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  934. }
  935. }
  936. return maxLocalVer, err
  937. }
  938. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  939. m.fmut.RLock()
  940. files := m.folderFiles[folder]
  941. m.fmut.RUnlock()
  942. files.Update(protocol.LocalDeviceID, fs)
  943. m.rvmut.Lock()
  944. for _, f := range fs {
  945. delete(m.reqValidationCache, folder+"/"+f.Name)
  946. }
  947. m.rvmut.Unlock()
  948. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  949. "folder": folder,
  950. "items": len(fs),
  951. "version": files.LocalVersion(protocol.LocalDeviceID),
  952. })
  953. }
  954. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, flags uint32, options []protocol.Option) ([]byte, error) {
  955. m.pmut.RLock()
  956. nc, ok := m.conn[deviceID]
  957. m.pmut.RUnlock()
  958. if !ok {
  959. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  960. }
  961. 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)
  962. return nc.Request(folder, name, offset, size, hash, flags, options)
  963. }
  964. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  965. if len(cfg.ID) == 0 {
  966. panic("cannot add empty folder id")
  967. }
  968. m.fmut.Lock()
  969. m.folderCfgs[cfg.ID] = cfg
  970. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  971. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  972. for i, device := range cfg.Devices {
  973. m.folderDevices[cfg.ID][i] = device.DeviceID
  974. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  975. }
  976. ignores := ignore.New(m.cacheIgnoredFiles)
  977. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  978. l.Warnln("Loading ignores:", err)
  979. }
  980. m.folderIgnores[cfg.ID] = ignores
  981. m.fmut.Unlock()
  982. }
  983. func (m *Model) ScanFolders() map[string]error {
  984. m.fmut.RLock()
  985. folders := make([]string, 0, len(m.folderCfgs))
  986. for folder := range m.folderCfgs {
  987. folders = append(folders, folder)
  988. }
  989. m.fmut.RUnlock()
  990. errors := make(map[string]error, len(m.folderCfgs))
  991. errorsMut := sync.NewMutex()
  992. wg := sync.NewWaitGroup()
  993. wg.Add(len(folders))
  994. for _, folder := range folders {
  995. folder := folder
  996. go func() {
  997. err := m.ScanFolder(folder)
  998. if err != nil {
  999. errorsMut.Lock()
  1000. errors[folder] = err
  1001. errorsMut.Unlock()
  1002. // Potentially sets the error twice, once in the scanner just
  1003. // by doing a check, and once here, if the error returned is
  1004. // the same one as returned by CheckFolderHealth, though
  1005. // duplicate set is handled by setError.
  1006. m.fmut.RLock()
  1007. srv := m.folderRunners[folder]
  1008. m.fmut.RUnlock()
  1009. srv.setError(err)
  1010. }
  1011. wg.Done()
  1012. }()
  1013. }
  1014. wg.Wait()
  1015. return errors
  1016. }
  1017. func (m *Model) ScanFolder(folder string) error {
  1018. return m.ScanFolderSubs(folder, nil)
  1019. }
  1020. func (m *Model) ScanFolderSubs(folder string, subs []string) error {
  1021. m.fmut.Lock()
  1022. runner, ok := m.folderRunners[folder]
  1023. m.fmut.Unlock()
  1024. // Folders are added to folderRunners only when they are started. We can't
  1025. // scan them before they have started, so that's what we need to check for
  1026. // here.
  1027. if !ok {
  1028. return errors.New("no such folder")
  1029. }
  1030. return runner.Scan(subs)
  1031. }
  1032. func (m *Model) internalScanFolderSubs(folder string, subs []string) error {
  1033. for i, sub := range subs {
  1034. sub = osutil.NativeFilename(sub)
  1035. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1036. return errors.New("invalid subpath")
  1037. }
  1038. subs[i] = sub
  1039. }
  1040. m.fmut.Lock()
  1041. fs := m.folderFiles[folder]
  1042. folderCfg := m.folderCfgs[folder]
  1043. ignores := m.folderIgnores[folder]
  1044. runner, ok := m.folderRunners[folder]
  1045. m.fmut.Unlock()
  1046. // Folders are added to folderRunners only when they are started. We can't
  1047. // scan them before they have started, so that's what we need to check for
  1048. // here.
  1049. if !ok {
  1050. return errors.New("no such folder")
  1051. }
  1052. if err := m.CheckFolderHealth(folder); err != nil {
  1053. runner.setError(err)
  1054. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1055. return err
  1056. }
  1057. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1058. err = fmt.Errorf("loading ignores: %v", err)
  1059. runner.setError(err)
  1060. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1061. return err
  1062. }
  1063. // Required to make sure that we start indexing at a directory we're already
  1064. // aware off.
  1065. var unifySubs []string
  1066. nextSub:
  1067. for _, sub := range subs {
  1068. for sub != "" {
  1069. parent := filepath.Dir(sub)
  1070. if parent == "." || parent == string(filepath.Separator) {
  1071. parent = ""
  1072. }
  1073. if _, ok = fs.Get(protocol.LocalDeviceID, parent); ok {
  1074. break
  1075. }
  1076. sub = parent
  1077. }
  1078. for _, us := range unifySubs {
  1079. if strings.HasPrefix(sub, us) {
  1080. continue nextSub
  1081. }
  1082. }
  1083. unifySubs = append(unifySubs, sub)
  1084. }
  1085. subs = unifySubs
  1086. w := &scanner.Walker{
  1087. Folder: folderCfg.ID,
  1088. Dir: folderCfg.Path(),
  1089. Subs: subs,
  1090. Matcher: ignores,
  1091. BlockSize: protocol.BlockSize,
  1092. TempNamer: defTempNamer,
  1093. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1094. CurrentFiler: cFiler{m, folder},
  1095. MtimeRepo: db.NewVirtualMtimeRepo(m.db, folderCfg.ID),
  1096. IgnorePerms: folderCfg.IgnorePerms,
  1097. AutoNormalize: folderCfg.AutoNormalize,
  1098. Hashers: m.numHashers(folder),
  1099. ShortID: m.shortID,
  1100. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1101. }
  1102. runner.setState(FolderScanning)
  1103. fchan, err := w.Walk()
  1104. if err != nil {
  1105. // The error we get here is likely an OS level error, which might not be
  1106. // as readable as our health check errors. Check if we can get a health
  1107. // check error first, and use that if it's available.
  1108. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1109. err = ferr
  1110. }
  1111. runner.setError(err)
  1112. return err
  1113. }
  1114. batchSizeFiles := 100
  1115. batchSizeBlocks := 2048 // about 256 MB
  1116. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1117. blocksHandled := 0
  1118. for f := range fchan {
  1119. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1120. if err := m.CheckFolderHealth(folder); err != nil {
  1121. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1122. return err
  1123. }
  1124. m.updateLocals(folder, batch)
  1125. batch = batch[:0]
  1126. blocksHandled = 0
  1127. }
  1128. batch = append(batch, f)
  1129. blocksHandled += len(f.Blocks)
  1130. }
  1131. if err := m.CheckFolderHealth(folder); err != nil {
  1132. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1133. return err
  1134. } else if len(batch) > 0 {
  1135. m.updateLocals(folder, batch)
  1136. }
  1137. batch = batch[:0]
  1138. // TODO: We should limit the Have scanning to start at sub
  1139. seenPrefix := false
  1140. var iterError error
  1141. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1142. f := fi.(db.FileInfoTruncated)
  1143. hasPrefix := len(subs) == 0
  1144. for _, sub := range subs {
  1145. if strings.HasPrefix(f.Name, sub) {
  1146. hasPrefix = true
  1147. break
  1148. }
  1149. }
  1150. // Return true so that we keep iterating, until we get to the part
  1151. // of the tree we are interested in. Then return false so we stop
  1152. // iterating when we've passed the end of the subtree.
  1153. if !hasPrefix {
  1154. return !seenPrefix
  1155. }
  1156. seenPrefix = true
  1157. if !f.IsDeleted() {
  1158. if f.IsInvalid() {
  1159. return true
  1160. }
  1161. if len(batch) == batchSizeFiles {
  1162. if err := m.CheckFolderHealth(folder); err != nil {
  1163. iterError = err
  1164. return false
  1165. }
  1166. m.updateLocals(folder, batch)
  1167. batch = batch[:0]
  1168. }
  1169. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  1170. // File has been ignored or an unsupported symlink. Set invalid bit.
  1171. l.Debugln("setting invalid bit on ignored", f)
  1172. nf := protocol.FileInfo{
  1173. Name: f.Name,
  1174. Flags: f.Flags | protocol.FlagInvalid,
  1175. Modified: f.Modified,
  1176. Version: f.Version, // The file is still the same, so don't bump version
  1177. }
  1178. batch = append(batch, nf)
  1179. } else if _, err := osutil.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1180. // File has been deleted.
  1181. // We don't specifically verify that the error is
  1182. // os.IsNotExist because there is a corner case when a
  1183. // directory is suddenly transformed into a file. When that
  1184. // happens, files that were in the directory (that is now a
  1185. // file) are deleted but will return a confusing error ("not a
  1186. // directory") when we try to Lstat() them.
  1187. nf := protocol.FileInfo{
  1188. Name: f.Name,
  1189. Flags: f.Flags | protocol.FlagDeleted,
  1190. Modified: f.Modified,
  1191. Version: f.Version.Update(m.shortID),
  1192. }
  1193. batch = append(batch, nf)
  1194. }
  1195. }
  1196. return true
  1197. })
  1198. if iterError != nil {
  1199. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1200. return iterError
  1201. }
  1202. if err := m.CheckFolderHealth(folder); err != nil {
  1203. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1204. return err
  1205. } else if len(batch) > 0 {
  1206. m.updateLocals(folder, batch)
  1207. }
  1208. runner.setState(FolderIdle)
  1209. return nil
  1210. }
  1211. func (m *Model) DelayScan(folder string, next time.Duration) {
  1212. m.fmut.Lock()
  1213. runner, ok := m.folderRunners[folder]
  1214. m.fmut.Unlock()
  1215. if !ok {
  1216. return
  1217. }
  1218. runner.DelayScan(next)
  1219. }
  1220. // numHashers returns the number of hasher routines to use for a given folder,
  1221. // taking into account configuration and available CPU cores.
  1222. func (m *Model) numHashers(folder string) int {
  1223. m.fmut.Lock()
  1224. folderCfg := m.folderCfgs[folder]
  1225. numFolders := len(m.folderCfgs)
  1226. m.fmut.Unlock()
  1227. if folderCfg.Hashers > 0 {
  1228. // Specific value set in the config, use that.
  1229. return folderCfg.Hashers
  1230. }
  1231. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1232. // Interactive operating systems; don't load the system too heavily by
  1233. // default.
  1234. return 1
  1235. }
  1236. // For other operating systems and architectures, lets try to get some
  1237. // work done... Divide the available CPU cores among the configured
  1238. // folders.
  1239. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1240. return perFolder
  1241. }
  1242. return 1
  1243. }
  1244. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer device
  1245. func (m *Model) clusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  1246. cm := protocol.ClusterConfigMessage{
  1247. ClientName: m.clientName,
  1248. ClientVersion: m.clientVersion,
  1249. Options: []protocol.Option{
  1250. {
  1251. Key: "name",
  1252. Value: m.deviceName,
  1253. },
  1254. },
  1255. }
  1256. m.fmut.RLock()
  1257. for _, folder := range m.deviceFolders[device] {
  1258. cr := protocol.Folder{
  1259. ID: folder,
  1260. }
  1261. for _, device := range m.folderDevices[folder] {
  1262. // DeviceID is a value type, but with an underlying array. Copy it
  1263. // so we don't grab aliases to the same array later on in device[:]
  1264. device := device
  1265. // TODO: Set read only bit when relevant
  1266. cn := protocol.Device{
  1267. ID: device[:],
  1268. Flags: protocol.FlagShareTrusted,
  1269. }
  1270. if deviceCfg := m.cfg.Devices()[device]; deviceCfg.Introducer {
  1271. cn.Flags |= protocol.FlagIntroducer
  1272. }
  1273. cr.Devices = append(cr.Devices, cn)
  1274. }
  1275. cm.Folders = append(cm.Folders, cr)
  1276. }
  1277. m.fmut.RUnlock()
  1278. return cm
  1279. }
  1280. func (m *Model) State(folder string) (string, time.Time, error) {
  1281. m.fmut.RLock()
  1282. runner, ok := m.folderRunners[folder]
  1283. m.fmut.RUnlock()
  1284. if !ok {
  1285. // The returned error should be an actual folder error, so returning
  1286. // errors.New("does not exist") or similar here would be
  1287. // inappropriate.
  1288. return "", time.Time{}, nil
  1289. }
  1290. state, changed, err := runner.getState()
  1291. return state.String(), changed, err
  1292. }
  1293. func (m *Model) Override(folder string) {
  1294. m.fmut.RLock()
  1295. fs, ok := m.folderFiles[folder]
  1296. runner := m.folderRunners[folder]
  1297. m.fmut.RUnlock()
  1298. if !ok {
  1299. return
  1300. }
  1301. runner.setState(FolderScanning)
  1302. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1303. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1304. need := fi.(protocol.FileInfo)
  1305. if len(batch) == indexBatchSize {
  1306. m.updateLocals(folder, batch)
  1307. batch = batch[:0]
  1308. }
  1309. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1310. if !ok || have.Name != need.Name {
  1311. // We are missing the file
  1312. need.Flags |= protocol.FlagDeleted
  1313. need.Blocks = nil
  1314. need.Version = need.Version.Update(m.shortID)
  1315. } else {
  1316. // We have the file, replace with our version
  1317. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1318. need = have
  1319. }
  1320. need.LocalVersion = 0
  1321. batch = append(batch, need)
  1322. return true
  1323. })
  1324. if len(batch) > 0 {
  1325. m.updateLocals(folder, batch)
  1326. }
  1327. runner.setState(FolderIdle)
  1328. }
  1329. // CurrentLocalVersion returns the change version for the given folder.
  1330. // This is guaranteed to increment if the contents of the local folder has
  1331. // changed.
  1332. func (m *Model) CurrentLocalVersion(folder string) (int64, bool) {
  1333. m.fmut.RLock()
  1334. fs, ok := m.folderFiles[folder]
  1335. m.fmut.RUnlock()
  1336. if !ok {
  1337. // The folder might not exist, since this can be called with a user
  1338. // specified folder name from the REST interface.
  1339. return 0, false
  1340. }
  1341. return fs.LocalVersion(protocol.LocalDeviceID), true
  1342. }
  1343. // RemoteLocalVersion returns the change version for the given folder, as
  1344. // sent by remote peers. This is guaranteed to increment if the contents of
  1345. // the remote or global folder has changed.
  1346. func (m *Model) RemoteLocalVersion(folder string) (int64, bool) {
  1347. m.fmut.RLock()
  1348. defer m.fmut.RUnlock()
  1349. fs, ok := m.folderFiles[folder]
  1350. if !ok {
  1351. // The folder might not exist, since this can be called with a user
  1352. // specified folder name from the REST interface.
  1353. return 0, false
  1354. }
  1355. var ver int64
  1356. for _, n := range m.folderDevices[folder] {
  1357. ver += fs.LocalVersion(n)
  1358. }
  1359. return ver, true
  1360. }
  1361. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1362. m.fmut.RLock()
  1363. files, ok := m.folderFiles[folder]
  1364. m.fmut.RUnlock()
  1365. if !ok {
  1366. return nil
  1367. }
  1368. output := make(map[string]interface{})
  1369. sep := string(filepath.Separator)
  1370. prefix = osutil.NativeFilename(prefix)
  1371. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1372. prefix = prefix + sep
  1373. }
  1374. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1375. f := fi.(db.FileInfoTruncated)
  1376. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1377. return true
  1378. }
  1379. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1380. var dir, base string
  1381. if f.IsDirectory() && !f.IsSymlink() {
  1382. dir = f.Name
  1383. } else {
  1384. dir = filepath.Dir(f.Name)
  1385. base = filepath.Base(f.Name)
  1386. }
  1387. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1388. return true
  1389. }
  1390. last := output
  1391. if dir != "." {
  1392. for _, path := range strings.Split(dir, sep) {
  1393. directory, ok := last[path]
  1394. if !ok {
  1395. newdir := make(map[string]interface{})
  1396. last[path] = newdir
  1397. last = newdir
  1398. } else {
  1399. last = directory.(map[string]interface{})
  1400. }
  1401. }
  1402. }
  1403. if !dirsonly && base != "" {
  1404. last[base] = []interface{}{
  1405. time.Unix(f.Modified, 0), f.Size(),
  1406. }
  1407. }
  1408. return true
  1409. })
  1410. return output
  1411. }
  1412. func (m *Model) Availability(folder, file string) []protocol.DeviceID {
  1413. // Acquire this lock first, as the value returned from foldersFiles can
  1414. // get heavily modified on Close()
  1415. m.pmut.RLock()
  1416. defer m.pmut.RUnlock()
  1417. m.fmut.RLock()
  1418. fs, ok := m.folderFiles[folder]
  1419. m.fmut.RUnlock()
  1420. if !ok {
  1421. return nil
  1422. }
  1423. availableDevices := []protocol.DeviceID{}
  1424. for _, device := range fs.Availability(file) {
  1425. _, ok := m.conn[device]
  1426. if ok {
  1427. availableDevices = append(availableDevices, device)
  1428. }
  1429. }
  1430. return availableDevices
  1431. }
  1432. // BringToFront bumps the given files priority in the job queue.
  1433. func (m *Model) BringToFront(folder, file string) {
  1434. m.pmut.RLock()
  1435. defer m.pmut.RUnlock()
  1436. runner, ok := m.folderRunners[folder]
  1437. if ok {
  1438. runner.BringToFront(file)
  1439. }
  1440. }
  1441. // CheckFolderHealth checks the folder for common errors and returns the
  1442. // current folder error, or nil if the folder is healthy.
  1443. func (m *Model) CheckFolderHealth(id string) error {
  1444. if minFree := m.cfg.Options().MinHomeDiskFreePct; minFree > 0 {
  1445. if free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath()); err == nil && free < minFree {
  1446. return errors.New("home disk has insufficient free space")
  1447. }
  1448. }
  1449. folder, ok := m.cfg.Folders()[id]
  1450. if !ok {
  1451. return errors.New("folder does not exist")
  1452. }
  1453. fi, err := os.Stat(folder.Path())
  1454. v, ok := m.CurrentLocalVersion(id)
  1455. indexHasFiles := ok && v > 0
  1456. if indexHasFiles {
  1457. // There are files in the folder according to the index, so it must
  1458. // have existed and had a correct marker at some point. Verify that
  1459. // this is still the case.
  1460. switch {
  1461. case err != nil || !fi.IsDir():
  1462. err = errors.New("folder path missing")
  1463. case !folder.HasMarker():
  1464. err = errors.New("folder marker missing")
  1465. case !folder.ReadOnly:
  1466. // Check for free space, if it isn't a master folder. We aren't
  1467. // going to change the contents of master folders, so we don't
  1468. // care about the amount of free space there.
  1469. if free, errDfp := osutil.DiskFreePercentage(folder.Path()); errDfp == nil && free < folder.MinDiskFreePct {
  1470. err = errors.New("insufficient free space")
  1471. }
  1472. }
  1473. } else {
  1474. // It's a blank folder, so this may the first time we're looking at
  1475. // it. Attempt to create and tag with our marker as appropriate.
  1476. if os.IsNotExist(err) {
  1477. err = osutil.MkdirAll(folder.Path(), 0700)
  1478. }
  1479. if err == nil && !folder.HasMarker() {
  1480. err = folder.CreateMarker()
  1481. }
  1482. }
  1483. m.fmut.RLock()
  1484. runner, runnerExists := m.folderRunners[folder.ID]
  1485. m.fmut.RUnlock()
  1486. var oldErr error
  1487. if runnerExists {
  1488. _, _, oldErr = runner.getState()
  1489. }
  1490. if err != nil {
  1491. if oldErr != nil && oldErr.Error() != err.Error() {
  1492. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1493. } else if oldErr == nil {
  1494. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1495. }
  1496. if runnerExists {
  1497. runner.setError(err)
  1498. }
  1499. } else if oldErr != nil {
  1500. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1501. if runnerExists {
  1502. runner.clearError()
  1503. }
  1504. }
  1505. return err
  1506. }
  1507. func (m *Model) ResetFolder(folder string) {
  1508. l.Infof("Cleaning data for folder %q", folder)
  1509. db.DropFolder(m.db, folder)
  1510. }
  1511. func (m *Model) String() string {
  1512. return fmt.Sprintf("model@%p", m)
  1513. }
  1514. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1515. return nil
  1516. }
  1517. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1518. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1519. // Go through the folder configs and figure out if we need to restart or not.
  1520. fromFolders := mapFolders(from.Folders)
  1521. toFolders := mapFolders(to.Folders)
  1522. for folderID, cfg := range toFolders {
  1523. if _, ok := fromFolders[folderID]; !ok {
  1524. // A folder was added.
  1525. l.Debugln(m, "adding folder", folderID)
  1526. m.AddFolder(cfg)
  1527. if cfg.ReadOnly {
  1528. m.StartFolderRO(folderID)
  1529. } else {
  1530. m.StartFolderRW(folderID)
  1531. }
  1532. // Drop connections to all devices that can now share the new
  1533. // folder.
  1534. m.pmut.Lock()
  1535. for _, dev := range cfg.DeviceIDs() {
  1536. if conn, ok := m.conn[dev]; ok {
  1537. closeRawConn(conn)
  1538. }
  1539. }
  1540. m.pmut.Unlock()
  1541. }
  1542. }
  1543. for folderID, fromCfg := range fromFolders {
  1544. toCfg, ok := toFolders[folderID]
  1545. if !ok {
  1546. // A folder was removed. Requires restart.
  1547. l.Debugln(m, "requires restart, removing folder", folderID)
  1548. return false
  1549. }
  1550. // This folder exists on both sides. Compare the device lists, as we
  1551. // can handle adding a device (but not currently removing one).
  1552. fromDevs := mapDevices(fromCfg.DeviceIDs())
  1553. toDevs := mapDevices(toCfg.DeviceIDs())
  1554. for dev := range fromDevs {
  1555. if _, ok := toDevs[dev]; !ok {
  1556. // A device was removed. Requires restart.
  1557. l.Debugln(m, "requires restart, removing device", dev, "from folder", folderID)
  1558. return false
  1559. }
  1560. }
  1561. for dev := range toDevs {
  1562. if _, ok := fromDevs[dev]; !ok {
  1563. // A device was added. Handle it!
  1564. m.fmut.Lock()
  1565. m.pmut.Lock()
  1566. m.folderCfgs[folderID] = toCfg
  1567. m.folderDevices[folderID] = append(m.folderDevices[folderID], dev)
  1568. m.deviceFolders[dev] = append(m.deviceFolders[dev], folderID)
  1569. // If we already have a connection to this device, we should
  1570. // disconnect it so that we start sharing the folder with it.
  1571. // We close the underlying connection and let the normal error
  1572. // handling kick in to clean up and reconnect.
  1573. if conn, ok := m.conn[dev]; ok {
  1574. closeRawConn(conn)
  1575. }
  1576. m.pmut.Unlock()
  1577. m.fmut.Unlock()
  1578. }
  1579. }
  1580. // Check if anything else differs, apart from the device list.
  1581. fromCfg.Devices = nil
  1582. toCfg.Devices = nil
  1583. if !reflect.DeepEqual(fromCfg, toCfg) {
  1584. l.Debugln(m, "requires restart, folder", folderID, "configuration differs")
  1585. return false
  1586. }
  1587. }
  1588. // Removing a device requres restart
  1589. toDevs := mapDeviceCfgs(from.Devices)
  1590. for _, dev := range from.Devices {
  1591. if _, ok := toDevs[dev.DeviceID]; !ok {
  1592. l.Debugln(m, "requires restart, device", dev.DeviceID, "was removed")
  1593. return false
  1594. }
  1595. }
  1596. // All of the generic options require restart
  1597. if !reflect.DeepEqual(from.Options, to.Options) {
  1598. l.Debugln(m, "requires restart, options differ")
  1599. return false
  1600. }
  1601. return true
  1602. }
  1603. // mapFolders returns a map of folder ID to folder configuration for the given
  1604. // slice of folder configurations.
  1605. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1606. m := make(map[string]config.FolderConfiguration, len(folders))
  1607. for _, cfg := range folders {
  1608. m[cfg.ID] = cfg
  1609. }
  1610. return m
  1611. }
  1612. // mapDevices returns a map of device ID to nothing for the given slice of
  1613. // device IDs.
  1614. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1615. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1616. for _, dev := range devices {
  1617. m[dev] = struct{}{}
  1618. }
  1619. return m
  1620. }
  1621. // mapDeviceCfgs returns a map of device ID to nothing for the given slice of
  1622. // device configurations.
  1623. func mapDeviceCfgs(devices []config.DeviceConfiguration) map[protocol.DeviceID]struct{} {
  1624. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1625. for _, dev := range devices {
  1626. m[dev.DeviceID] = struct{}{}
  1627. }
  1628. return m
  1629. }
  1630. func filterIndex(folder string, fs []protocol.FileInfo, dropDeletes bool) []protocol.FileInfo {
  1631. for i := 0; i < len(fs); {
  1632. if fs[i].Flags&^protocol.FlagsAll != 0 {
  1633. l.Debugln("dropping update for file with unknown bits set", fs[i])
  1634. fs[i] = fs[len(fs)-1]
  1635. fs = fs[:len(fs)-1]
  1636. } else if fs[i].IsDeleted() && dropDeletes {
  1637. l.Debugln("dropping update for undesired delete", fs[i])
  1638. fs[i] = fs[len(fs)-1]
  1639. fs = fs[:len(fs)-1]
  1640. } else if symlinkInvalid(folder, fs[i]) {
  1641. l.Debugln("dropping update for unsupported symlink", fs[i])
  1642. fs[i] = fs[len(fs)-1]
  1643. fs = fs[:len(fs)-1]
  1644. } else {
  1645. i++
  1646. }
  1647. }
  1648. return fs
  1649. }
  1650. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1651. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1652. symlinkWarning.Do(func() {
  1653. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1654. })
  1655. // Need to type switch for the concrete type to be able to access fields...
  1656. var name string
  1657. switch fi := fi.(type) {
  1658. case protocol.FileInfo:
  1659. name = fi.Name
  1660. case db.FileInfoTruncated:
  1661. name = fi.Name
  1662. }
  1663. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1664. return true
  1665. }
  1666. return false
  1667. }
  1668. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1669. // Returns the resulting slice, plus how much elements are left to skip or
  1670. // copy to satisfy the values which were provided, given the slice is not
  1671. // big enough.
  1672. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1673. l := len(data)
  1674. if l <= skip {
  1675. return []string{}, skip - l, get
  1676. } else if l < skip+get {
  1677. return data[skip:l], 0, get - (l - skip)
  1678. }
  1679. return data[skip : skip+get], 0, 0
  1680. }
  1681. func closeRawConn(conn io.Closer) error {
  1682. if conn, ok := conn.(*tls.Conn); ok {
  1683. // If the underlying connection is a *tls.Conn, Close() does more
  1684. // than it says on the tin. Specifically, it sends a TLS alert
  1685. // message, which might block forever if the connection is dead
  1686. // and we don't have a deadline set.
  1687. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1688. }
  1689. return conn.Close()
  1690. }