model.go 77 KB

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