model.go 80 KB

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