model.go 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478
  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. "bytes"
  10. "crypto/tls"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "os"
  17. "path/filepath"
  18. "reflect"
  19. "runtime"
  20. "sort"
  21. "strings"
  22. stdsync "sync"
  23. "time"
  24. "github.com/syncthing/syncthing/lib/config"
  25. "github.com/syncthing/syncthing/lib/connections"
  26. "github.com/syncthing/syncthing/lib/db"
  27. "github.com/syncthing/syncthing/lib/events"
  28. "github.com/syncthing/syncthing/lib/fs"
  29. "github.com/syncthing/syncthing/lib/ignore"
  30. "github.com/syncthing/syncthing/lib/osutil"
  31. "github.com/syncthing/syncthing/lib/protocol"
  32. "github.com/syncthing/syncthing/lib/scanner"
  33. "github.com/syncthing/syncthing/lib/stats"
  34. "github.com/syncthing/syncthing/lib/symlinks"
  35. "github.com/syncthing/syncthing/lib/sync"
  36. "github.com/syncthing/syncthing/lib/versioner"
  37. "github.com/thejerf/suture"
  38. )
  39. // How many files to send in each Index/IndexUpdate message.
  40. const (
  41. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  42. indexBatchSize = 1000 // Either way, don't include more files than this
  43. )
  44. type service interface {
  45. BringToFront(string)
  46. DelayScan(d time.Duration)
  47. IndexUpdated() // Remote index was updated notification
  48. Jobs() ([]string, []string) // In progress, Queued
  49. Scan(subs []string) error
  50. Serve()
  51. Stop()
  52. getState() (folderState, time.Time, error)
  53. setState(state folderState)
  54. clearError()
  55. setError(err error)
  56. }
  57. type Availability struct {
  58. ID protocol.DeviceID `json:"id"`
  59. FromTemporary bool `json:"fromTemporary"`
  60. }
  61. type Model struct {
  62. *suture.Supervisor
  63. cfg *config.Wrapper
  64. db *db.Instance
  65. finder *db.BlockFinder
  66. progressEmitter *ProgressEmitter
  67. id protocol.DeviceID
  68. shortID protocol.ShortID
  69. cacheIgnoredFiles bool
  70. protectedFiles []string
  71. deviceName string
  72. clientName string
  73. clientVersion string
  74. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  75. folderFiles map[string]*db.FileSet // folder -> files
  76. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  77. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  78. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  79. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  80. folderRunners map[string]service // folder -> puller or scanner
  81. folderRunnerTokens map[string][]suture.ServiceToken // folder -> tokens for puller or scanner
  82. folderStatRefs map[string]*stats.FolderStatisticsReference // folder -> statsRef
  83. fmut sync.RWMutex // protects the above
  84. conn map[protocol.DeviceID]connections.Connection
  85. closed map[protocol.DeviceID]chan struct{}
  86. helloMessages map[protocol.DeviceID]protocol.HelloResult
  87. devicePaused map[protocol.DeviceID]bool
  88. deviceDownloads map[protocol.DeviceID]*deviceDownloadState
  89. pmut sync.RWMutex // protects the above
  90. }
  91. type folderFactory func(*Model, config.FolderConfiguration, versioner.Versioner, *fs.MtimeFS) service
  92. var (
  93. symlinkWarning = stdsync.Once{}
  94. folderFactories = make(map[config.FolderType]folderFactory, 0)
  95. )
  96. // errors returned by the CheckFolderHealth method
  97. var (
  98. errFolderPathEmpty = errors.New("folder path empty")
  99. errFolderPathMissing = errors.New("folder path missing")
  100. errFolderMarkerMissing = errors.New("folder marker missing")
  101. errHomeDiskNoSpace = errors.New("home disk has insufficient free space")
  102. errFolderNoSpace = errors.New("folder has insufficient free space")
  103. errUnsupportedSymlink = errors.New("symlink not supported")
  104. errInvalidFilename = errors.New("filename is invalid")
  105. errDeviceUnknown = errors.New("unknown device")
  106. errDevicePaused = errors.New("device is paused")
  107. errDeviceIgnored = errors.New("device is ignored")
  108. )
  109. // NewModel creates and starts a new model. The model starts in read-only mode,
  110. // where it sends index information to connected peers and responds to requests
  111. // for file data without altering the local folder in any way.
  112. func NewModel(cfg *config.Wrapper, id protocol.DeviceID, deviceName, clientName, clientVersion string, ldb *db.Instance, protectedFiles []string) *Model {
  113. m := &Model{
  114. Supervisor: suture.New("model", suture.Spec{
  115. Log: func(line string) {
  116. l.Debugln(line)
  117. },
  118. }),
  119. cfg: cfg,
  120. db: ldb,
  121. finder: db.NewBlockFinder(ldb),
  122. progressEmitter: NewProgressEmitter(cfg),
  123. id: id,
  124. shortID: id.Short(),
  125. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  126. protectedFiles: protectedFiles,
  127. deviceName: deviceName,
  128. clientName: clientName,
  129. clientVersion: clientVersion,
  130. folderCfgs: make(map[string]config.FolderConfiguration),
  131. folderFiles: make(map[string]*db.FileSet),
  132. folderDevices: make(map[string][]protocol.DeviceID),
  133. deviceFolders: make(map[protocol.DeviceID][]string),
  134. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  135. folderIgnores: make(map[string]*ignore.Matcher),
  136. folderRunners: make(map[string]service),
  137. folderRunnerTokens: make(map[string][]suture.ServiceToken),
  138. folderStatRefs: make(map[string]*stats.FolderStatisticsReference),
  139. conn: make(map[protocol.DeviceID]connections.Connection),
  140. closed: make(map[protocol.DeviceID]chan struct{}),
  141. helloMessages: make(map[protocol.DeviceID]protocol.HelloResult),
  142. devicePaused: make(map[protocol.DeviceID]bool),
  143. deviceDownloads: make(map[protocol.DeviceID]*deviceDownloadState),
  144. fmut: sync.NewRWMutex(),
  145. pmut: sync.NewRWMutex(),
  146. }
  147. if cfg.Options().ProgressUpdateIntervalS > -1 {
  148. go m.progressEmitter.Serve()
  149. }
  150. cfg.Subscribe(m)
  151. return m
  152. }
  153. // StartDeadlockDetector starts a deadlock detector on the models locks which
  154. // causes panics in case the locks cannot be acquired in the given timeout
  155. // period.
  156. func (m *Model) StartDeadlockDetector(timeout time.Duration) {
  157. l.Infof("Starting deadlock detector with %v timeout", timeout)
  158. deadlockDetect(m.fmut, timeout)
  159. deadlockDetect(m.pmut, timeout)
  160. }
  161. // StartFolder constructs the folder service and starts it.
  162. func (m *Model) StartFolder(folder string) {
  163. m.fmut.Lock()
  164. folderType := m.startFolderLocked(folder)
  165. m.fmut.Unlock()
  166. l.Infoln("Ready to synchronize", folder, fmt.Sprintf("(%s)", folderType))
  167. }
  168. func (m *Model) startFolderLocked(folder string) config.FolderType {
  169. cfg, ok := m.folderCfgs[folder]
  170. if !ok {
  171. panic("cannot start nonexistent folder " + folder)
  172. }
  173. _, ok = m.folderRunners[folder]
  174. if ok {
  175. panic("cannot start already running folder " + folder)
  176. }
  177. folderFactory, ok := folderFactories[cfg.Type]
  178. if !ok {
  179. panic(fmt.Sprintf("unknown folder type 0x%x", cfg.Type))
  180. }
  181. fs := m.folderFiles[folder]
  182. // Find any devices for which we hold the index in the db, but the folder
  183. // is not shared, and drop it.
  184. expected := mapDevices(cfg.DeviceIDs())
  185. for _, available := range fs.ListDevices() {
  186. if _, ok := expected[available]; !ok {
  187. l.Debugln("dropping", folder, "state for", available)
  188. fs.Replace(available, nil)
  189. }
  190. }
  191. v, ok := fs.Sequence(protocol.LocalDeviceID), true
  192. indexHasFiles := ok && v > 0
  193. if !indexHasFiles {
  194. // It's a blank folder, so this may the first time we're looking at
  195. // it. Attempt to create and tag with our marker as appropriate. We
  196. // don't really do anything with errors at this point except warn -
  197. // if these things don't work, we still want to start the folder and
  198. // it'll show up as errored later.
  199. if _, err := os.Stat(cfg.Path()); os.IsNotExist(err) {
  200. if err := osutil.MkdirAll(cfg.Path(), 0700); err != nil {
  201. l.Warnln("Creating folder:", err)
  202. }
  203. }
  204. if err := cfg.CreateMarker(); err != nil {
  205. l.Warnln("Creating folder marker:", err)
  206. }
  207. }
  208. var ver versioner.Versioner
  209. if len(cfg.Versioning.Type) > 0 {
  210. versionerFactory, ok := versioner.Factories[cfg.Versioning.Type]
  211. if !ok {
  212. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  213. }
  214. ver = versionerFactory(folder, cfg.Path(), cfg.Versioning.Params)
  215. if service, ok := ver.(suture.Service); ok {
  216. // The versioner implements the suture.Service interface, so
  217. // expects to be run in the background in addition to being called
  218. // when files are going to be archived.
  219. token := m.Add(service)
  220. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  221. }
  222. }
  223. p := folderFactory(m, cfg, ver, fs.MtimeFS())
  224. m.folderRunners[folder] = p
  225. m.warnAboutOverwritingProtectedFiles(folder)
  226. token := m.Add(p)
  227. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  228. return cfg.Type
  229. }
  230. func (m *Model) warnAboutOverwritingProtectedFiles(folder string) {
  231. if m.folderCfgs[folder].Type == config.FolderTypeReadOnly {
  232. return
  233. }
  234. folderLocation := m.folderCfgs[folder].Path()
  235. ignores := m.folderIgnores[folder]
  236. var filesAtRisk []string
  237. for _, protectedFilePath := range m.protectedFiles {
  238. // check if file is synced in this folder
  239. if !strings.HasPrefix(protectedFilePath, folderLocation) {
  240. continue
  241. }
  242. // check if file is ignored
  243. if ignores.Match(protectedFilePath).IsIgnored() {
  244. continue
  245. }
  246. filesAtRisk = append(filesAtRisk, protectedFilePath)
  247. }
  248. if len(filesAtRisk) > 0 {
  249. 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, ", "))
  250. }
  251. }
  252. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  253. if len(cfg.ID) == 0 {
  254. panic("cannot add empty folder id")
  255. }
  256. m.fmut.Lock()
  257. m.addFolderLocked(cfg)
  258. m.fmut.Unlock()
  259. }
  260. func (m *Model) addFolderLocked(cfg config.FolderConfiguration) {
  261. m.folderCfgs[cfg.ID] = cfg
  262. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  263. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  264. for i, device := range cfg.Devices {
  265. m.folderDevices[cfg.ID][i] = device.DeviceID
  266. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  267. }
  268. ignores := ignore.New(m.cacheIgnoredFiles)
  269. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  270. l.Warnln("Loading ignores:", err)
  271. }
  272. m.folderIgnores[cfg.ID] = ignores
  273. }
  274. func (m *Model) RemoveFolder(folder string) {
  275. m.fmut.Lock()
  276. m.pmut.Lock()
  277. m.tearDownFolderLocked(folder)
  278. // Remove it from the database
  279. db.DropFolder(m.db, folder)
  280. m.pmut.Unlock()
  281. m.fmut.Unlock()
  282. }
  283. func (m *Model) tearDownFolderLocked(folder string) {
  284. // Stop the services running for this folder
  285. for _, id := range m.folderRunnerTokens[folder] {
  286. m.Remove(id)
  287. }
  288. // Close connections to affected devices
  289. for _, dev := range m.folderDevices[folder] {
  290. if conn, ok := m.conn[dev]; ok {
  291. closeRawConn(conn)
  292. }
  293. }
  294. // Clean up our config maps
  295. delete(m.folderCfgs, folder)
  296. delete(m.folderFiles, folder)
  297. delete(m.folderDevices, folder)
  298. delete(m.folderIgnores, folder)
  299. delete(m.folderRunners, folder)
  300. delete(m.folderRunnerTokens, folder)
  301. delete(m.folderStatRefs, folder)
  302. for dev, folders := range m.deviceFolders {
  303. m.deviceFolders[dev] = stringSliceWithout(folders, folder)
  304. }
  305. }
  306. func (m *Model) RestartFolder(cfg config.FolderConfiguration) {
  307. if len(cfg.ID) == 0 {
  308. panic("cannot add empty folder id")
  309. }
  310. m.fmut.Lock()
  311. m.pmut.Lock()
  312. m.tearDownFolderLocked(cfg.ID)
  313. m.addFolderLocked(cfg)
  314. folderType := m.startFolderLocked(cfg.ID)
  315. m.pmut.Unlock()
  316. m.fmut.Unlock()
  317. l.Infoln("Restarted folder", cfg.ID, fmt.Sprintf("(%s)", folderType))
  318. }
  319. type ConnectionInfo struct {
  320. protocol.Statistics
  321. Connected bool
  322. Paused bool
  323. Address string
  324. ClientVersion string
  325. Type string
  326. }
  327. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  328. return json.Marshal(map[string]interface{}{
  329. "at": info.At,
  330. "inBytesTotal": info.InBytesTotal,
  331. "outBytesTotal": info.OutBytesTotal,
  332. "connected": info.Connected,
  333. "paused": info.Paused,
  334. "address": info.Address,
  335. "clientVersion": info.ClientVersion,
  336. "type": info.Type,
  337. })
  338. }
  339. // ConnectionStats returns a map with connection statistics for each device.
  340. func (m *Model) ConnectionStats() map[string]interface{} {
  341. m.fmut.RLock()
  342. m.pmut.RLock()
  343. res := make(map[string]interface{})
  344. devs := m.cfg.Devices()
  345. conns := make(map[string]ConnectionInfo, len(devs))
  346. for device := range devs {
  347. hello := m.helloMessages[device]
  348. versionString := hello.ClientVersion
  349. if hello.ClientName != "syncthing" {
  350. versionString = hello.ClientName + " " + hello.ClientVersion
  351. }
  352. ci := ConnectionInfo{
  353. ClientVersion: strings.TrimSpace(versionString),
  354. Paused: m.devicePaused[device],
  355. }
  356. if conn, ok := m.conn[device]; ok {
  357. ci.Type = conn.Type
  358. ci.Connected = ok
  359. ci.Statistics = conn.Statistics()
  360. if addr := conn.RemoteAddr(); addr != nil {
  361. ci.Address = addr.String()
  362. }
  363. }
  364. conns[device.String()] = ci
  365. }
  366. res["connections"] = conns
  367. m.pmut.RUnlock()
  368. m.fmut.RUnlock()
  369. in, out := protocol.TotalInOut()
  370. res["total"] = ConnectionInfo{
  371. Statistics: protocol.Statistics{
  372. At: time.Now(),
  373. InBytesTotal: in,
  374. OutBytesTotal: out,
  375. },
  376. }
  377. return res
  378. }
  379. // DeviceStatistics returns statistics about each device
  380. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  381. var res = make(map[string]stats.DeviceStatistics)
  382. for id := range m.cfg.Devices() {
  383. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  384. }
  385. return res
  386. }
  387. // FolderStatistics returns statistics about each folder
  388. func (m *Model) FolderStatistics() map[string]stats.FolderStatistics {
  389. var res = make(map[string]stats.FolderStatistics)
  390. for id := range m.cfg.Folders() {
  391. res[id] = m.folderStatRef(id).GetStatistics()
  392. }
  393. return res
  394. }
  395. type FolderCompletion struct {
  396. CompletionPct float64
  397. NeedBytes int64
  398. GlobalBytes int64
  399. NeedDeletes int64
  400. }
  401. // Completion returns the completion status, in percent, for the given device
  402. // and folder.
  403. func (m *Model) Completion(device protocol.DeviceID, folder string) FolderCompletion {
  404. m.fmut.RLock()
  405. rf, ok := m.folderFiles[folder]
  406. m.fmut.RUnlock()
  407. if !ok {
  408. return FolderCompletion{} // Folder doesn't exist, so we hardly have any of it
  409. }
  410. _, _, tot := rf.GlobalSize()
  411. if tot == 0 {
  412. // Folder is empty, so we have all of it
  413. return FolderCompletion{
  414. CompletionPct: 100,
  415. }
  416. }
  417. m.pmut.RLock()
  418. counts := m.deviceDownloads[device].GetBlockCounts(folder)
  419. m.pmut.RUnlock()
  420. var need, fileNeed, downloaded, deletes int64
  421. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  422. ft := f.(db.FileInfoTruncated)
  423. // If the file is deleted, we account it only in the deleted column.
  424. if ft.Deleted {
  425. deletes++
  426. return true
  427. }
  428. // This might might be more than it really is, because some blocks can be of a smaller size.
  429. downloaded = int64(counts[ft.Name] * protocol.BlockSize)
  430. fileNeed = ft.FileSize() - downloaded
  431. if fileNeed < 0 {
  432. fileNeed = 0
  433. }
  434. need += fileNeed
  435. return true
  436. })
  437. needRatio := float64(need) / float64(tot)
  438. completionPct := 100 * (1 - needRatio)
  439. // If the completion is 100% but there are deletes we need to handle,
  440. // drop it down a notch. Hack for consumers that look only at the
  441. // percentage (our own GUI does the same calculation as here on it's own
  442. // and needs the same fixup).
  443. if need == 0 && deletes > 0 {
  444. completionPct = 95 // chosen by fair dice roll
  445. }
  446. l.Debugf("%v Completion(%s, %q): %f (%d / %d = %f)", m, device, folder, completionPct, need, tot, needRatio)
  447. return FolderCompletion{
  448. CompletionPct: completionPct,
  449. NeedBytes: need,
  450. GlobalBytes: tot,
  451. NeedDeletes: deletes,
  452. }
  453. }
  454. func sizeOfFile(f db.FileIntf) (files, deleted int, bytes int64) {
  455. if !f.IsDeleted() {
  456. files++
  457. } else {
  458. deleted++
  459. }
  460. bytes += f.FileSize()
  461. return
  462. }
  463. // GlobalSize returns the number of files, deleted files and total bytes for all
  464. // files in the global model.
  465. func (m *Model) GlobalSize(folder string) (nfiles, deleted int, bytes int64) {
  466. m.fmut.RLock()
  467. defer m.fmut.RUnlock()
  468. if rf, ok := m.folderFiles[folder]; ok {
  469. nfiles, deleted, bytes = rf.GlobalSize()
  470. }
  471. return
  472. }
  473. // LocalSize returns the number of files, deleted files and total bytes for all
  474. // files in the local folder.
  475. func (m *Model) LocalSize(folder string) (nfiles, deleted int, bytes int64) {
  476. m.fmut.RLock()
  477. defer m.fmut.RUnlock()
  478. if rf, ok := m.folderFiles[folder]; ok {
  479. nfiles, deleted, bytes = rf.LocalSize()
  480. }
  481. return
  482. }
  483. // NeedSize returns the number and total size of currently needed files.
  484. func (m *Model) NeedSize(folder string) (nfiles, ndeletes int, bytes int64) {
  485. m.fmut.RLock()
  486. defer m.fmut.RUnlock()
  487. if rf, ok := m.folderFiles[folder]; ok {
  488. ignores := m.folderIgnores[folder]
  489. cfg := m.folderCfgs[folder]
  490. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  491. if shouldIgnore(f, ignores, cfg.IgnoreDelete) {
  492. return true
  493. }
  494. fs, de, by := sizeOfFile(f)
  495. nfiles += fs
  496. ndeletes += de
  497. bytes += by
  498. return true
  499. })
  500. }
  501. bytes -= m.progressEmitter.BytesCompleted(folder)
  502. l.Debugf("%v NeedSize(%q): %d %d", m, folder, nfiles, bytes)
  503. return
  504. }
  505. // NeedFolderFiles returns paginated list of currently needed files in
  506. // progress, queued, and to be queued on next puller iteration, as well as the
  507. // total number of files currently needed.
  508. func (m *Model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated, int) {
  509. m.fmut.RLock()
  510. defer m.fmut.RUnlock()
  511. total := 0
  512. rf, ok := m.folderFiles[folder]
  513. if !ok {
  514. return nil, nil, nil, 0
  515. }
  516. var progress, queued, rest []db.FileInfoTruncated
  517. var seen map[string]struct{}
  518. skip := (page - 1) * perpage
  519. get := perpage
  520. runner, ok := m.folderRunners[folder]
  521. if ok {
  522. allProgressNames, allQueuedNames := runner.Jobs()
  523. var progressNames, queuedNames []string
  524. progressNames, skip, get = getChunk(allProgressNames, skip, get)
  525. queuedNames, skip, get = getChunk(allQueuedNames, skip, get)
  526. progress = make([]db.FileInfoTruncated, len(progressNames))
  527. queued = make([]db.FileInfoTruncated, len(queuedNames))
  528. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  529. for i, name := range progressNames {
  530. if f, ok := rf.GetGlobalTruncated(name); ok {
  531. progress[i] = f
  532. seen[name] = struct{}{}
  533. }
  534. }
  535. for i, name := range queuedNames {
  536. if f, ok := rf.GetGlobalTruncated(name); ok {
  537. queued[i] = f
  538. seen[name] = struct{}{}
  539. }
  540. }
  541. }
  542. rest = make([]db.FileInfoTruncated, 0, perpage)
  543. ignores := m.folderIgnores[folder]
  544. cfg := m.folderCfgs[folder]
  545. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  546. if shouldIgnore(f, ignores, cfg.IgnoreDelete) {
  547. return true
  548. }
  549. total++
  550. if skip > 0 {
  551. skip--
  552. return true
  553. }
  554. if get > 0 {
  555. ft := f.(db.FileInfoTruncated)
  556. if _, ok := seen[ft.Name]; !ok {
  557. rest = append(rest, ft)
  558. get--
  559. }
  560. }
  561. return true
  562. })
  563. return progress, queued, rest, total
  564. }
  565. // Index is called when a new device is connected and we receive their full index.
  566. // Implements the protocol.Model interface.
  567. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  568. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  569. if !m.folderSharedWith(folder, deviceID) {
  570. 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)
  571. return
  572. }
  573. m.fmut.RLock()
  574. files, ok := m.folderFiles[folder]
  575. runner := m.folderRunners[folder]
  576. m.fmut.RUnlock()
  577. if runner != nil {
  578. // Runner may legitimately not be set if this is the "cleanup" Index
  579. // message at startup.
  580. defer runner.IndexUpdated()
  581. }
  582. if !ok {
  583. l.Fatalf("Index for nonexistent folder %q", folder)
  584. }
  585. m.pmut.RLock()
  586. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  587. m.pmut.RUnlock()
  588. files.Replace(deviceID, fs)
  589. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  590. "device": deviceID.String(),
  591. "folder": folder,
  592. "items": len(fs),
  593. "version": files.Sequence(deviceID),
  594. })
  595. }
  596. // IndexUpdate is called for incremental updates to connected devices' indexes.
  597. // Implements the protocol.Model interface.
  598. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  599. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  600. if !m.folderSharedWith(folder, deviceID) {
  601. 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)
  602. return
  603. }
  604. m.fmut.RLock()
  605. files := m.folderFiles[folder]
  606. runner, ok := m.folderRunners[folder]
  607. m.fmut.RUnlock()
  608. if !ok {
  609. l.Fatalf("IndexUpdate for nonexistent folder %q", folder)
  610. }
  611. m.pmut.RLock()
  612. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  613. m.pmut.RUnlock()
  614. files.Update(deviceID, fs)
  615. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  616. "device": deviceID.String(),
  617. "folder": folder,
  618. "items": len(fs),
  619. "version": files.Sequence(deviceID),
  620. })
  621. runner.IndexUpdated()
  622. }
  623. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  624. m.fmut.RLock()
  625. defer m.fmut.RUnlock()
  626. return m.folderSharedWithLocked(folder, deviceID)
  627. }
  628. func (m *Model) folderSharedWithLocked(folder string, deviceID protocol.DeviceID) bool {
  629. for _, nfolder := range m.deviceFolders[deviceID] {
  630. if nfolder == folder {
  631. return true
  632. }
  633. }
  634. return false
  635. }
  636. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfig) {
  637. // Check the peer device's announced folders against our own. Emits events
  638. // for folders that we don't expect (unknown or not shared).
  639. // Also, collect a list of folders we do share, and if he's interested in
  640. // temporary indexes, subscribe the connection.
  641. tempIndexFolders := make([]string, 0, len(cm.Folders))
  642. m.pmut.RLock()
  643. conn, ok := m.conn[deviceID]
  644. m.pmut.RUnlock()
  645. if !ok {
  646. panic("bug: ClusterConfig called on closed or nonexistent connection")
  647. }
  648. dbLocation := filepath.Dir(m.db.Location())
  649. m.fmut.Lock()
  650. for _, folder := range cm.Folders {
  651. if !m.folderSharedWithLocked(folder.ID, deviceID) {
  652. events.Default.Log(events.FolderRejected, map[string]string{
  653. "folder": folder.ID,
  654. "folderLabel": folder.Label,
  655. "device": deviceID.String(),
  656. })
  657. 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)
  658. continue
  659. }
  660. if !folder.DisableTempIndexes {
  661. tempIndexFolders = append(tempIndexFolders, folder.ID)
  662. }
  663. fs := m.folderFiles[folder.ID]
  664. myIndexID := fs.IndexID(protocol.LocalDeviceID)
  665. mySequence := fs.Sequence(protocol.LocalDeviceID)
  666. var startSequence int64
  667. for _, dev := range folder.Devices {
  668. if bytes.Equal(dev.ID, m.id[:]) {
  669. // This is the other side's description of what it knows
  670. // about us. Lets check to see if we can start sending index
  671. // updates directly or need to send the index from start...
  672. if dev.IndexID == myIndexID {
  673. // They say they've seen our index ID before, so we can
  674. // send a delta update only.
  675. if dev.MaxSequence > mySequence {
  676. // Safety check. They claim to have more or newer
  677. // index data than we have - either we have lost
  678. // index data, or reset the index without resetting
  679. // the IndexID, or something else weird has
  680. // happened. We send a full index to reset the
  681. // situation.
  682. l.Infof("Device %v folder %q is delta index compatible, but seems out of sync with reality", deviceID, folder.ID)
  683. startSequence = 0
  684. continue
  685. }
  686. l.Infof("Device %v folder %q is delta index compatible (mlv=%d)", deviceID, folder.ID, dev.MaxSequence)
  687. startSequence = dev.MaxSequence
  688. } else if dev.IndexID != 0 {
  689. // They say they've seen an index ID from us, but it's
  690. // not the right one. Either they are confused or we
  691. // must have reset our database since last talking to
  692. // them. We'll start with a full index transfer.
  693. l.Infof("Device %v folder %q has mismatching index ID for us (%v != %v)", deviceID, folder.ID, dev.IndexID, myIndexID)
  694. startSequence = 0
  695. }
  696. } else if bytes.Equal(dev.ID, deviceID[:]) && dev.IndexID != 0 {
  697. // This is the other side's description of themselves. We
  698. // check to see that it matches the IndexID we have on file,
  699. // otherwise we drop our old index data and expect to get a
  700. // completely new set.
  701. theirIndexID := fs.IndexID(deviceID)
  702. if dev.IndexID == 0 {
  703. // They're not announcing an index ID. This means they
  704. // do not support delta indexes and we should clear any
  705. // information we have from them before accepting their
  706. // index, which will presumably be a full index.
  707. fs.Replace(deviceID, nil)
  708. } else if dev.IndexID != theirIndexID {
  709. // The index ID we have on file is not what they're
  710. // announcing. They must have reset their database and
  711. // will probably send us a full index. We drop any
  712. // information we have and remember this new index ID
  713. // instead.
  714. l.Infof("Device %v folder %q has a new index ID (%v)", deviceID, folder.ID, dev.IndexID)
  715. fs.Replace(deviceID, nil)
  716. fs.SetIndexID(deviceID, dev.IndexID)
  717. } else {
  718. // They're sending a recognized index ID and will most
  719. // likely use delta indexes. We might already have files
  720. // that we need to pull so let the folder runner know
  721. // that it should recheck the index data.
  722. if runner := m.folderRunners[folder.ID]; runner != nil {
  723. defer runner.IndexUpdated()
  724. }
  725. }
  726. }
  727. }
  728. go sendIndexes(conn, folder.ID, fs, m.folderIgnores[folder.ID], startSequence, dbLocation)
  729. }
  730. m.fmut.Unlock()
  731. // This breaks if we send multiple CM messages during the same connection.
  732. if len(tempIndexFolders) > 0 {
  733. m.pmut.RLock()
  734. conn, ok := m.conn[deviceID]
  735. m.pmut.RUnlock()
  736. // In case we've got ClusterConfig, and the connection disappeared
  737. // from infront of our nose.
  738. if ok {
  739. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  740. }
  741. }
  742. var changed bool
  743. if m.cfg.Devices()[deviceID].Introducer {
  744. // This device is an introducer. Go through the announced lists of folders
  745. // and devices and add what we are missing.
  746. for _, folder := range cm.Folders {
  747. if _, ok := m.folderDevices[folder.ID]; !ok {
  748. continue
  749. }
  750. nextDevice:
  751. for _, device := range folder.Devices {
  752. var id protocol.DeviceID
  753. copy(id[:], device.ID)
  754. if _, ok := m.cfg.Devices()[id]; !ok {
  755. // The device is currently unknown. Add it to the config.
  756. addresses := []string{"dynamic"}
  757. for _, addr := range device.Addresses {
  758. if addr != "dynamic" {
  759. addresses = append(addresses, addr)
  760. }
  761. }
  762. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  763. newDeviceCfg := config.DeviceConfiguration{
  764. DeviceID: id,
  765. Name: device.Name,
  766. Compression: m.cfg.Devices()[deviceID].Compression,
  767. Addresses: addresses,
  768. CertName: device.CertName,
  769. }
  770. // The introducers' introducers are also our introducers.
  771. if device.Introducer {
  772. l.Infof("Device %v is now also an introducer", id)
  773. newDeviceCfg.Introducer = true
  774. }
  775. m.cfg.SetDevice(newDeviceCfg)
  776. changed = true
  777. }
  778. for _, er := range m.deviceFolders[id] {
  779. if er == folder.ID {
  780. // We already share the folder with this device, so
  781. // nothing to do.
  782. continue nextDevice
  783. }
  784. }
  785. // We don't yet share this folder with this device. Add the device
  786. // to sharing list of the folder.
  787. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  788. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  789. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  790. folderCfg := m.cfg.Folders()[folder.ID]
  791. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  792. DeviceID: id,
  793. })
  794. m.cfg.SetFolder(folderCfg)
  795. changed = true
  796. }
  797. }
  798. }
  799. if changed {
  800. m.cfg.Save()
  801. }
  802. }
  803. // Closed is called when a connection has been closed
  804. func (m *Model) Closed(conn protocol.Connection, err error) {
  805. device := conn.ID()
  806. m.pmut.Lock()
  807. conn, ok := m.conn[device]
  808. if ok {
  809. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  810. }
  811. delete(m.conn, device)
  812. delete(m.helloMessages, device)
  813. delete(m.deviceDownloads, device)
  814. closed := m.closed[device]
  815. delete(m.closed, device)
  816. m.pmut.Unlock()
  817. l.Infof("Connection to %s closed: %v", device, err)
  818. events.Default.Log(events.DeviceDisconnected, map[string]string{
  819. "id": device.String(),
  820. "error": err.Error(),
  821. })
  822. close(closed)
  823. }
  824. // close will close the underlying connection for a given device
  825. func (m *Model) close(device protocol.DeviceID) {
  826. m.pmut.Lock()
  827. conn, ok := m.conn[device]
  828. m.pmut.Unlock()
  829. if !ok {
  830. // There is no connection to close
  831. return
  832. }
  833. closeRawConn(conn)
  834. }
  835. // Request returns the specified data segment by reading it from local disk.
  836. // Implements the protocol.Model interface.
  837. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, fromTemporary bool, buf []byte) error {
  838. if offset < 0 {
  839. return protocol.ErrInvalid
  840. }
  841. if !m.folderSharedWith(folder, deviceID) {
  842. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  843. return protocol.ErrNoSuchFile
  844. }
  845. if deviceID != protocol.LocalDeviceID {
  846. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, len(buf), fromTemporary)
  847. }
  848. m.fmut.RLock()
  849. folderCfg := m.folderCfgs[folder]
  850. folderPath := folderCfg.Path()
  851. folderIgnores := m.folderIgnores[folder]
  852. m.fmut.RUnlock()
  853. // filepath.Join() returns a filepath.Clean()ed path, which (quoting the
  854. // docs for clarity here):
  855. //
  856. // Clean returns the shortest path name equivalent to path by purely lexical
  857. // processing. It applies the following rules iteratively until no further
  858. // processing can be done:
  859. //
  860. // 1. Replace multiple Separator elements with a single one.
  861. // 2. Eliminate each . path name element (the current directory).
  862. // 3. Eliminate each inner .. path name element (the parent directory)
  863. // along with the non-.. element that precedes it.
  864. // 4. Eliminate .. elements that begin a rooted path:
  865. // that is, replace "/.." by "/" at the beginning of a path,
  866. // assuming Separator is '/'.
  867. fn := filepath.Join(folderPath, name)
  868. if !strings.HasPrefix(fn, folderPath) {
  869. // Request tries to escape!
  870. l.Debugf("%v Invalid REQ(in) tries to escape: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  871. return protocol.ErrInvalid
  872. }
  873. if folderIgnores != nil {
  874. // "rn" becomes the relative name of the file within the folder. This is
  875. // different than the original "name" parameter in that it's been
  876. // cleaned from any possible funny business.
  877. if rn, err := filepath.Rel(folderPath, fn); err != nil {
  878. return err
  879. } else if folderIgnores.Match(rn).IsIgnored() {
  880. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  881. return protocol.ErrNoSuchFile
  882. }
  883. }
  884. if info, err := osutil.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  885. target, _, err := symlinks.Read(fn)
  886. if err != nil {
  887. l.Debugln("symlinks.Read:", err)
  888. if os.IsNotExist(err) {
  889. return protocol.ErrNoSuchFile
  890. }
  891. return protocol.ErrGeneric
  892. }
  893. if _, err := strings.NewReader(target).ReadAt(buf, offset); err != nil {
  894. l.Debugln("symlink.Reader.ReadAt", err)
  895. return protocol.ErrGeneric
  896. }
  897. return nil
  898. }
  899. // Only check temp files if the flag is set, and if we are set to advertise
  900. // the temp indexes.
  901. if fromTemporary && !folderCfg.DisableTempIndexes {
  902. tempFn := filepath.Join(folderPath, defTempNamer.TempName(name))
  903. if err := readOffsetIntoBuf(tempFn, offset, buf); err == nil {
  904. return nil
  905. }
  906. // Fall through to reading from a non-temp file, just incase the temp
  907. // file has finished downloading.
  908. }
  909. err := readOffsetIntoBuf(fn, offset, buf)
  910. if os.IsNotExist(err) {
  911. return protocol.ErrNoSuchFile
  912. } else if err != nil {
  913. return protocol.ErrGeneric
  914. }
  915. return nil
  916. }
  917. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  918. m.fmut.RLock()
  919. fs, ok := m.folderFiles[folder]
  920. m.fmut.RUnlock()
  921. if !ok {
  922. return protocol.FileInfo{}, false
  923. }
  924. f, ok := fs.Get(protocol.LocalDeviceID, file)
  925. return f, ok
  926. }
  927. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  928. m.fmut.RLock()
  929. fs, ok := m.folderFiles[folder]
  930. m.fmut.RUnlock()
  931. if !ok {
  932. return protocol.FileInfo{}, false
  933. }
  934. f, ok := fs.GetGlobal(file)
  935. return f, ok
  936. }
  937. type cFiler struct {
  938. m *Model
  939. r string
  940. }
  941. // Implements scanner.CurrentFiler
  942. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  943. return cf.m.CurrentFolderFile(cf.r, file)
  944. }
  945. // ConnectedTo returns true if we are connected to the named device.
  946. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  947. m.pmut.RLock()
  948. _, ok := m.conn[deviceID]
  949. m.pmut.RUnlock()
  950. if ok {
  951. m.deviceWasSeen(deviceID)
  952. }
  953. return ok
  954. }
  955. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  956. var lines []string
  957. m.fmut.RLock()
  958. cfg, ok := m.folderCfgs[folder]
  959. m.fmut.RUnlock()
  960. if !ok {
  961. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  962. }
  963. if !cfg.HasMarker() {
  964. return lines, nil, fmt.Errorf("Folder %s stopped", folder)
  965. }
  966. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  967. if err != nil {
  968. if os.IsNotExist(err) {
  969. return lines, nil, nil
  970. }
  971. l.Warnln("Loading .stignore:", err)
  972. return lines, nil, err
  973. }
  974. defer fd.Close()
  975. scanner := bufio.NewScanner(fd)
  976. for scanner.Scan() {
  977. lines = append(lines, strings.TrimSpace(scanner.Text()))
  978. }
  979. m.fmut.RLock()
  980. patterns := m.folderIgnores[folder].Patterns()
  981. m.fmut.RUnlock()
  982. return lines, patterns, nil
  983. }
  984. func (m *Model) SetIgnores(folder string, content []string) error {
  985. cfg, ok := m.folderCfgs[folder]
  986. if !ok {
  987. return fmt.Errorf("Folder %s does not exist", folder)
  988. }
  989. path := filepath.Join(cfg.Path(), ".stignore")
  990. fd, err := osutil.CreateAtomic(path, 0644)
  991. if err != nil {
  992. l.Warnln("Saving .stignore:", err)
  993. return err
  994. }
  995. for _, line := range content {
  996. fmt.Fprintln(fd, line)
  997. }
  998. if err := fd.Close(); err != nil {
  999. l.Warnln("Saving .stignore:", err)
  1000. return err
  1001. }
  1002. osutil.HideFile(path)
  1003. return m.ScanFolder(folder)
  1004. }
  1005. // OnHello is called when an device connects to us.
  1006. // This allows us to extract some information from the Hello message
  1007. // and add it to a list of known devices ahead of any checks.
  1008. func (m *Model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloResult) error {
  1009. if m.IsPaused(remoteID) {
  1010. return errDevicePaused
  1011. }
  1012. if m.cfg.IgnoredDevice(remoteID) {
  1013. return errDeviceIgnored
  1014. }
  1015. if _, ok := m.cfg.Device(remoteID); ok {
  1016. // The device exists
  1017. return nil
  1018. }
  1019. events.Default.Log(events.DeviceRejected, map[string]string{
  1020. "name": hello.DeviceName,
  1021. "device": remoteID.String(),
  1022. "address": addr.String(),
  1023. })
  1024. return errDeviceUnknown
  1025. }
  1026. // GetHello is called when we are about to connect to some remote device.
  1027. func (m *Model) GetHello(protocol.DeviceID) protocol.HelloIntf {
  1028. return &protocol.Hello{
  1029. DeviceName: m.deviceName,
  1030. ClientName: m.clientName,
  1031. ClientVersion: m.clientVersion,
  1032. }
  1033. }
  1034. // AddConnection adds a new peer connection to the model. An initial index will
  1035. // be sent to the connected peer, thereafter index updates whenever the local
  1036. // folder changes.
  1037. func (m *Model) AddConnection(conn connections.Connection, hello protocol.HelloResult) {
  1038. deviceID := conn.ID()
  1039. m.pmut.Lock()
  1040. if oldConn, ok := m.conn[deviceID]; ok {
  1041. l.Infoln("Replacing old connection", oldConn, "with", conn, "for", deviceID)
  1042. // There is an existing connection to this device that we are
  1043. // replacing. We must close the existing connection and wait for the
  1044. // close to complete before adding the new connection. We do the
  1045. // actual close without holding pmut as the connection will call
  1046. // back into Closed() for the cleanup.
  1047. closed := m.closed[deviceID]
  1048. m.pmut.Unlock()
  1049. closeRawConn(oldConn)
  1050. <-closed
  1051. m.pmut.Lock()
  1052. }
  1053. m.conn[deviceID] = conn
  1054. m.closed[deviceID] = make(chan struct{})
  1055. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  1056. m.helloMessages[deviceID] = hello
  1057. event := map[string]string{
  1058. "id": deviceID.String(),
  1059. "deviceName": hello.DeviceName,
  1060. "clientName": hello.ClientName,
  1061. "clientVersion": hello.ClientVersion,
  1062. "type": conn.Type,
  1063. }
  1064. addr := conn.RemoteAddr()
  1065. if addr != nil {
  1066. event["addr"] = addr.String()
  1067. }
  1068. events.Default.Log(events.DeviceConnected, event)
  1069. l.Infof(`Device %s client is "%s %s" named "%s"`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName)
  1070. conn.Start()
  1071. cm := m.generateClusterConfig(deviceID)
  1072. conn.ClusterConfig(cm)
  1073. m.pmut.Unlock()
  1074. device, ok := m.cfg.Devices()[deviceID]
  1075. if ok && (device.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) {
  1076. device.Name = hello.DeviceName
  1077. m.cfg.SetDevice(device)
  1078. m.cfg.Save()
  1079. }
  1080. m.deviceWasSeen(deviceID)
  1081. }
  1082. func (m *Model) PauseDevice(device protocol.DeviceID) {
  1083. m.pmut.Lock()
  1084. m.devicePaused[device] = true
  1085. conn, ok := m.conn[device]
  1086. m.pmut.Unlock()
  1087. if ok {
  1088. closeRawConn(conn)
  1089. }
  1090. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  1091. }
  1092. func (m *Model) DownloadProgress(device protocol.DeviceID, folder string, updates []protocol.FileDownloadProgressUpdate) {
  1093. if !m.folderSharedWith(folder, device) {
  1094. return
  1095. }
  1096. m.fmut.RLock()
  1097. cfg, ok := m.folderCfgs[folder]
  1098. m.fmut.RUnlock()
  1099. if !ok || cfg.Type == config.FolderTypeReadOnly || cfg.DisableTempIndexes {
  1100. return
  1101. }
  1102. m.pmut.RLock()
  1103. m.deviceDownloads[device].Update(folder, updates)
  1104. state := m.deviceDownloads[device].GetBlockCounts(folder)
  1105. m.pmut.RUnlock()
  1106. events.Default.Log(events.RemoteDownloadProgress, map[string]interface{}{
  1107. "device": device.String(),
  1108. "folder": folder,
  1109. "state": state,
  1110. })
  1111. }
  1112. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  1113. m.pmut.Lock()
  1114. m.devicePaused[device] = false
  1115. m.pmut.Unlock()
  1116. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  1117. }
  1118. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  1119. m.pmut.Lock()
  1120. paused := m.devicePaused[device]
  1121. m.pmut.Unlock()
  1122. return paused
  1123. }
  1124. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  1125. m.fmut.Lock()
  1126. defer m.fmut.Unlock()
  1127. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  1128. return sr
  1129. }
  1130. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  1131. m.deviceStatRefs[deviceID] = sr
  1132. return sr
  1133. }
  1134. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  1135. m.deviceStatRef(deviceID).WasSeen()
  1136. }
  1137. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  1138. m.fmut.Lock()
  1139. defer m.fmut.Unlock()
  1140. sr, ok := m.folderStatRefs[folder]
  1141. if !ok {
  1142. sr = stats.NewFolderStatisticsReference(m.db, folder)
  1143. m.folderStatRefs[folder] = sr
  1144. }
  1145. return sr
  1146. }
  1147. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  1148. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  1149. }
  1150. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, startSequence int64, dbLocation string) {
  1151. deviceID := conn.ID()
  1152. name := conn.Name()
  1153. var err error
  1154. l.Debugf("sendIndexes for %s-%s/%q starting (slv=%d)", deviceID, name, folder, startSequence)
  1155. defer l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  1156. minSequence, err := sendIndexTo(startSequence, conn, folder, fs, ignores, dbLocation)
  1157. // Subscribe to LocalIndexUpdated (we have new information to send) and
  1158. // DeviceDisconnected (it might be us who disconnected, so we should
  1159. // exit).
  1160. sub := events.Default.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  1161. defer events.Default.Unsubscribe(sub)
  1162. for err == nil {
  1163. if conn.Closed() {
  1164. // Our work is done.
  1165. return
  1166. }
  1167. // While we have sent a sequence at least equal to the one
  1168. // currently in the database, wait for the local index to update. The
  1169. // local index may update for other folders than the one we are
  1170. // sending for.
  1171. if fs.Sequence(protocol.LocalDeviceID) <= minSequence {
  1172. sub.Poll(time.Minute)
  1173. continue
  1174. }
  1175. minSequence, err = sendIndexTo(minSequence, conn, folder, fs, ignores, dbLocation)
  1176. // Wait a short amount of time before entering the next loop. If there
  1177. // are continuous changes happening to the local index, this gives us
  1178. // time to batch them up a little.
  1179. time.Sleep(250 * time.Millisecond)
  1180. }
  1181. }
  1182. func sendIndexTo(minSequence int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, dbLocation string) (int64, error) {
  1183. deviceID := conn.ID()
  1184. name := conn.Name()
  1185. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1186. currentBatchSize := 0
  1187. initial := minSequence == 0
  1188. maxSequence := minSequence
  1189. var err error
  1190. sorter := NewIndexSorter(dbLocation)
  1191. defer sorter.Close()
  1192. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1193. f := fi.(protocol.FileInfo)
  1194. if f.Sequence <= minSequence {
  1195. return true
  1196. }
  1197. if f.Sequence > maxSequence {
  1198. maxSequence = f.Sequence
  1199. }
  1200. sorter.Append(f)
  1201. return true
  1202. })
  1203. sorter.Sorted(func(f protocol.FileInfo) bool {
  1204. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  1205. if initial {
  1206. if err = conn.Index(folder, batch); err != nil {
  1207. return false
  1208. }
  1209. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  1210. initial = false
  1211. } else {
  1212. if err = conn.IndexUpdate(folder, batch); err != nil {
  1213. return false
  1214. }
  1215. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  1216. }
  1217. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  1218. currentBatchSize = 0
  1219. }
  1220. batch = append(batch, f)
  1221. currentBatchSize += f.ProtoSize()
  1222. return true
  1223. })
  1224. if initial && err == nil {
  1225. err = conn.Index(folder, batch)
  1226. if err == nil {
  1227. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  1228. }
  1229. } else if len(batch) > 0 && err == nil {
  1230. err = conn.IndexUpdate(folder, batch)
  1231. if err == nil {
  1232. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  1233. }
  1234. }
  1235. return maxSequence, err
  1236. }
  1237. func (m *Model) updateLocalsFromScanning(folder string, fs []protocol.FileInfo) {
  1238. m.updateLocals(folder, fs)
  1239. m.fmut.RLock()
  1240. folderCfg := m.folderCfgs[folder]
  1241. m.fmut.RUnlock()
  1242. // Fire the LocalChangeDetected event to notify listeners about local updates.
  1243. m.localChangeDetected(folderCfg, fs)
  1244. }
  1245. func (m *Model) updateLocalsFromPulling(folder string, fs []protocol.FileInfo) {
  1246. m.updateLocals(folder, fs)
  1247. }
  1248. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  1249. m.fmut.RLock()
  1250. files := m.folderFiles[folder]
  1251. m.fmut.RUnlock()
  1252. if files == nil {
  1253. // The folder doesn't exist.
  1254. return
  1255. }
  1256. files.Update(protocol.LocalDeviceID, fs)
  1257. filenames := make([]string, len(fs))
  1258. for i, file := range fs {
  1259. filenames[i] = file.Name
  1260. }
  1261. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1262. "folder": folder,
  1263. "items": len(fs),
  1264. "filenames": filenames,
  1265. "version": files.Sequence(protocol.LocalDeviceID),
  1266. })
  1267. }
  1268. func (m *Model) localChangeDetected(folderCfg config.FolderConfiguration, files []protocol.FileInfo) {
  1269. path := strings.Replace(folderCfg.Path(), `\\?\`, "", 1)
  1270. for _, file := range files {
  1271. objType := "file"
  1272. action := "modified"
  1273. // If our local vector is version 1 AND it is the only version
  1274. // vector so far seen for this file then it is a new file. Else if
  1275. // it is > 1 it's not new, and if it is 1 but another shortId
  1276. // version vector exists then it is new for us but created elsewhere
  1277. // so the file is still not new but modified by us. Only if it is
  1278. // truly new do we change this to 'added', else we leave it as
  1279. // 'modified'.
  1280. if len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1 {
  1281. action = "added"
  1282. }
  1283. if file.IsDirectory() {
  1284. objType = "dir"
  1285. }
  1286. if file.IsDeleted() {
  1287. action = "deleted"
  1288. }
  1289. // The full file path, adjusted to the local path separator character. Also
  1290. // for windows paths, strip unwanted chars from the front.
  1291. path := filepath.Join(path, filepath.FromSlash(file.Name))
  1292. events.Default.Log(events.LocalChangeDetected, map[string]string{
  1293. "folderID": folderCfg.ID,
  1294. "label": folderCfg.Label,
  1295. "action": action,
  1296. "type": objType,
  1297. "path": path,
  1298. })
  1299. }
  1300. }
  1301. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  1302. m.pmut.RLock()
  1303. nc, ok := m.conn[deviceID]
  1304. m.pmut.RUnlock()
  1305. if !ok {
  1306. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1307. }
  1308. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x ft=%t", m, deviceID, folder, name, offset, size, hash, fromTemporary)
  1309. return nc.Request(folder, name, offset, size, hash, fromTemporary)
  1310. }
  1311. func (m *Model) ScanFolders() map[string]error {
  1312. m.fmut.RLock()
  1313. folders := make([]string, 0, len(m.folderCfgs))
  1314. for folder := range m.folderCfgs {
  1315. folders = append(folders, folder)
  1316. }
  1317. m.fmut.RUnlock()
  1318. errors := make(map[string]error, len(m.folderCfgs))
  1319. errorsMut := sync.NewMutex()
  1320. wg := sync.NewWaitGroup()
  1321. wg.Add(len(folders))
  1322. for _, folder := range folders {
  1323. folder := folder
  1324. go func() {
  1325. err := m.ScanFolder(folder)
  1326. if err != nil {
  1327. errorsMut.Lock()
  1328. errors[folder] = err
  1329. errorsMut.Unlock()
  1330. // Potentially sets the error twice, once in the scanner just
  1331. // by doing a check, and once here, if the error returned is
  1332. // the same one as returned by CheckFolderHealth, though
  1333. // duplicate set is handled by setError.
  1334. m.fmut.RLock()
  1335. srv := m.folderRunners[folder]
  1336. m.fmut.RUnlock()
  1337. srv.setError(err)
  1338. }
  1339. wg.Done()
  1340. }()
  1341. }
  1342. wg.Wait()
  1343. return errors
  1344. }
  1345. func (m *Model) ScanFolder(folder string) error {
  1346. return m.ScanFolderSubdirs(folder, nil)
  1347. }
  1348. func (m *Model) ScanFolderSubdirs(folder string, subs []string) error {
  1349. m.fmut.Lock()
  1350. runner, ok := m.folderRunners[folder]
  1351. m.fmut.Unlock()
  1352. // Folders are added to folderRunners only when they are started. We can't
  1353. // scan them before they have started, so that's what we need to check for
  1354. // here.
  1355. if !ok {
  1356. return errors.New("no such folder")
  1357. }
  1358. return runner.Scan(subs)
  1359. }
  1360. func (m *Model) internalScanFolderSubdirs(folder string, subDirs []string) error {
  1361. for i, sub := range subDirs {
  1362. sub = osutil.NativeFilename(sub)
  1363. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1364. return errors.New("invalid subpath")
  1365. }
  1366. subDirs[i] = sub
  1367. }
  1368. m.fmut.Lock()
  1369. fs := m.folderFiles[folder]
  1370. folderCfg := m.folderCfgs[folder]
  1371. ignores := m.folderIgnores[folder]
  1372. runner, ok := m.folderRunners[folder]
  1373. m.fmut.Unlock()
  1374. mtimefs := fs.MtimeFS()
  1375. // Check if the ignore patterns changed as part of scanning this folder.
  1376. // If they did we should schedule a pull of the folder so that we
  1377. // request things we might have suddenly become unignored and so on.
  1378. oldHash := ignores.Hash()
  1379. defer func() {
  1380. if ignores.Hash() != oldHash {
  1381. l.Debugln("Folder", folder, "ignore patterns changed; triggering puller")
  1382. runner.IndexUpdated()
  1383. }
  1384. }()
  1385. // Folders are added to folderRunners only when they are started. We can't
  1386. // scan them before they have started, so that's what we need to check for
  1387. // here.
  1388. if !ok {
  1389. return errors.New("no such folder")
  1390. }
  1391. if err := m.CheckFolderHealth(folder); err != nil {
  1392. runner.setError(err)
  1393. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1394. return err
  1395. }
  1396. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1397. err = fmt.Errorf("loading ignores: %v", err)
  1398. runner.setError(err)
  1399. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1400. return err
  1401. }
  1402. // Clean the list of subitems to ensure that we start at a known
  1403. // directory, and don't scan subdirectories of things we've already
  1404. // scanned.
  1405. subDirs = unifySubs(subDirs, func(f string) bool {
  1406. _, ok := fs.Get(protocol.LocalDeviceID, f)
  1407. return ok
  1408. })
  1409. // The cancel channel is closed whenever we return (such as from an error),
  1410. // to signal the potentially still running walker to stop.
  1411. cancel := make(chan struct{})
  1412. defer close(cancel)
  1413. runner.setState(FolderScanning)
  1414. fchan, err := scanner.Walk(scanner.Config{
  1415. Folder: folderCfg.ID,
  1416. Dir: folderCfg.Path(),
  1417. Subs: subDirs,
  1418. Matcher: ignores,
  1419. BlockSize: protocol.BlockSize,
  1420. TempNamer: defTempNamer,
  1421. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1422. CurrentFiler: cFiler{m, folder},
  1423. Lstater: mtimefs,
  1424. IgnorePerms: folderCfg.IgnorePerms,
  1425. AutoNormalize: folderCfg.AutoNormalize,
  1426. Hashers: m.numHashers(folder),
  1427. ShortID: m.shortID,
  1428. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1429. Cancel: cancel,
  1430. })
  1431. if err != nil {
  1432. // The error we get here is likely an OS level error, which might not be
  1433. // as readable as our health check errors. Check if we can get a health
  1434. // check error first, and use that if it's available.
  1435. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1436. err = ferr
  1437. }
  1438. runner.setError(err)
  1439. return err
  1440. }
  1441. batchSizeFiles := 100
  1442. batchSizeBlocks := 2048 // about 256 MB
  1443. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1444. blocksHandled := 0
  1445. for f := range fchan {
  1446. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1447. if err := m.CheckFolderHealth(folder); err != nil {
  1448. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1449. return err
  1450. }
  1451. m.updateLocalsFromScanning(folder, batch)
  1452. batch = batch[:0]
  1453. blocksHandled = 0
  1454. }
  1455. batch = append(batch, f)
  1456. blocksHandled += len(f.Blocks)
  1457. }
  1458. if err := m.CheckFolderHealth(folder); err != nil {
  1459. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1460. return err
  1461. } else if len(batch) > 0 {
  1462. m.updateLocalsFromScanning(folder, batch)
  1463. }
  1464. if len(subDirs) == 0 {
  1465. // If we have no specific subdirectories to traverse, set it to one
  1466. // empty prefix so we traverse the entire folder contents once.
  1467. subDirs = []string{""}
  1468. }
  1469. // Do a scan of the database for each prefix, to check for deleted and
  1470. // ignored files.
  1471. batch = batch[:0]
  1472. for _, sub := range subDirs {
  1473. var iterError error
  1474. fs.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  1475. f := fi.(db.FileInfoTruncated)
  1476. if len(batch) == batchSizeFiles {
  1477. if err := m.CheckFolderHealth(folder); err != nil {
  1478. iterError = err
  1479. return false
  1480. }
  1481. m.updateLocalsFromScanning(folder, batch)
  1482. batch = batch[:0]
  1483. }
  1484. switch {
  1485. case !f.IsInvalid() && (ignores.Match(f.Name).IsIgnored() || symlinkInvalid(folder, f)):
  1486. // File was valid at last pass but has been ignored or is an
  1487. // unsupported symlink. Set invalid bit.
  1488. l.Debugln("setting invalid bit on ignored", f)
  1489. nf := protocol.FileInfo{
  1490. Name: f.Name,
  1491. Type: f.Type,
  1492. Size: f.Size,
  1493. ModifiedS: f.ModifiedS,
  1494. ModifiedNs: f.ModifiedNs,
  1495. Permissions: f.Permissions,
  1496. NoPermissions: f.NoPermissions,
  1497. Invalid: true,
  1498. Version: f.Version, // The file is still the same, so don't bump version
  1499. }
  1500. batch = append(batch, nf)
  1501. case !f.IsInvalid() && !f.IsDeleted():
  1502. // The file is valid and not deleted. Lets check if it's
  1503. // still here.
  1504. if _, err := mtimefs.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1505. // We don't specifically verify that the error is
  1506. // os.IsNotExist because there is a corner case when a
  1507. // directory is suddenly transformed into a file. When that
  1508. // happens, files that were in the directory (that is now a
  1509. // file) are deleted but will return a confusing error ("not a
  1510. // directory") when we try to Lstat() them.
  1511. nf := protocol.FileInfo{
  1512. Name: f.Name,
  1513. Type: f.Type,
  1514. Size: 0,
  1515. ModifiedS: f.ModifiedS,
  1516. ModifiedNs: f.ModifiedNs,
  1517. Deleted: true,
  1518. Version: f.Version.Update(m.shortID),
  1519. }
  1520. batch = append(batch, nf)
  1521. }
  1522. }
  1523. return true
  1524. })
  1525. if iterError != nil {
  1526. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1527. return iterError
  1528. }
  1529. }
  1530. if err := m.CheckFolderHealth(folder); err != nil {
  1531. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1532. return err
  1533. } else if len(batch) > 0 {
  1534. m.updateLocalsFromScanning(folder, batch)
  1535. }
  1536. m.folderStatRef(folder).ScanCompleted()
  1537. runner.setState(FolderIdle)
  1538. return nil
  1539. }
  1540. func (m *Model) DelayScan(folder string, next time.Duration) {
  1541. m.fmut.Lock()
  1542. runner, ok := m.folderRunners[folder]
  1543. m.fmut.Unlock()
  1544. if !ok {
  1545. return
  1546. }
  1547. runner.DelayScan(next)
  1548. }
  1549. // numHashers returns the number of hasher routines to use for a given folder,
  1550. // taking into account configuration and available CPU cores.
  1551. func (m *Model) numHashers(folder string) int {
  1552. m.fmut.Lock()
  1553. folderCfg := m.folderCfgs[folder]
  1554. numFolders := len(m.folderCfgs)
  1555. m.fmut.Unlock()
  1556. if folderCfg.Hashers > 0 {
  1557. // Specific value set in the config, use that.
  1558. return folderCfg.Hashers
  1559. }
  1560. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1561. // Interactive operating systems; don't load the system too heavily by
  1562. // default.
  1563. return 1
  1564. }
  1565. // For other operating systems and architectures, lets try to get some
  1566. // work done... Divide the available CPU cores among the configured
  1567. // folders.
  1568. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1569. return perFolder
  1570. }
  1571. return 1
  1572. }
  1573. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1574. // the given peer device
  1575. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1576. var message protocol.ClusterConfig
  1577. m.fmut.RLock()
  1578. for _, folder := range m.deviceFolders[device] {
  1579. folderCfg := m.cfg.Folders()[folder]
  1580. fs := m.folderFiles[folder]
  1581. protocolFolder := protocol.Folder{
  1582. ID: folder,
  1583. Label: folderCfg.Label,
  1584. ReadOnly: folderCfg.Type == config.FolderTypeReadOnly,
  1585. IgnorePermissions: folderCfg.IgnorePerms,
  1586. IgnoreDelete: folderCfg.IgnoreDelete,
  1587. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1588. }
  1589. for _, device := range m.folderDevices[folder] {
  1590. // DeviceID is a value type, but with an underlying array. Copy it
  1591. // so we don't grab aliases to the same array later on in device[:]
  1592. device := device
  1593. // TODO: Set read only bit when relevant, and when we have per device
  1594. // access controls.
  1595. deviceCfg := m.cfg.Devices()[device]
  1596. var indexID protocol.IndexID
  1597. var maxSequence int64
  1598. if device == m.id {
  1599. indexID = fs.IndexID(protocol.LocalDeviceID)
  1600. maxSequence = fs.Sequence(protocol.LocalDeviceID)
  1601. } else {
  1602. indexID = fs.IndexID(device)
  1603. maxSequence = fs.Sequence(device)
  1604. }
  1605. protocolDevice := protocol.Device{
  1606. ID: device[:],
  1607. Name: deviceCfg.Name,
  1608. Addresses: deviceCfg.Addresses,
  1609. Compression: deviceCfg.Compression,
  1610. CertName: deviceCfg.CertName,
  1611. Introducer: deviceCfg.Introducer,
  1612. IndexID: indexID,
  1613. MaxSequence: maxSequence,
  1614. }
  1615. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1616. }
  1617. message.Folders = append(message.Folders, protocolFolder)
  1618. }
  1619. m.fmut.RUnlock()
  1620. return message
  1621. }
  1622. func (m *Model) State(folder string) (string, time.Time, error) {
  1623. m.fmut.RLock()
  1624. runner, ok := m.folderRunners[folder]
  1625. m.fmut.RUnlock()
  1626. if !ok {
  1627. // The returned error should be an actual folder error, so returning
  1628. // errors.New("does not exist") or similar here would be
  1629. // inappropriate.
  1630. return "", time.Time{}, nil
  1631. }
  1632. state, changed, err := runner.getState()
  1633. return state.String(), changed, err
  1634. }
  1635. func (m *Model) Override(folder string) {
  1636. m.fmut.RLock()
  1637. fs, ok := m.folderFiles[folder]
  1638. runner := m.folderRunners[folder]
  1639. m.fmut.RUnlock()
  1640. if !ok {
  1641. return
  1642. }
  1643. runner.setState(FolderScanning)
  1644. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1645. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1646. need := fi.(protocol.FileInfo)
  1647. if len(batch) == indexBatchSize {
  1648. m.updateLocalsFromScanning(folder, batch)
  1649. batch = batch[:0]
  1650. }
  1651. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1652. if !ok || have.Name != need.Name {
  1653. // We are missing the file
  1654. need.Deleted = true
  1655. need.Blocks = nil
  1656. need.Version = need.Version.Update(m.shortID)
  1657. need.Size = 0
  1658. } else {
  1659. // We have the file, replace with our version
  1660. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1661. need = have
  1662. }
  1663. need.Sequence = 0
  1664. batch = append(batch, need)
  1665. return true
  1666. })
  1667. if len(batch) > 0 {
  1668. m.updateLocalsFromScanning(folder, batch)
  1669. }
  1670. runner.setState(FolderIdle)
  1671. }
  1672. // CurrentSequence returns the change version for the given folder.
  1673. // This is guaranteed to increment if the contents of the local folder has
  1674. // changed.
  1675. func (m *Model) CurrentSequence(folder string) (int64, bool) {
  1676. m.fmut.RLock()
  1677. fs, ok := m.folderFiles[folder]
  1678. m.fmut.RUnlock()
  1679. if !ok {
  1680. // The folder might not exist, since this can be called with a user
  1681. // specified folder name from the REST interface.
  1682. return 0, false
  1683. }
  1684. return fs.Sequence(protocol.LocalDeviceID), true
  1685. }
  1686. // RemoteSequence returns the change version for the given folder, as
  1687. // sent by remote peers. This is guaranteed to increment if the contents of
  1688. // the remote or global folder has changed.
  1689. func (m *Model) RemoteSequence(folder string) (int64, bool) {
  1690. m.fmut.RLock()
  1691. defer m.fmut.RUnlock()
  1692. fs, ok := m.folderFiles[folder]
  1693. if !ok {
  1694. // The folder might not exist, since this can be called with a user
  1695. // specified folder name from the REST interface.
  1696. return 0, false
  1697. }
  1698. var ver int64
  1699. for _, n := range m.folderDevices[folder] {
  1700. ver += fs.Sequence(n)
  1701. }
  1702. return ver, true
  1703. }
  1704. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1705. m.fmut.RLock()
  1706. files, ok := m.folderFiles[folder]
  1707. m.fmut.RUnlock()
  1708. if !ok {
  1709. return nil
  1710. }
  1711. output := make(map[string]interface{})
  1712. sep := string(filepath.Separator)
  1713. prefix = osutil.NativeFilename(prefix)
  1714. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1715. prefix = prefix + sep
  1716. }
  1717. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1718. f := fi.(db.FileInfoTruncated)
  1719. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1720. return true
  1721. }
  1722. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1723. var dir, base string
  1724. if f.IsDirectory() && !f.IsSymlink() {
  1725. dir = f.Name
  1726. } else {
  1727. dir = filepath.Dir(f.Name)
  1728. base = filepath.Base(f.Name)
  1729. }
  1730. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1731. return true
  1732. }
  1733. last := output
  1734. if dir != "." {
  1735. for _, path := range strings.Split(dir, sep) {
  1736. directory, ok := last[path]
  1737. if !ok {
  1738. newdir := make(map[string]interface{})
  1739. last[path] = newdir
  1740. last = newdir
  1741. } else {
  1742. last = directory.(map[string]interface{})
  1743. }
  1744. }
  1745. }
  1746. if !dirsonly && base != "" {
  1747. last[base] = []interface{}{
  1748. f.ModTime(), f.FileSize(),
  1749. }
  1750. }
  1751. return true
  1752. })
  1753. return output
  1754. }
  1755. func (m *Model) Availability(folder, file string, version protocol.Vector, block protocol.BlockInfo) []Availability {
  1756. // Acquire this lock first, as the value returned from foldersFiles can
  1757. // get heavily modified on Close()
  1758. m.pmut.RLock()
  1759. defer m.pmut.RUnlock()
  1760. m.fmut.RLock()
  1761. fs, ok := m.folderFiles[folder]
  1762. devices := m.folderDevices[folder]
  1763. m.fmut.RUnlock()
  1764. if !ok {
  1765. return nil
  1766. }
  1767. var availabilities []Availability
  1768. for _, device := range fs.Availability(file) {
  1769. _, ok := m.conn[device]
  1770. if ok {
  1771. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  1772. }
  1773. }
  1774. for _, device := range devices {
  1775. if m.deviceDownloads[device].Has(folder, file, version, int32(block.Offset/protocol.BlockSize)) {
  1776. availabilities = append(availabilities, Availability{ID: device, FromTemporary: true})
  1777. }
  1778. }
  1779. return availabilities
  1780. }
  1781. // BringToFront bumps the given files priority in the job queue.
  1782. func (m *Model) BringToFront(folder, file string) {
  1783. m.pmut.RLock()
  1784. defer m.pmut.RUnlock()
  1785. runner, ok := m.folderRunners[folder]
  1786. if ok {
  1787. runner.BringToFront(file)
  1788. }
  1789. }
  1790. // CheckFolderHealth checks the folder for common errors and returns the
  1791. // current folder error, or nil if the folder is healthy.
  1792. func (m *Model) CheckFolderHealth(id string) error {
  1793. folder, ok := m.cfg.Folders()[id]
  1794. if !ok {
  1795. return errors.New("folder does not exist")
  1796. }
  1797. // Check for folder errors, with the most serious and specific first and
  1798. // generic ones like out of space on the home disk later. Note the
  1799. // inverted error flow (err==nil checks) here.
  1800. err := m.checkFolderPath(folder)
  1801. if err == nil {
  1802. err = m.checkFolderFreeSpace(folder)
  1803. }
  1804. if err == nil {
  1805. err = m.checkHomeDiskFree()
  1806. }
  1807. // Set or clear the error on the runner, which also does logging and
  1808. // generates events and stuff.
  1809. m.runnerExchangeError(folder, err)
  1810. return err
  1811. }
  1812. // checkFolderPath returns nil if the folder path exists and has the marker file.
  1813. func (m *Model) checkFolderPath(folder config.FolderConfiguration) error {
  1814. if folder.Path() == "" {
  1815. return errFolderPathEmpty
  1816. }
  1817. if fi, err := os.Stat(folder.Path()); err != nil || !fi.IsDir() {
  1818. return errFolderPathMissing
  1819. }
  1820. if !folder.HasMarker() {
  1821. return errFolderMarkerMissing
  1822. }
  1823. return nil
  1824. }
  1825. // checkFolderFreeSpace returns nil if the folder has the required amount of
  1826. // free space, or if folder free space checking is disabled.
  1827. func (m *Model) checkFolderFreeSpace(folder config.FolderConfiguration) error {
  1828. if folder.MinDiskFreePct <= 0 {
  1829. return nil
  1830. }
  1831. free, err := osutil.DiskFreePercentage(folder.Path())
  1832. if err == nil && free < folder.MinDiskFreePct {
  1833. return errFolderNoSpace
  1834. }
  1835. return nil
  1836. }
  1837. // checkHomeDiskFree returns nil if the home disk has the required amount of
  1838. // free space, or if home disk free space checking is disabled.
  1839. func (m *Model) checkHomeDiskFree() error {
  1840. minFree := m.cfg.Options().MinHomeDiskFreePct
  1841. if minFree <= 0 {
  1842. return nil
  1843. }
  1844. free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath())
  1845. if err == nil && free < minFree {
  1846. return errHomeDiskNoSpace
  1847. }
  1848. return nil
  1849. }
  1850. // runnerExchangeError sets the given error (which way be nil) on the folder
  1851. // runner. If the error differs from any previous error, logging and events
  1852. // happen.
  1853. func (m *Model) runnerExchangeError(folder config.FolderConfiguration, err error) {
  1854. m.fmut.RLock()
  1855. runner, runnerExists := m.folderRunners[folder.ID]
  1856. m.fmut.RUnlock()
  1857. var oldErr error
  1858. if runnerExists {
  1859. _, _, oldErr = runner.getState()
  1860. }
  1861. if err != nil {
  1862. if oldErr != nil && oldErr.Error() != err.Error() {
  1863. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1864. } else if oldErr == nil {
  1865. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1866. }
  1867. if runnerExists {
  1868. runner.setError(err)
  1869. }
  1870. } else if oldErr != nil {
  1871. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1872. if runnerExists {
  1873. runner.clearError()
  1874. }
  1875. }
  1876. }
  1877. func (m *Model) ResetFolder(folder string) {
  1878. l.Infof("Cleaning data for folder %q", folder)
  1879. db.DropFolder(m.db, folder)
  1880. }
  1881. func (m *Model) String() string {
  1882. return fmt.Sprintf("model@%p", m)
  1883. }
  1884. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1885. return nil
  1886. }
  1887. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1888. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1889. // Go through the folder configs and figure out if we need to restart or not.
  1890. fromFolders := mapFolders(from.Folders)
  1891. toFolders := mapFolders(to.Folders)
  1892. for folderID, cfg := range toFolders {
  1893. if _, ok := fromFolders[folderID]; !ok {
  1894. // A folder was added.
  1895. l.Debugln(m, "adding folder", folderID)
  1896. m.AddFolder(cfg)
  1897. m.StartFolder(folderID)
  1898. // Drop connections to all devices that can now share the new
  1899. // folder.
  1900. m.pmut.Lock()
  1901. for _, dev := range cfg.DeviceIDs() {
  1902. if conn, ok := m.conn[dev]; ok {
  1903. closeRawConn(conn)
  1904. }
  1905. }
  1906. m.pmut.Unlock()
  1907. }
  1908. }
  1909. for folderID, fromCfg := range fromFolders {
  1910. toCfg, ok := toFolders[folderID]
  1911. if !ok {
  1912. // The folder was removed.
  1913. m.RemoveFolder(folderID)
  1914. continue
  1915. }
  1916. // This folder exists on both sides. Settings might have changed.
  1917. // Check if anything differs, apart from the label.
  1918. toCfgCopy := toCfg
  1919. fromCfgCopy := fromCfg
  1920. fromCfgCopy.Label = ""
  1921. toCfgCopy.Label = ""
  1922. if !reflect.DeepEqual(fromCfgCopy, toCfgCopy) {
  1923. m.RestartFolder(toCfg)
  1924. }
  1925. }
  1926. // Removing a device. We actually don't need to do anything.
  1927. // Because folder config has changed (since the device lists do not match)
  1928. // Folders for that had device got "restarted", which involves killing
  1929. // connections to all devices that we were sharing the folder with.
  1930. // At some point model.Close() will get called for that device which will
  1931. // clean residue device state that is not part of any folder.
  1932. // Some options don't require restart as those components handle it fine
  1933. // by themselves.
  1934. from.Options.URAccepted = to.Options.URAccepted
  1935. from.Options.URUniqueID = to.Options.URUniqueID
  1936. from.Options.ListenAddresses = to.Options.ListenAddresses
  1937. from.Options.RelaysEnabled = to.Options.RelaysEnabled
  1938. from.Options.UnackedNotificationIDs = to.Options.UnackedNotificationIDs
  1939. // All of the other generic options require restart. Or at least they may;
  1940. // removing this check requires going through those options carefully and
  1941. // making sure there are individual services that handle them correctly.
  1942. // This code is the "original" requires-restart check and protects other
  1943. // components that haven't yet been converted to VerifyConfig/CommitConfig
  1944. // handling.
  1945. if !reflect.DeepEqual(from.Options, to.Options) {
  1946. l.Debugln(m, "requires restart, options differ")
  1947. return false
  1948. }
  1949. return true
  1950. }
  1951. // mapFolders returns a map of folder ID to folder configuration for the given
  1952. // slice of folder configurations.
  1953. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1954. m := make(map[string]config.FolderConfiguration, len(folders))
  1955. for _, cfg := range folders {
  1956. m[cfg.ID] = cfg
  1957. }
  1958. return m
  1959. }
  1960. // mapDevices returns a map of device ID to nothing for the given slice of
  1961. // device IDs.
  1962. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1963. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1964. for _, dev := range devices {
  1965. m[dev] = struct{}{}
  1966. }
  1967. return m
  1968. }
  1969. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1970. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1971. symlinkWarning.Do(func() {
  1972. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1973. })
  1974. // Need to type switch for the concrete type to be able to access fields...
  1975. var name string
  1976. switch fi := fi.(type) {
  1977. case protocol.FileInfo:
  1978. name = fi.Name
  1979. case db.FileInfoTruncated:
  1980. name = fi.Name
  1981. }
  1982. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1983. return true
  1984. }
  1985. return false
  1986. }
  1987. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1988. // Returns the resulting slice, plus how much elements are left to skip or
  1989. // copy to satisfy the values which were provided, given the slice is not
  1990. // big enough.
  1991. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1992. l := len(data)
  1993. if l <= skip {
  1994. return []string{}, skip - l, get
  1995. } else if l < skip+get {
  1996. return data[skip:l], 0, get - (l - skip)
  1997. }
  1998. return data[skip : skip+get], 0, 0
  1999. }
  2000. func closeRawConn(conn io.Closer) error {
  2001. if conn, ok := conn.(*tls.Conn); ok {
  2002. // If the underlying connection is a *tls.Conn, Close() does more
  2003. // than it says on the tin. Specifically, it sends a TLS alert
  2004. // message, which might block forever if the connection is dead
  2005. // and we don't have a deadline set.
  2006. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  2007. }
  2008. return conn.Close()
  2009. }
  2010. func stringSliceWithout(ss []string, s string) []string {
  2011. for i := range ss {
  2012. if ss[i] == s {
  2013. copy(ss[i:], ss[i+1:])
  2014. ss = ss[:len(ss)-1]
  2015. return ss
  2016. }
  2017. }
  2018. return ss
  2019. }
  2020. func readOffsetIntoBuf(file string, offset int64, buf []byte) error {
  2021. fd, err := os.Open(file)
  2022. if err != nil {
  2023. l.Debugln("readOffsetIntoBuf.Open", file, err)
  2024. return err
  2025. }
  2026. defer fd.Close()
  2027. _, err = fd.ReadAt(buf, offset)
  2028. if err != nil {
  2029. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  2030. }
  2031. return err
  2032. }
  2033. // The exists function is expected to return true for all known paths
  2034. // (excluding "" and ".")
  2035. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  2036. subs := trimUntilParentKnown(dirs, exists)
  2037. sort.Strings(subs)
  2038. return simplifySortedPaths(subs)
  2039. }
  2040. func trimUntilParentKnown(dirs []string, exists func(dir string) bool) []string {
  2041. var subs []string
  2042. for _, sub := range dirs {
  2043. for sub != "" && sub != ".stfolder" && sub != ".stignore" {
  2044. sub = filepath.Clean(sub)
  2045. parent := filepath.Dir(sub)
  2046. if parent == "." || exists(parent) {
  2047. break
  2048. }
  2049. sub = parent
  2050. if sub == "." || sub == string(filepath.Separator) {
  2051. // Shortcut. We are going to scan the full folder, so we can
  2052. // just return an empty list of subs at this point.
  2053. return nil
  2054. }
  2055. }
  2056. if sub == "" {
  2057. return nil
  2058. }
  2059. subs = append(subs, sub)
  2060. }
  2061. return subs
  2062. }
  2063. func simplifySortedPaths(subs []string) []string {
  2064. var cleaned []string
  2065. next:
  2066. for _, sub := range subs {
  2067. for _, existing := range cleaned {
  2068. if sub == existing || strings.HasPrefix(sub, existing+string(os.PathSeparator)) {
  2069. continue next
  2070. }
  2071. }
  2072. cleaned = append(cleaned, sub)
  2073. }
  2074. return cleaned
  2075. }
  2076. // makeForgetUpdate takes an index update and constructs a download progress update
  2077. // causing to forget any progress for files which we've just been sent.
  2078. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  2079. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  2080. for _, file := range files {
  2081. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  2082. continue
  2083. }
  2084. updates = append(updates, protocol.FileDownloadProgressUpdate{
  2085. Name: file.Name,
  2086. Version: file.Version,
  2087. UpdateType: protocol.UpdateTypeForget,
  2088. })
  2089. }
  2090. return updates
  2091. }
  2092. // shouldIgnore returns true when a file should be excluded from processing
  2093. func shouldIgnore(file db.FileIntf, matcher *ignore.Matcher, ignoreDelete bool) bool {
  2094. // We check things in a certain order here...
  2095. switch {
  2096. case ignoreDelete && file.IsDeleted():
  2097. // ignoreDelete first because it's a very cheap test so a win if it
  2098. // succeeds, and we might in the long run accumulate quite a few
  2099. // deleted files.
  2100. return true
  2101. case matcher.Match(file.FileName()).IsIgnored():
  2102. // ignore patterns second because ignoring them is a valid way to
  2103. // silence warnings about them being invalid and so on.
  2104. return true
  2105. }
  2106. return false
  2107. }