model.go 55 KB

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