model.go 86 KB

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