model.go 58 KB

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