model.go 85 KB

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