model.go 77 KB

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