model.go 76 KB

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