model.go 69 KB

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