model.go 80 KB

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