model.go 78 KB

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