model.go 77 KB

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