model.go 82 KB

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