model_test.go 53 KB

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