model.go 77 KB

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