model.go 80 KB

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