model.go 55 KB

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