model.go 83 KB

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