model.go 80 KB

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