model.go 53 KB

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