model.go 54 KB

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