model.go 83 KB

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