model_test.go 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  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. "bytes"
  9. "encoding/json"
  10. "fmt"
  11. "io/ioutil"
  12. "math/rand"
  13. "net"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. "strconv"
  18. "sync"
  19. "testing"
  20. "time"
  21. "github.com/d4l3k/messagediff"
  22. "github.com/syncthing/syncthing/lib/config"
  23. "github.com/syncthing/syncthing/lib/db"
  24. "github.com/syncthing/syncthing/lib/ignore"
  25. "github.com/syncthing/syncthing/lib/osutil"
  26. "github.com/syncthing/syncthing/lib/protocol"
  27. srand "github.com/syncthing/syncthing/lib/rand"
  28. "github.com/syncthing/syncthing/lib/scanner"
  29. )
  30. var device1, device2 protocol.DeviceID
  31. var defaultConfig *config.Wrapper
  32. var defaultFolderConfig config.FolderConfiguration
  33. func init() {
  34. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  35. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  36. defaultFolderConfig = config.NewFolderConfiguration("default", "testdata")
  37. defaultFolderConfig.Devices = []config.FolderDeviceConfiguration{{DeviceID: device1}}
  38. _defaultConfig := config.Configuration{
  39. Folders: []config.FolderConfiguration{defaultFolderConfig},
  40. Devices: []config.DeviceConfiguration{config.NewDeviceConfiguration(device1, "device1")},
  41. Options: config.OptionsConfiguration{
  42. // Don't remove temporaries directly on startup
  43. KeepTemporariesH: 1,
  44. },
  45. }
  46. defaultConfig = config.Wrap("/tmp/test", _defaultConfig)
  47. }
  48. var testDataExpected = map[string]protocol.FileInfo{
  49. "foo": {
  50. Name: "foo",
  51. Type: protocol.FileInfoTypeFile,
  52. ModifiedS: 0,
  53. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0x7, Hash: []uint8{0xae, 0xc0, 0x70, 0x64, 0x5f, 0xe5, 0x3e, 0xe3, 0xb3, 0x76, 0x30, 0x59, 0x37, 0x61, 0x34, 0xf0, 0x58, 0xcc, 0x33, 0x72, 0x47, 0xc9, 0x78, 0xad, 0xd1, 0x78, 0xb6, 0xcc, 0xdf, 0xb0, 0x1, 0x9f}}},
  54. },
  55. "empty": {
  56. Name: "empty",
  57. Type: protocol.FileInfoTypeFile,
  58. ModifiedS: 0,
  59. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0x0, Hash: []uint8{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}}},
  60. },
  61. "bar": {
  62. Name: "bar",
  63. Type: protocol.FileInfoTypeFile,
  64. ModifiedS: 0,
  65. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}},
  66. },
  67. }
  68. func init() {
  69. // Fix expected test data to match reality
  70. for n, f := range testDataExpected {
  71. fi, _ := os.Stat("testdata/" + n)
  72. f.Permissions = uint32(fi.Mode())
  73. f.ModifiedS = fi.ModTime().Unix()
  74. f.Size = fi.Size()
  75. testDataExpected[n] = f
  76. }
  77. }
  78. func TestRequest(t *testing.T) {
  79. db := db.OpenMemory()
  80. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  81. // device1 shares default, but device2 doesn't
  82. m.AddFolder(defaultFolderConfig)
  83. m.StartFolder("default")
  84. m.ServeBackground()
  85. defer m.Stop()
  86. m.ScanFolder("default")
  87. bs := make([]byte, protocol.BlockSize)
  88. // Existing, shared file
  89. bs = bs[:6]
  90. err := m.Request(device1, "default", "foo", 0, nil, false, bs)
  91. if err != nil {
  92. t.Error(err)
  93. }
  94. if !bytes.Equal(bs, []byte("foobar")) {
  95. t.Errorf("Incorrect data from request: %q", string(bs))
  96. }
  97. // Existing, nonshared file
  98. err = m.Request(device2, "default", "foo", 0, nil, false, bs)
  99. if err == nil {
  100. t.Error("Unexpected nil error on insecure file read")
  101. }
  102. // Nonexistent file
  103. err = m.Request(device1, "default", "nonexistent", 0, nil, false, bs)
  104. if err == nil {
  105. t.Error("Unexpected nil error on insecure file read")
  106. }
  107. // Shared folder, but disallowed file name
  108. err = m.Request(device1, "default", "../walk.go", 0, nil, false, bs)
  109. if err == nil {
  110. t.Error("Unexpected nil error on insecure file read")
  111. }
  112. // Negative offset
  113. err = m.Request(device1, "default", "foo", -4, nil, false, bs[:0])
  114. if err == nil {
  115. t.Error("Unexpected nil error on insecure file read")
  116. }
  117. // Larger block than available
  118. bs = bs[:42]
  119. err = m.Request(device1, "default", "foo", 0, nil, false, bs)
  120. if err == nil {
  121. t.Error("Unexpected nil error on insecure file read")
  122. }
  123. }
  124. func genFiles(n int) []protocol.FileInfo {
  125. files := make([]protocol.FileInfo, n)
  126. t := time.Now().Unix()
  127. for i := 0; i < n; i++ {
  128. files[i] = protocol.FileInfo{
  129. Name: fmt.Sprintf("file%d", i),
  130. ModifiedS: t,
  131. Sequence: int64(i + 1),
  132. Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
  133. }
  134. }
  135. return files
  136. }
  137. func BenchmarkIndex_10000(b *testing.B) {
  138. benchmarkIndex(b, 10000)
  139. }
  140. func BenchmarkIndex_100(b *testing.B) {
  141. benchmarkIndex(b, 100)
  142. }
  143. func benchmarkIndex(b *testing.B, nfiles int) {
  144. db := db.OpenMemory()
  145. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  146. m.AddFolder(defaultFolderConfig)
  147. m.StartFolder("default")
  148. m.ServeBackground()
  149. defer m.Stop()
  150. files := genFiles(nfiles)
  151. m.Index(device1, "default", files)
  152. b.ResetTimer()
  153. for i := 0; i < b.N; i++ {
  154. m.Index(device1, "default", files)
  155. }
  156. b.ReportAllocs()
  157. }
  158. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  159. benchmarkIndexUpdate(b, 10000, 10000)
  160. }
  161. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  162. benchmarkIndexUpdate(b, 10000, 100)
  163. }
  164. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  165. benchmarkIndexUpdate(b, 10000, 1)
  166. }
  167. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  168. db := db.OpenMemory()
  169. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  170. m.AddFolder(defaultFolderConfig)
  171. m.StartFolder("default")
  172. m.ServeBackground()
  173. defer m.Stop()
  174. files := genFiles(nfiles)
  175. ufiles := genFiles(nufiles)
  176. m.Index(device1, "default", files)
  177. b.ResetTimer()
  178. for i := 0; i < b.N; i++ {
  179. m.IndexUpdate(device1, "default", ufiles)
  180. }
  181. b.ReportAllocs()
  182. }
  183. type downloadProgressMessage struct {
  184. folder string
  185. updates []protocol.FileDownloadProgressUpdate
  186. }
  187. type fakeConnection struct {
  188. id protocol.DeviceID
  189. downloadProgressMessages []downloadProgressMessage
  190. closed bool
  191. files []protocol.FileInfo
  192. fileData map[string][]byte
  193. folder string
  194. model *Model
  195. indexFn func(string, []protocol.FileInfo)
  196. mut sync.Mutex
  197. }
  198. func (f *fakeConnection) Close() error {
  199. f.mut.Lock()
  200. defer f.mut.Unlock()
  201. f.closed = true
  202. return nil
  203. }
  204. func (f *fakeConnection) Start() {
  205. }
  206. func (f *fakeConnection) ID() protocol.DeviceID {
  207. return f.id
  208. }
  209. func (f *fakeConnection) Name() string {
  210. return ""
  211. }
  212. func (f *fakeConnection) Option(string) string {
  213. return ""
  214. }
  215. func (f *fakeConnection) Index(folder string, fs []protocol.FileInfo) error {
  216. f.mut.Lock()
  217. defer f.mut.Unlock()
  218. if f.indexFn != nil {
  219. f.indexFn(folder, fs)
  220. }
  221. return nil
  222. }
  223. func (f *fakeConnection) IndexUpdate(folder string, fs []protocol.FileInfo) error {
  224. f.mut.Lock()
  225. defer f.mut.Unlock()
  226. if f.indexFn != nil {
  227. f.indexFn(folder, fs)
  228. }
  229. return nil
  230. }
  231. func (f *fakeConnection) Request(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  232. return f.fileData[name], nil
  233. }
  234. func (f *fakeConnection) ClusterConfig(protocol.ClusterConfig) {}
  235. func (f *fakeConnection) Ping() bool {
  236. f.mut.Lock()
  237. defer f.mut.Unlock()
  238. return f.closed
  239. }
  240. func (f *fakeConnection) Closed() bool {
  241. f.mut.Lock()
  242. defer f.mut.Unlock()
  243. return f.closed
  244. }
  245. func (f *fakeConnection) Statistics() protocol.Statistics {
  246. return protocol.Statistics{}
  247. }
  248. func (f *fakeConnection) RemoteAddr() net.Addr {
  249. return &fakeAddr{}
  250. }
  251. func (f *fakeConnection) Type() string {
  252. return "fake"
  253. }
  254. func (f *fakeConnection) DownloadProgress(folder string, updates []protocol.FileDownloadProgressUpdate) {
  255. f.downloadProgressMessages = append(f.downloadProgressMessages, downloadProgressMessage{
  256. folder: folder,
  257. updates: updates,
  258. })
  259. }
  260. func (f *fakeConnection) addFile(name string, flags uint32, data []byte) {
  261. f.mut.Lock()
  262. defer f.mut.Unlock()
  263. blocks, _ := scanner.Blocks(bytes.NewReader(data), protocol.BlockSize, int64(len(data)), nil)
  264. var version protocol.Vector
  265. version.Update(f.id.Short())
  266. f.files = append(f.files, protocol.FileInfo{
  267. Name: name,
  268. Type: protocol.FileInfoTypeFile,
  269. Size: int64(len(data)),
  270. ModifiedS: time.Now().Unix(),
  271. Permissions: flags,
  272. Version: version,
  273. Sequence: time.Now().UnixNano(),
  274. Blocks: blocks,
  275. })
  276. if f.fileData == nil {
  277. f.fileData = make(map[string][]byte)
  278. }
  279. f.fileData[name] = data
  280. }
  281. func (f *fakeConnection) sendIndexUpdate() {
  282. f.model.IndexUpdate(f.id, f.folder, f.files)
  283. }
  284. func BenchmarkRequest(b *testing.B) {
  285. db := db.OpenMemory()
  286. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  287. m.AddFolder(defaultFolderConfig)
  288. m.ServeBackground()
  289. defer m.Stop()
  290. m.ScanFolder("default")
  291. const n = 1000
  292. files := genFiles(n)
  293. fc := &fakeConnection{id: device1}
  294. for _, f := range files {
  295. fc.addFile(f.Name, 0644, []byte("some data to return"))
  296. }
  297. m.AddConnection(fc, protocol.HelloResult{})
  298. m.Index(device1, "default", files)
  299. b.ResetTimer()
  300. for i := 0; i < b.N; i++ {
  301. data, err := m.requestGlobal(device1, "default", files[i%n].Name, 0, 32, nil, false)
  302. if err != nil {
  303. b.Error(err)
  304. }
  305. if data == nil {
  306. b.Error("nil data")
  307. }
  308. }
  309. }
  310. func TestDeviceRename(t *testing.T) {
  311. hello := protocol.HelloResult{
  312. ClientName: "syncthing",
  313. ClientVersion: "v0.9.4",
  314. }
  315. defer os.Remove("tmpconfig.xml")
  316. rawCfg := config.New(device1)
  317. rawCfg.Devices = []config.DeviceConfiguration{
  318. {
  319. DeviceID: device1,
  320. },
  321. }
  322. cfg := config.Wrap("tmpconfig.xml", rawCfg)
  323. db := db.OpenMemory()
  324. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  325. if cfg.Devices()[device1].Name != "" {
  326. t.Errorf("Device already has a name")
  327. }
  328. conn := &fakeConnection{id: device1}
  329. m.AddConnection(conn, hello)
  330. m.ServeBackground()
  331. defer m.Stop()
  332. if cfg.Devices()[device1].Name != "" {
  333. t.Errorf("Device already has a name")
  334. }
  335. m.Closed(conn, protocol.ErrTimeout)
  336. hello.DeviceName = "tester"
  337. m.AddConnection(conn, hello)
  338. if cfg.Devices()[device1].Name != "tester" {
  339. t.Errorf("Device did not get a name")
  340. }
  341. m.Closed(conn, protocol.ErrTimeout)
  342. hello.DeviceName = "tester2"
  343. m.AddConnection(conn, hello)
  344. if cfg.Devices()[device1].Name != "tester" {
  345. t.Errorf("Device name got overwritten")
  346. }
  347. cfgw, err := config.Load("tmpconfig.xml", protocol.LocalDeviceID)
  348. if err != nil {
  349. t.Error(err)
  350. return
  351. }
  352. if cfgw.Devices()[device1].Name != "tester" {
  353. t.Errorf("Device name not saved in config")
  354. }
  355. m.Closed(conn, protocol.ErrTimeout)
  356. opts := cfg.Options()
  357. opts.OverwriteRemoteDevNames = true
  358. cfg.SetOptions(opts)
  359. hello.DeviceName = "tester2"
  360. m.AddConnection(conn, hello)
  361. if cfg.Devices()[device1].Name != "tester2" {
  362. t.Errorf("Device name not overwritten")
  363. }
  364. }
  365. func TestClusterConfig(t *testing.T) {
  366. cfg := config.New(device1)
  367. cfg.Devices = []config.DeviceConfiguration{
  368. {
  369. DeviceID: device1,
  370. Introducer: true,
  371. },
  372. {
  373. DeviceID: device2,
  374. },
  375. }
  376. cfg.Folders = []config.FolderConfiguration{
  377. {
  378. ID: "folder1",
  379. Devices: []config.FolderDeviceConfiguration{
  380. {DeviceID: device1},
  381. {DeviceID: device2},
  382. },
  383. },
  384. {
  385. ID: "folder2",
  386. Devices: []config.FolderDeviceConfiguration{
  387. {DeviceID: device1},
  388. {DeviceID: device2},
  389. },
  390. },
  391. }
  392. db := db.OpenMemory()
  393. m := NewModel(config.Wrap("/tmp/test", cfg), protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  394. m.AddFolder(cfg.Folders[0])
  395. m.AddFolder(cfg.Folders[1])
  396. m.ServeBackground()
  397. defer m.Stop()
  398. cm := m.generateClusterConfig(device2)
  399. if l := len(cm.Folders); l != 2 {
  400. t.Fatalf("Incorrect number of folders %d != 2", l)
  401. }
  402. r := cm.Folders[0]
  403. if r.ID != "folder1" {
  404. t.Errorf("Incorrect folder %q != folder1", r.ID)
  405. }
  406. if l := len(r.Devices); l != 2 {
  407. t.Errorf("Incorrect number of devices %d != 2", l)
  408. }
  409. if id := r.Devices[0].ID; id != device1 {
  410. t.Errorf("Incorrect device ID %s != %s", id, device1)
  411. }
  412. if !r.Devices[0].Introducer {
  413. t.Error("Device1 should be flagged as Introducer")
  414. }
  415. if id := r.Devices[1].ID; id != device2 {
  416. t.Errorf("Incorrect device ID %s != %s", id, device2)
  417. }
  418. if r.Devices[1].Introducer {
  419. t.Error("Device2 should not be flagged as Introducer")
  420. }
  421. r = cm.Folders[1]
  422. if r.ID != "folder2" {
  423. t.Errorf("Incorrect folder %q != folder2", r.ID)
  424. }
  425. if l := len(r.Devices); l != 2 {
  426. t.Errorf("Incorrect number of devices %d != 2", l)
  427. }
  428. if id := r.Devices[0].ID; id != device1 {
  429. t.Errorf("Incorrect device ID %s != %s", id, device1)
  430. }
  431. if !r.Devices[0].Introducer {
  432. t.Error("Device1 should be flagged as Introducer")
  433. }
  434. if id := r.Devices[1].ID; id != device2 {
  435. t.Errorf("Incorrect device ID %s != %s", id, device2)
  436. }
  437. if r.Devices[1].Introducer {
  438. t.Error("Device2 should not be flagged as Introducer")
  439. }
  440. }
  441. func TestIntroducer(t *testing.T) {
  442. var introducedByAnyone protocol.DeviceID
  443. // LocalDeviceID is a magic value meaning don't check introducer
  444. contains := func(cfg config.FolderConfiguration, id, introducedBy protocol.DeviceID) bool {
  445. for _, dev := range cfg.Devices {
  446. if dev.DeviceID.Equals(id) {
  447. if introducedBy.Equals(introducedByAnyone) {
  448. return true
  449. }
  450. return introducedBy.Equals(introducedBy)
  451. }
  452. }
  453. return false
  454. }
  455. newState := func(cfg config.Configuration) (*config.Wrapper, *Model) {
  456. db := db.OpenMemory()
  457. wcfg := config.Wrap("/tmp/test", cfg)
  458. m := NewModel(wcfg, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  459. for _, folder := range cfg.Folders {
  460. m.AddFolder(folder)
  461. }
  462. m.ServeBackground()
  463. m.AddConnection(&fakeConnection{id: device1}, protocol.HelloResult{})
  464. return wcfg, m
  465. }
  466. wcfg, m := newState(config.Configuration{
  467. Devices: []config.DeviceConfiguration{
  468. {
  469. DeviceID: device1,
  470. Introducer: true,
  471. },
  472. },
  473. Folders: []config.FolderConfiguration{
  474. {
  475. ID: "folder1",
  476. Devices: []config.FolderDeviceConfiguration{
  477. {DeviceID: device1},
  478. },
  479. },
  480. {
  481. ID: "folder2",
  482. Devices: []config.FolderDeviceConfiguration{
  483. {DeviceID: device1},
  484. },
  485. },
  486. },
  487. })
  488. m.ClusterConfig(device1, protocol.ClusterConfig{
  489. Folders: []protocol.Folder{
  490. {
  491. ID: "folder1",
  492. Devices: []protocol.Device{
  493. {
  494. ID: device2,
  495. Introducer: true,
  496. SkipIntroductionRemovals: true,
  497. },
  498. },
  499. },
  500. },
  501. })
  502. if newDev, ok := wcfg.Device(device2); !ok || !newDev.Introducer || !newDev.SkipIntroductionRemovals {
  503. t.Error("devie 2 missing or wrong flags")
  504. }
  505. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  506. t.Error("expected folder 1 to have device2 introduced by device 1")
  507. }
  508. wcfg, m = newState(config.Configuration{
  509. Devices: []config.DeviceConfiguration{
  510. {
  511. DeviceID: device1,
  512. Introducer: true,
  513. },
  514. {
  515. DeviceID: device2,
  516. IntroducedBy: device1,
  517. },
  518. },
  519. Folders: []config.FolderConfiguration{
  520. {
  521. ID: "folder1",
  522. Devices: []config.FolderDeviceConfiguration{
  523. {DeviceID: device1},
  524. {DeviceID: device2, IntroducedBy: device1},
  525. },
  526. },
  527. {
  528. ID: "folder2",
  529. Devices: []config.FolderDeviceConfiguration{
  530. {DeviceID: device1},
  531. },
  532. },
  533. },
  534. })
  535. m.ClusterConfig(device1, protocol.ClusterConfig{
  536. Folders: []protocol.Folder{
  537. {
  538. ID: "folder2",
  539. Devices: []protocol.Device{
  540. {
  541. ID: device2,
  542. Introducer: true,
  543. SkipIntroductionRemovals: true,
  544. },
  545. },
  546. },
  547. },
  548. })
  549. // Should not get introducer, as it's already unset, and it's an existing device.
  550. if newDev, ok := wcfg.Device(device2); !ok || newDev.Introducer || newDev.SkipIntroductionRemovals {
  551. t.Error("device 2 missing or changed flags")
  552. }
  553. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  554. t.Error("expected device 2 to be removed from folder 1")
  555. }
  556. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  557. t.Error("expected device 2 to be added to folder 2")
  558. }
  559. wcfg, m = newState(config.Configuration{
  560. Devices: []config.DeviceConfiguration{
  561. {
  562. DeviceID: device1,
  563. Introducer: true,
  564. },
  565. {
  566. DeviceID: device2,
  567. IntroducedBy: device1,
  568. },
  569. },
  570. Folders: []config.FolderConfiguration{
  571. {
  572. ID: "folder1",
  573. Devices: []config.FolderDeviceConfiguration{
  574. {DeviceID: device1},
  575. {DeviceID: device2, IntroducedBy: device1},
  576. },
  577. },
  578. {
  579. ID: "folder2",
  580. Devices: []config.FolderDeviceConfiguration{
  581. {DeviceID: device1},
  582. {DeviceID: device2, IntroducedBy: device1},
  583. },
  584. },
  585. },
  586. })
  587. m.ClusterConfig(device1, protocol.ClusterConfig{})
  588. if _, ok := wcfg.Device(device2); ok {
  589. t.Error("device 2 should have been removed")
  590. }
  591. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  592. t.Error("expected device 2 to be removed from folder 1")
  593. }
  594. if contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  595. t.Error("expected device 2 to be removed from folder 2")
  596. }
  597. // Two cases when removals should not happen
  598. // 1. Introducer flag no longer set on device
  599. wcfg, m = newState(config.Configuration{
  600. Devices: []config.DeviceConfiguration{
  601. {
  602. DeviceID: device1,
  603. Introducer: false,
  604. },
  605. {
  606. DeviceID: device2,
  607. IntroducedBy: device1,
  608. },
  609. },
  610. Folders: []config.FolderConfiguration{
  611. {
  612. ID: "folder1",
  613. Devices: []config.FolderDeviceConfiguration{
  614. {DeviceID: device1},
  615. {DeviceID: device2, IntroducedBy: device1},
  616. },
  617. },
  618. {
  619. ID: "folder2",
  620. Devices: []config.FolderDeviceConfiguration{
  621. {DeviceID: device1},
  622. {DeviceID: device2, IntroducedBy: device1},
  623. },
  624. },
  625. },
  626. })
  627. m.ClusterConfig(device1, protocol.ClusterConfig{})
  628. if _, ok := wcfg.Device(device2); !ok {
  629. t.Error("device 2 should not have been removed")
  630. }
  631. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  632. t.Error("expected device 2 not to be removed from folder 1")
  633. }
  634. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  635. t.Error("expected device 2 not to be removed from folder 2")
  636. }
  637. // 2. SkipIntroductionRemovals is set
  638. wcfg, m = newState(config.Configuration{
  639. Devices: []config.DeviceConfiguration{
  640. {
  641. DeviceID: device1,
  642. Introducer: true,
  643. SkipIntroductionRemovals: true,
  644. },
  645. {
  646. DeviceID: device2,
  647. IntroducedBy: device1,
  648. },
  649. },
  650. Folders: []config.FolderConfiguration{
  651. {
  652. ID: "folder1",
  653. Devices: []config.FolderDeviceConfiguration{
  654. {DeviceID: device1},
  655. {DeviceID: device2, IntroducedBy: device1},
  656. },
  657. },
  658. {
  659. ID: "folder2",
  660. Devices: []config.FolderDeviceConfiguration{
  661. {DeviceID: device1},
  662. },
  663. },
  664. },
  665. })
  666. m.ClusterConfig(device1, protocol.ClusterConfig{
  667. Folders: []protocol.Folder{
  668. {
  669. ID: "folder2",
  670. Devices: []protocol.Device{
  671. {
  672. ID: device2,
  673. Introducer: true,
  674. SkipIntroductionRemovals: true,
  675. },
  676. },
  677. },
  678. },
  679. })
  680. if _, ok := wcfg.Device(device2); !ok {
  681. t.Error("device 2 should not have been removed")
  682. }
  683. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  684. t.Error("expected device 2 not to be removed from folder 1")
  685. }
  686. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  687. t.Error("expected device 2 not to be added to folder 2")
  688. }
  689. // Test device not being removed as it's shared without an introducer.
  690. wcfg, m = newState(config.Configuration{
  691. Devices: []config.DeviceConfiguration{
  692. {
  693. DeviceID: device1,
  694. Introducer: true,
  695. },
  696. {
  697. DeviceID: device2,
  698. IntroducedBy: device1,
  699. },
  700. },
  701. Folders: []config.FolderConfiguration{
  702. {
  703. ID: "folder1",
  704. Devices: []config.FolderDeviceConfiguration{
  705. {DeviceID: device1},
  706. {DeviceID: device2, IntroducedBy: device1},
  707. },
  708. },
  709. {
  710. ID: "folder2",
  711. Devices: []config.FolderDeviceConfiguration{
  712. {DeviceID: device1},
  713. {DeviceID: device2},
  714. },
  715. },
  716. },
  717. })
  718. m.ClusterConfig(device1, protocol.ClusterConfig{})
  719. if _, ok := wcfg.Device(device2); !ok {
  720. t.Error("device 2 should not have been removed")
  721. }
  722. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  723. t.Error("expected device 2 to be removed from folder 1")
  724. }
  725. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  726. t.Error("expected device 2 not to be removed from folder 2")
  727. }
  728. // Test device not being removed as it's shared by a different introducer.
  729. wcfg, m = newState(config.Configuration{
  730. Devices: []config.DeviceConfiguration{
  731. {
  732. DeviceID: device1,
  733. Introducer: true,
  734. },
  735. {
  736. DeviceID: device2,
  737. IntroducedBy: device1,
  738. },
  739. },
  740. Folders: []config.FolderConfiguration{
  741. {
  742. ID: "folder1",
  743. Devices: []config.FolderDeviceConfiguration{
  744. {DeviceID: device1},
  745. {DeviceID: device2, IntroducedBy: device1},
  746. },
  747. },
  748. {
  749. ID: "folder2",
  750. Devices: []config.FolderDeviceConfiguration{
  751. {DeviceID: device1},
  752. {DeviceID: device2, IntroducedBy: protocol.LocalDeviceID},
  753. },
  754. },
  755. },
  756. })
  757. m.ClusterConfig(device1, protocol.ClusterConfig{})
  758. if _, ok := wcfg.Device(device2); !ok {
  759. t.Error("device 2 should not have been removed")
  760. }
  761. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  762. t.Error("expected device 2 to be removed from folder 1")
  763. }
  764. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  765. t.Error("expected device 2 not to be removed from folder 2")
  766. }
  767. }
  768. func TestIgnores(t *testing.T) {
  769. arrEqual := func(a, b []string) bool {
  770. if len(a) != len(b) {
  771. return false
  772. }
  773. for i := range a {
  774. if a[i] != b[i] {
  775. return false
  776. }
  777. }
  778. return true
  779. }
  780. // Assure a clean start state
  781. ioutil.WriteFile("testdata/.stfolder", nil, 0644)
  782. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  783. db := db.OpenMemory()
  784. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  785. m.AddFolder(defaultFolderConfig)
  786. m.StartFolder("default")
  787. m.ServeBackground()
  788. defer m.Stop()
  789. expected := []string{
  790. ".*",
  791. "quux",
  792. }
  793. ignores, _, err := m.GetIgnores("default")
  794. if err != nil {
  795. t.Error(err)
  796. }
  797. if !arrEqual(ignores, expected) {
  798. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  799. }
  800. ignores = append(ignores, "pox")
  801. err = m.SetIgnores("default", ignores)
  802. if err != nil {
  803. t.Error(err)
  804. }
  805. ignores2, _, err := m.GetIgnores("default")
  806. if err != nil {
  807. t.Error(err)
  808. }
  809. if arrEqual(expected, ignores2) {
  810. t.Errorf("Incorrect ignores: %v == %v", ignores2, expected)
  811. }
  812. if !arrEqual(ignores, ignores2) {
  813. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  814. }
  815. err = m.SetIgnores("default", expected)
  816. if err != nil {
  817. t.Error(err)
  818. }
  819. ignores, _, err = m.GetIgnores("default")
  820. if err != nil {
  821. t.Error(err)
  822. }
  823. if !arrEqual(ignores, expected) {
  824. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  825. }
  826. _, _, err = m.GetIgnores("doesnotexist")
  827. if err == nil {
  828. t.Error("No error")
  829. }
  830. err = m.SetIgnores("doesnotexist", expected)
  831. if err == nil {
  832. t.Error("No error")
  833. }
  834. // Invalid path, marker should be missing, hence returns an error.
  835. m.AddFolder(config.FolderConfiguration{ID: "fresh", RawPath: "XXX"})
  836. _, _, err = m.GetIgnores("fresh")
  837. if err == nil {
  838. t.Error("No error")
  839. }
  840. }
  841. func TestROScanRecovery(t *testing.T) {
  842. ldb := db.OpenMemory()
  843. set := db.NewFileSet("default", ldb)
  844. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  845. {Name: "dummyfile"},
  846. })
  847. fcfg := config.FolderConfiguration{
  848. ID: "default",
  849. RawPath: "testdata/rotestfolder",
  850. Type: config.FolderTypeReadOnly,
  851. RescanIntervalS: 1,
  852. }
  853. cfg := config.Wrap("/tmp/test", config.Configuration{
  854. Folders: []config.FolderConfiguration{fcfg},
  855. Devices: []config.DeviceConfiguration{
  856. {
  857. DeviceID: device1,
  858. },
  859. },
  860. })
  861. os.RemoveAll(fcfg.RawPath)
  862. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  863. m.AddFolder(fcfg)
  864. m.StartFolder("default")
  865. m.ServeBackground()
  866. defer m.Stop()
  867. waitFor := func(status string) error {
  868. timeout := time.Now().Add(2 * time.Second)
  869. for {
  870. _, _, err := m.State("default")
  871. if err == nil && status == "" {
  872. return nil
  873. }
  874. if err != nil && err.Error() == status {
  875. return nil
  876. }
  877. if time.Now().After(timeout) {
  878. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  879. }
  880. time.Sleep(10 * time.Millisecond)
  881. }
  882. }
  883. if err := waitFor("folder path missing"); err != nil {
  884. t.Error(err)
  885. return
  886. }
  887. os.Mkdir(fcfg.RawPath, 0700)
  888. if err := waitFor("folder marker missing"); err != nil {
  889. t.Error(err)
  890. return
  891. }
  892. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  893. if err != nil {
  894. t.Error(err)
  895. return
  896. }
  897. fd.Close()
  898. if err := waitFor(""); err != nil {
  899. t.Error(err)
  900. return
  901. }
  902. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  903. if err := waitFor("folder marker missing"); err != nil {
  904. t.Error(err)
  905. return
  906. }
  907. os.Remove(fcfg.RawPath)
  908. if err := waitFor("folder path missing"); err != nil {
  909. t.Error(err)
  910. return
  911. }
  912. }
  913. func TestRWScanRecovery(t *testing.T) {
  914. ldb := db.OpenMemory()
  915. set := db.NewFileSet("default", ldb)
  916. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  917. {Name: "dummyfile"},
  918. })
  919. fcfg := config.FolderConfiguration{
  920. ID: "default",
  921. RawPath: "testdata/rwtestfolder",
  922. Type: config.FolderTypeReadWrite,
  923. RescanIntervalS: 1,
  924. }
  925. cfg := config.Wrap("/tmp/test", config.Configuration{
  926. Folders: []config.FolderConfiguration{fcfg},
  927. Devices: []config.DeviceConfiguration{
  928. {
  929. DeviceID: device1,
  930. },
  931. },
  932. })
  933. os.RemoveAll(fcfg.RawPath)
  934. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  935. m.AddFolder(fcfg)
  936. m.StartFolder("default")
  937. m.ServeBackground()
  938. defer m.Stop()
  939. waitFor := func(status string) error {
  940. timeout := time.Now().Add(2 * time.Second)
  941. for {
  942. _, _, err := m.State("default")
  943. if err == nil && status == "" {
  944. return nil
  945. }
  946. if err != nil && err.Error() == status {
  947. return nil
  948. }
  949. if time.Now().After(timeout) {
  950. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  951. }
  952. time.Sleep(10 * time.Millisecond)
  953. }
  954. }
  955. if err := waitFor("folder path missing"); err != nil {
  956. t.Error(err)
  957. return
  958. }
  959. os.Mkdir(fcfg.RawPath, 0700)
  960. if err := waitFor("folder marker missing"); err != nil {
  961. t.Error(err)
  962. return
  963. }
  964. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  965. if err != nil {
  966. t.Error(err)
  967. return
  968. }
  969. fd.Close()
  970. if err := waitFor(""); err != nil {
  971. t.Error(err)
  972. return
  973. }
  974. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  975. if err := waitFor("folder marker missing"); err != nil {
  976. t.Error(err)
  977. return
  978. }
  979. os.Remove(fcfg.RawPath)
  980. if err := waitFor("folder path missing"); err != nil {
  981. t.Error(err)
  982. return
  983. }
  984. }
  985. func TestGlobalDirectoryTree(t *testing.T) {
  986. db := db.OpenMemory()
  987. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  988. m.AddFolder(defaultFolderConfig)
  989. m.ServeBackground()
  990. defer m.Stop()
  991. b := func(isfile bool, path ...string) protocol.FileInfo {
  992. typ := protocol.FileInfoTypeDirectory
  993. blocks := []protocol.BlockInfo{}
  994. if isfile {
  995. typ = protocol.FileInfoTypeFile
  996. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  997. }
  998. return protocol.FileInfo{
  999. Name: filepath.Join(path...),
  1000. Type: typ,
  1001. ModifiedS: 0x666,
  1002. Blocks: blocks,
  1003. Size: 0xa,
  1004. }
  1005. }
  1006. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  1007. testdata := []protocol.FileInfo{
  1008. b(false, "another"),
  1009. b(false, "another", "directory"),
  1010. b(true, "another", "directory", "afile"),
  1011. b(false, "another", "directory", "with"),
  1012. b(false, "another", "directory", "with", "a"),
  1013. b(true, "another", "directory", "with", "a", "file"),
  1014. b(true, "another", "directory", "with", "file"),
  1015. b(true, "another", "file"),
  1016. b(false, "other"),
  1017. b(false, "other", "rand"),
  1018. b(false, "other", "random"),
  1019. b(false, "other", "random", "dir"),
  1020. b(false, "other", "random", "dirx"),
  1021. b(false, "other", "randomx"),
  1022. b(false, "some"),
  1023. b(false, "some", "directory"),
  1024. b(false, "some", "directory", "with"),
  1025. b(false, "some", "directory", "with", "a"),
  1026. b(true, "some", "directory", "with", "a", "file"),
  1027. b(true, "rootfile"),
  1028. }
  1029. expectedResult := map[string]interface{}{
  1030. "another": map[string]interface{}{
  1031. "directory": map[string]interface{}{
  1032. "afile": filedata,
  1033. "with": map[string]interface{}{
  1034. "a": map[string]interface{}{
  1035. "file": filedata,
  1036. },
  1037. "file": filedata,
  1038. },
  1039. },
  1040. "file": filedata,
  1041. },
  1042. "other": map[string]interface{}{
  1043. "rand": map[string]interface{}{},
  1044. "random": map[string]interface{}{
  1045. "dir": map[string]interface{}{},
  1046. "dirx": map[string]interface{}{},
  1047. },
  1048. "randomx": map[string]interface{}{},
  1049. },
  1050. "some": map[string]interface{}{
  1051. "directory": map[string]interface{}{
  1052. "with": map[string]interface{}{
  1053. "a": map[string]interface{}{
  1054. "file": filedata,
  1055. },
  1056. },
  1057. },
  1058. },
  1059. "rootfile": filedata,
  1060. }
  1061. mm := func(data interface{}) string {
  1062. bytes, err := json.Marshal(data)
  1063. if err != nil {
  1064. panic(err)
  1065. }
  1066. return string(bytes)
  1067. }
  1068. m.Index(device1, "default", testdata)
  1069. result := m.GlobalDirectoryTree("default", "", -1, false)
  1070. if mm(result) != mm(expectedResult) {
  1071. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  1072. }
  1073. result = m.GlobalDirectoryTree("default", "another", -1, false)
  1074. if mm(result) != mm(expectedResult["another"]) {
  1075. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  1076. }
  1077. result = m.GlobalDirectoryTree("default", "", 0, false)
  1078. currentResult := map[string]interface{}{
  1079. "another": map[string]interface{}{},
  1080. "other": map[string]interface{}{},
  1081. "some": map[string]interface{}{},
  1082. "rootfile": filedata,
  1083. }
  1084. if mm(result) != mm(currentResult) {
  1085. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1086. }
  1087. result = m.GlobalDirectoryTree("default", "", 1, false)
  1088. currentResult = map[string]interface{}{
  1089. "another": map[string]interface{}{
  1090. "directory": map[string]interface{}{},
  1091. "file": filedata,
  1092. },
  1093. "other": map[string]interface{}{
  1094. "rand": map[string]interface{}{},
  1095. "random": map[string]interface{}{},
  1096. "randomx": map[string]interface{}{},
  1097. },
  1098. "some": map[string]interface{}{
  1099. "directory": map[string]interface{}{},
  1100. },
  1101. "rootfile": filedata,
  1102. }
  1103. if mm(result) != mm(currentResult) {
  1104. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1105. }
  1106. result = m.GlobalDirectoryTree("default", "", -1, true)
  1107. currentResult = map[string]interface{}{
  1108. "another": map[string]interface{}{
  1109. "directory": map[string]interface{}{
  1110. "with": map[string]interface{}{
  1111. "a": map[string]interface{}{},
  1112. },
  1113. },
  1114. },
  1115. "other": map[string]interface{}{
  1116. "rand": map[string]interface{}{},
  1117. "random": map[string]interface{}{
  1118. "dir": map[string]interface{}{},
  1119. "dirx": map[string]interface{}{},
  1120. },
  1121. "randomx": map[string]interface{}{},
  1122. },
  1123. "some": map[string]interface{}{
  1124. "directory": map[string]interface{}{
  1125. "with": map[string]interface{}{
  1126. "a": map[string]interface{}{},
  1127. },
  1128. },
  1129. },
  1130. }
  1131. if mm(result) != mm(currentResult) {
  1132. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1133. }
  1134. result = m.GlobalDirectoryTree("default", "", 1, true)
  1135. currentResult = map[string]interface{}{
  1136. "another": map[string]interface{}{
  1137. "directory": map[string]interface{}{},
  1138. },
  1139. "other": map[string]interface{}{
  1140. "rand": map[string]interface{}{},
  1141. "random": map[string]interface{}{},
  1142. "randomx": map[string]interface{}{},
  1143. },
  1144. "some": map[string]interface{}{
  1145. "directory": map[string]interface{}{},
  1146. },
  1147. }
  1148. if mm(result) != mm(currentResult) {
  1149. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1150. }
  1151. result = m.GlobalDirectoryTree("default", "another", 0, false)
  1152. currentResult = map[string]interface{}{
  1153. "directory": map[string]interface{}{},
  1154. "file": filedata,
  1155. }
  1156. if mm(result) != mm(currentResult) {
  1157. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1158. }
  1159. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1160. currentResult = map[string]interface{}{
  1161. "with": map[string]interface{}{},
  1162. }
  1163. if mm(result) != mm(currentResult) {
  1164. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1165. }
  1166. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1167. currentResult = map[string]interface{}{
  1168. "with": map[string]interface{}{
  1169. "a": map[string]interface{}{},
  1170. },
  1171. }
  1172. if mm(result) != mm(currentResult) {
  1173. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1174. }
  1175. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1176. currentResult = map[string]interface{}{
  1177. "with": map[string]interface{}{
  1178. "a": map[string]interface{}{
  1179. "file": filedata,
  1180. },
  1181. },
  1182. }
  1183. if mm(result) != mm(currentResult) {
  1184. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1185. }
  1186. result = m.GlobalDirectoryTree("default", "another", -1, true)
  1187. currentResult = map[string]interface{}{
  1188. "directory": map[string]interface{}{
  1189. "with": map[string]interface{}{
  1190. "a": map[string]interface{}{},
  1191. },
  1192. },
  1193. }
  1194. if mm(result) != mm(currentResult) {
  1195. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1196. }
  1197. // No prefix matching!
  1198. result = m.GlobalDirectoryTree("default", "som", -1, false)
  1199. currentResult = map[string]interface{}{}
  1200. if mm(result) != mm(currentResult) {
  1201. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1202. }
  1203. }
  1204. func TestGlobalDirectorySelfFixing(t *testing.T) {
  1205. db := db.OpenMemory()
  1206. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1207. m.AddFolder(defaultFolderConfig)
  1208. m.ServeBackground()
  1209. b := func(isfile bool, path ...string) protocol.FileInfo {
  1210. typ := protocol.FileInfoTypeDirectory
  1211. blocks := []protocol.BlockInfo{}
  1212. if isfile {
  1213. typ = protocol.FileInfoTypeFile
  1214. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  1215. }
  1216. return protocol.FileInfo{
  1217. Name: filepath.Join(path...),
  1218. Type: typ,
  1219. ModifiedS: 0x666,
  1220. Blocks: blocks,
  1221. Size: 0xa,
  1222. }
  1223. }
  1224. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  1225. testdata := []protocol.FileInfo{
  1226. b(true, "another", "directory", "afile"),
  1227. b(true, "another", "directory", "with", "a", "file"),
  1228. b(true, "another", "directory", "with", "file"),
  1229. b(false, "other", "random", "dirx"),
  1230. b(false, "other", "randomx"),
  1231. b(false, "some", "directory", "with", "x"),
  1232. b(true, "some", "directory", "with", "a", "file"),
  1233. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  1234. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  1235. }
  1236. expectedResult := map[string]interface{}{
  1237. "another": map[string]interface{}{
  1238. "directory": map[string]interface{}{
  1239. "afile": filedata,
  1240. "with": map[string]interface{}{
  1241. "a": map[string]interface{}{
  1242. "file": filedata,
  1243. },
  1244. "file": filedata,
  1245. },
  1246. },
  1247. },
  1248. "other": map[string]interface{}{
  1249. "random": map[string]interface{}{
  1250. "dirx": map[string]interface{}{},
  1251. },
  1252. "randomx": map[string]interface{}{},
  1253. },
  1254. "some": map[string]interface{}{
  1255. "directory": map[string]interface{}{
  1256. "with": map[string]interface{}{
  1257. "a": map[string]interface{}{
  1258. "file": filedata,
  1259. },
  1260. "x": map[string]interface{}{},
  1261. },
  1262. },
  1263. },
  1264. "this": map[string]interface{}{
  1265. "is": map[string]interface{}{
  1266. "a": map[string]interface{}{
  1267. "deep": map[string]interface{}{
  1268. "invalid": map[string]interface{}{
  1269. "directory": map[string]interface{}{},
  1270. },
  1271. },
  1272. },
  1273. },
  1274. },
  1275. "xthis": map[string]interface{}{
  1276. "is": map[string]interface{}{
  1277. "a": map[string]interface{}{
  1278. "deep": map[string]interface{}{
  1279. "invalid": map[string]interface{}{
  1280. "file": filedata,
  1281. },
  1282. },
  1283. },
  1284. },
  1285. },
  1286. }
  1287. mm := func(data interface{}) string {
  1288. bytes, err := json.Marshal(data)
  1289. if err != nil {
  1290. panic(err)
  1291. }
  1292. return string(bytes)
  1293. }
  1294. m.Index(device1, "default", testdata)
  1295. result := m.GlobalDirectoryTree("default", "", -1, false)
  1296. if mm(result) != mm(expectedResult) {
  1297. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  1298. }
  1299. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  1300. currentResult := map[string]interface{}{
  1301. "invalid": map[string]interface{}{
  1302. "file": filedata,
  1303. },
  1304. }
  1305. if mm(result) != mm(currentResult) {
  1306. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1307. }
  1308. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  1309. currentResult = map[string]interface{}{
  1310. "invalid": map[string]interface{}{},
  1311. }
  1312. if mm(result) != mm(currentResult) {
  1313. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1314. }
  1315. // !!! This is actually BAD, because we don't have enough level allowance
  1316. // to accept this file, hence the tree is left unbuilt !!!
  1317. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  1318. currentResult = map[string]interface{}{}
  1319. if mm(result) != mm(currentResult) {
  1320. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1321. }
  1322. }
  1323. func genDeepFiles(n, d int) []protocol.FileInfo {
  1324. rand.Seed(int64(n))
  1325. files := make([]protocol.FileInfo, n)
  1326. t := time.Now().Unix()
  1327. for i := 0; i < n; i++ {
  1328. path := ""
  1329. for i := 0; i <= d; i++ {
  1330. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  1331. }
  1332. sofar := ""
  1333. for _, path := range filepath.SplitList(path) {
  1334. sofar = filepath.Join(sofar, path)
  1335. files[i] = protocol.FileInfo{
  1336. Name: sofar,
  1337. }
  1338. i++
  1339. }
  1340. files[i].ModifiedS = t
  1341. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  1342. }
  1343. return files
  1344. }
  1345. func BenchmarkTree_10000_50(b *testing.B) {
  1346. benchmarkTree(b, 10000, 50)
  1347. }
  1348. func BenchmarkTree_100_50(b *testing.B) {
  1349. benchmarkTree(b, 100, 50)
  1350. }
  1351. func BenchmarkTree_100_10(b *testing.B) {
  1352. benchmarkTree(b, 100, 10)
  1353. }
  1354. func benchmarkTree(b *testing.B, n1, n2 int) {
  1355. db := db.OpenMemory()
  1356. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1357. m.AddFolder(defaultFolderConfig)
  1358. m.ServeBackground()
  1359. m.ScanFolder("default")
  1360. files := genDeepFiles(n1, n2)
  1361. m.Index(device1, "default", files)
  1362. b.ResetTimer()
  1363. for i := 0; i < b.N; i++ {
  1364. m.GlobalDirectoryTree("default", "", -1, false)
  1365. }
  1366. b.ReportAllocs()
  1367. }
  1368. func TestUnifySubs(t *testing.T) {
  1369. cases := []struct {
  1370. in []string // input to unifySubs
  1371. exists []string // paths that exist in the database
  1372. out []string // expected output
  1373. }{
  1374. {
  1375. // 0. trailing slashes are cleaned, known paths are just passed on
  1376. []string{"foo/", "bar//"},
  1377. []string{"foo", "bar"},
  1378. []string{"bar", "foo"}, // the output is sorted
  1379. },
  1380. {
  1381. // 1. "foo/bar" gets trimmed as it's covered by foo
  1382. []string{"foo", "bar/", "foo/bar/"},
  1383. []string{"foo", "bar"},
  1384. []string{"bar", "foo"},
  1385. },
  1386. {
  1387. // 2. "" gets simplified to the empty list; ie scan all
  1388. []string{"foo", ""},
  1389. []string{"foo"},
  1390. nil,
  1391. },
  1392. {
  1393. // 3. "foo/bar" is unknown, but it's kept
  1394. // because its parent is known
  1395. []string{"foo/bar"},
  1396. []string{"foo"},
  1397. []string{"foo/bar"},
  1398. },
  1399. {
  1400. // 4. two independent known paths, both are kept
  1401. // "usr/lib" is not a prefix of "usr/libexec"
  1402. []string{"usr/lib", "usr/libexec"},
  1403. []string{"usr", "usr/lib", "usr/libexec"},
  1404. []string{"usr/lib", "usr/libexec"},
  1405. },
  1406. {
  1407. // 5. "usr/lib" is a prefix of "usr/lib/exec"
  1408. []string{"usr/lib", "usr/lib/exec"},
  1409. []string{"usr", "usr/lib", "usr/libexec"},
  1410. []string{"usr/lib"},
  1411. },
  1412. {
  1413. // 6. .stignore and .stfolder are special and are passed on
  1414. // verbatim even though they are unknown
  1415. []string{".stfolder", ".stignore"},
  1416. []string{},
  1417. []string{".stfolder", ".stignore"},
  1418. },
  1419. {
  1420. // 7. but the presence of something else unknown forces an actual
  1421. // scan
  1422. []string{".stfolder", ".stignore", "foo/bar"},
  1423. []string{},
  1424. []string{".stfolder", ".stignore", "foo"},
  1425. },
  1426. {
  1427. // 8. explicit request to scan all
  1428. nil,
  1429. []string{"foo"},
  1430. nil,
  1431. },
  1432. {
  1433. // 9. empty list of subs
  1434. []string{},
  1435. []string{"foo"},
  1436. nil,
  1437. },
  1438. }
  1439. if runtime.GOOS == "windows" {
  1440. // Fixup path separators
  1441. for i := range cases {
  1442. for j, p := range cases[i].in {
  1443. cases[i].in[j] = filepath.FromSlash(p)
  1444. }
  1445. for j, p := range cases[i].exists {
  1446. cases[i].exists[j] = filepath.FromSlash(p)
  1447. }
  1448. for j, p := range cases[i].out {
  1449. cases[i].out[j] = filepath.FromSlash(p)
  1450. }
  1451. }
  1452. }
  1453. for i, tc := range cases {
  1454. exists := func(f string) bool {
  1455. for _, e := range tc.exists {
  1456. if f == e {
  1457. return true
  1458. }
  1459. }
  1460. return false
  1461. }
  1462. out := unifySubs(tc.in, exists)
  1463. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1464. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1465. }
  1466. }
  1467. }
  1468. func TestIssue3028(t *testing.T) {
  1469. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1470. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1471. t.Fatal(err)
  1472. }
  1473. defer os.Remove("testdata/testrm")
  1474. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1475. t.Fatal(err)
  1476. }
  1477. defer os.Remove("testdata/testrm2")
  1478. // Create a model and default folder
  1479. db := db.OpenMemory()
  1480. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1481. defCfg := defaultFolderConfig.Copy()
  1482. defCfg.RescanIntervalS = 86400
  1483. m.AddFolder(defCfg)
  1484. m.StartFolder("default")
  1485. m.ServeBackground()
  1486. // Ugly hack for testing: reach into the model for the rwfolder and wait
  1487. // for it to complete the initial scan. The risk is that it otherwise
  1488. // runs during our modifications and screws up the test.
  1489. m.fmut.RLock()
  1490. folder := m.folderRunners["default"].(*rwFolder)
  1491. m.fmut.RUnlock()
  1492. <-folder.initialScanCompleted
  1493. // Get a count of how many files are there now
  1494. locorigfiles := m.LocalSize("default").Files
  1495. globorigfiles := m.GlobalSize("default").Files
  1496. // Delete and rescan specifically these two
  1497. os.Remove("testdata/testrm")
  1498. os.Remove("testdata/testrm2")
  1499. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1500. // Verify that the number of files decreased by two and the number of
  1501. // deleted files increases by two
  1502. loc := m.LocalSize("default")
  1503. glob := m.GlobalSize("default")
  1504. if loc.Files != locorigfiles-2 {
  1505. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1506. }
  1507. if glob.Files != globorigfiles-2 {
  1508. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1509. }
  1510. if loc.Deleted != 2 {
  1511. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1512. }
  1513. if glob.Deleted != 2 {
  1514. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1515. }
  1516. }
  1517. func TestIssue3164(t *testing.T) {
  1518. os.RemoveAll("testdata/issue3164")
  1519. defer os.RemoveAll("testdata/issue3164")
  1520. if err := os.MkdirAll("testdata/issue3164/oktodelete/foobar", 0777); err != nil {
  1521. t.Fatal(err)
  1522. }
  1523. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  1524. t.Fatal(err)
  1525. }
  1526. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  1527. t.Fatal(err)
  1528. }
  1529. f := protocol.FileInfo{
  1530. Name: "issue3164",
  1531. }
  1532. m := ignore.New(false)
  1533. if err := m.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  1534. t.Fatal(err)
  1535. }
  1536. fl := rwFolder{
  1537. dbUpdates: make(chan dbUpdateJob, 1),
  1538. dir: "testdata",
  1539. }
  1540. fl.deleteDir(f, m)
  1541. if _, err := os.Stat("testdata/issue3164"); !os.IsNotExist(err) {
  1542. t.Fatal(err)
  1543. }
  1544. }
  1545. func TestScanNoDatabaseWrite(t *testing.T) {
  1546. // When scanning, nothing should be committed to database unless
  1547. // something actually changed.
  1548. db := db.OpenMemory()
  1549. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1550. m.AddFolder(defaultFolderConfig)
  1551. m.StartFolder("default")
  1552. m.ServeBackground()
  1553. // Start with no ignores, and restore the previous state when the test completes
  1554. curIgn, _, err := m.GetIgnores("default")
  1555. if err != nil {
  1556. t.Fatal(err)
  1557. }
  1558. defer m.SetIgnores("default", curIgn)
  1559. m.SetIgnores("default", nil)
  1560. fakeTime := time.Now().Add(5 * time.Second)
  1561. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1562. // Scan the folder twice. The second scan should be a no-op database wise
  1563. m.ScanFolder("default")
  1564. c0 := db.Committed()
  1565. m.ScanFolder("default")
  1566. c1 := db.Committed()
  1567. if c1 != c0 {
  1568. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  1569. }
  1570. // Ignore a file we know exists. It'll be updated in the database.
  1571. m.SetIgnores("default", []string{"foo"})
  1572. fakeTime = time.Now().Add(10 * time.Second)
  1573. os.Chtimes("testdata/.stignore", fakeTime, fakeTime)
  1574. m.ScanFolder("default")
  1575. c2 := db.Committed()
  1576. if c2 <= c1 {
  1577. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  1578. }
  1579. // Scan again. Nothing should happen.
  1580. m.ScanFolder("default")
  1581. c3 := db.Committed()
  1582. if c3 != c2 {
  1583. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  1584. }
  1585. }
  1586. func TestIssue2782(t *testing.T) {
  1587. // CheckFolderHealth should accept a symlinked folder, when using tilde-expanded path.
  1588. if runtime.GOOS == "windows" {
  1589. t.Skip("not reliable on Windows")
  1590. return
  1591. }
  1592. home := os.Getenv("HOME")
  1593. if home == "" {
  1594. t.Skip("no home")
  1595. }
  1596. // Create the test env. Needs to be based on $HOME as tilde expansion is
  1597. // part of the issue. Skip the test if any of this fails, as we are a
  1598. // bit outside of our stated domain here...
  1599. testName := ".syncthing-test." + srand.String(16)
  1600. testDir := filepath.Join(home, testName)
  1601. if err := os.RemoveAll(testDir); err != nil {
  1602. t.Skip(err)
  1603. }
  1604. if err := osutil.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  1605. t.Skip(err)
  1606. }
  1607. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  1608. t.Skip(err)
  1609. }
  1610. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  1611. t.Skip(err)
  1612. }
  1613. defer os.RemoveAll(testDir)
  1614. db := db.OpenMemory()
  1615. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1616. m.AddFolder(config.NewFolderConfiguration("default", "~/"+testName+"/synclink/"))
  1617. m.StartFolder("default")
  1618. m.ServeBackground()
  1619. defer m.Stop()
  1620. if err := m.ScanFolder("default"); err != nil {
  1621. t.Error("scan error:", err)
  1622. }
  1623. if err := m.CheckFolderHealth("default"); err != nil {
  1624. t.Error("health check error:", err)
  1625. }
  1626. }
  1627. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1628. dbi := db.OpenMemory()
  1629. files := db.NewFileSet("default", dbi)
  1630. files.Replace(device1, genFiles(1))
  1631. files.Replace(device2, genFiles(1))
  1632. if len(files.ListDevices()) != 2 {
  1633. t.Error("expected two devices")
  1634. }
  1635. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1636. m.AddFolder(defaultFolderConfig)
  1637. m.StartFolder("default")
  1638. // Remote sequence is cached, hence need to recreated.
  1639. files = db.NewFileSet("default", dbi)
  1640. if len(files.ListDevices()) != 1 {
  1641. t.Error("Expected one device")
  1642. }
  1643. }
  1644. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1645. dbi := db.OpenMemory()
  1646. fcfg := config.NewFolderConfiguration("default", "testdata")
  1647. fcfg.Devices = []config.FolderDeviceConfiguration{
  1648. {DeviceID: device1},
  1649. {DeviceID: device2},
  1650. }
  1651. cfg := config.Configuration{
  1652. Folders: []config.FolderConfiguration{fcfg},
  1653. Devices: []config.DeviceConfiguration{
  1654. config.NewDeviceConfiguration(device1, "device1"),
  1655. config.NewDeviceConfiguration(device2, "device2"),
  1656. },
  1657. Options: config.OptionsConfiguration{
  1658. // Don't remove temporaries directly on startup
  1659. KeepTemporariesH: 1,
  1660. },
  1661. }
  1662. wcfg := config.Wrap("/tmp/test", cfg)
  1663. m := NewModel(wcfg, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1664. m.AddFolder(fcfg)
  1665. m.StartFolder(fcfg.ID)
  1666. m.ServeBackground()
  1667. conn1 := &fakeConnection{id: device1}
  1668. m.AddConnection(conn1, protocol.HelloResult{})
  1669. conn2 := &fakeConnection{id: device2}
  1670. m.AddConnection(conn2, protocol.HelloResult{})
  1671. m.ClusterConfig(device1, protocol.ClusterConfig{
  1672. Folders: []protocol.Folder{
  1673. {
  1674. ID: "default",
  1675. Devices: []protocol.Device{
  1676. {ID: device1},
  1677. {ID: device2},
  1678. },
  1679. },
  1680. },
  1681. })
  1682. m.ClusterConfig(device2, protocol.ClusterConfig{
  1683. Folders: []protocol.Folder{
  1684. {
  1685. ID: "default",
  1686. Devices: []protocol.Device{
  1687. {ID: device1},
  1688. {ID: device2},
  1689. },
  1690. },
  1691. },
  1692. })
  1693. if !m.folderSharedWith("default", device1) {
  1694. t.Error("not shared with device1")
  1695. }
  1696. if !m.folderSharedWith("default", device2) {
  1697. t.Error("not shared with device2")
  1698. }
  1699. if conn2.Closed() {
  1700. t.Error("conn already closed")
  1701. }
  1702. cfg = cfg.Copy()
  1703. cfg.Devices = cfg.Devices[:1]
  1704. if err := wcfg.Replace(cfg); err != nil {
  1705. t.Error(err)
  1706. }
  1707. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1708. if !m.folderSharedWith("default", device1) {
  1709. t.Error("not shared with device1")
  1710. }
  1711. if m.folderSharedWith("default", device2) { // checks m.deviceFolders
  1712. t.Error("shared with device2")
  1713. }
  1714. if !conn2.Closed() {
  1715. t.Error("connection not closed")
  1716. }
  1717. if _, ok := wcfg.Devices()[device2]; ok {
  1718. t.Error("device still in config")
  1719. }
  1720. fdevs, ok := m.folderDevices["default"]
  1721. if !ok {
  1722. t.Error("folder missing?")
  1723. }
  1724. for id := range fdevs {
  1725. if id == device2 {
  1726. t.Error("still there")
  1727. }
  1728. }
  1729. if _, ok := m.conn[device2]; !ok {
  1730. t.Error("conn missing early")
  1731. }
  1732. if _, ok := m.helloMessages[device2]; !ok {
  1733. t.Error("hello missing early")
  1734. }
  1735. if _, ok := m.deviceDownloads[device2]; !ok {
  1736. t.Error("downloads missing early")
  1737. }
  1738. m.Closed(conn2, fmt.Errorf("foo"))
  1739. if _, ok := m.conn[device2]; ok {
  1740. t.Error("conn not missing")
  1741. }
  1742. if _, ok := m.helloMessages[device2]; ok {
  1743. t.Error("hello not missing")
  1744. }
  1745. if _, ok := m.deviceDownloads[device2]; ok {
  1746. t.Error("downloads not missing")
  1747. }
  1748. }
  1749. func TestIssue3496(t *testing.T) {
  1750. // It seems like lots of deleted files can cause negative completion
  1751. // percentages. Lets make sure that doesn't happen. Also do some general
  1752. // checks on the completion calculation stuff.
  1753. dbi := db.OpenMemory()
  1754. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1755. m.AddFolder(defaultFolderConfig)
  1756. m.StartFolder("default")
  1757. m.ServeBackground()
  1758. defer m.Stop()
  1759. m.ScanFolder("default")
  1760. addFakeConn(m, device1)
  1761. addFakeConn(m, device2)
  1762. // Reach into the model and grab the current file list...
  1763. m.fmut.RLock()
  1764. fs := m.folderFiles["default"]
  1765. m.fmut.RUnlock()
  1766. var localFiles []protocol.FileInfo
  1767. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  1768. localFiles = append(localFiles, i.(protocol.FileInfo))
  1769. return true
  1770. })
  1771. // Mark all files as deleted and fake it as update from device1
  1772. for i := range localFiles {
  1773. localFiles[i].Deleted = true
  1774. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  1775. localFiles[i].Blocks = nil
  1776. }
  1777. // Also add a small file that we're supposed to need, or the global size
  1778. // stuff will bail out early due to the entire folder being zero size.
  1779. localFiles = append(localFiles, protocol.FileInfo{
  1780. Name: "fake",
  1781. Size: 1234,
  1782. Type: protocol.FileInfoTypeFile,
  1783. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  1784. })
  1785. m.IndexUpdate(device1, "default", localFiles)
  1786. // Check that the completion percentage for us makes sense
  1787. comp := m.Completion(protocol.LocalDeviceID, "default")
  1788. if comp.NeedBytes > comp.GlobalBytes {
  1789. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  1790. }
  1791. if comp.CompletionPct < 0 {
  1792. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  1793. }
  1794. if comp.NeedBytes == 0 {
  1795. t.Error("Need no bytes even though some files are deleted")
  1796. }
  1797. if comp.CompletionPct == 100 {
  1798. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  1799. }
  1800. t.Log(comp)
  1801. // Check that NeedSize does the correct thing
  1802. need := m.NeedSize("default")
  1803. if need.Files != 1 || need.Bytes != 1234 {
  1804. // The one we added synthetically above
  1805. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  1806. }
  1807. if need.Deleted != len(localFiles)-1 {
  1808. // The rest
  1809. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  1810. }
  1811. }
  1812. func addFakeConn(m *Model, dev protocol.DeviceID) *fakeConnection {
  1813. fc := &fakeConnection{id: dev, model: m}
  1814. m.AddConnection(fc, protocol.HelloResult{})
  1815. m.ClusterConfig(dev, protocol.ClusterConfig{
  1816. Folders: []protocol.Folder{
  1817. {
  1818. ID: "default",
  1819. Devices: []protocol.Device{
  1820. {ID: device1},
  1821. {ID: device2},
  1822. },
  1823. },
  1824. },
  1825. })
  1826. return fc
  1827. }
  1828. type fakeAddr struct{}
  1829. func (fakeAddr) Network() string {
  1830. return "network"
  1831. }
  1832. func (fakeAddr) String() string {
  1833. return "address"
  1834. }