model_test.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. "strconv"
  17. "testing"
  18. "time"
  19. "github.com/syncthing/syncthing/lib/config"
  20. "github.com/syncthing/syncthing/lib/db"
  21. "github.com/syncthing/syncthing/lib/protocol"
  22. )
  23. var device1, device2 protocol.DeviceID
  24. var defaultConfig *config.Wrapper
  25. var defaultFolderConfig config.FolderConfiguration
  26. func init() {
  27. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  28. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  29. defaultFolderConfig = config.NewFolderConfiguration("default", "testdata")
  30. defaultFolderConfig.Devices = []config.FolderDeviceConfiguration{{DeviceID: device1}}
  31. _defaultConfig := config.Configuration{
  32. Folders: []config.FolderConfiguration{defaultFolderConfig},
  33. Devices: []config.DeviceConfiguration{config.NewDeviceConfiguration(device1, "device1")},
  34. Options: config.OptionsConfiguration{
  35. // Don't remove temporaries directly on startup
  36. KeepTemporariesH: 1,
  37. },
  38. }
  39. defaultConfig = config.Wrap("/tmp/test", _defaultConfig)
  40. }
  41. var testDataExpected = map[string]protocol.FileInfo{
  42. "foo": {
  43. Name: "foo",
  44. Flags: 0,
  45. Modified: 0,
  46. 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}}},
  47. },
  48. "empty": {
  49. Name: "empty",
  50. Flags: 0,
  51. Modified: 0,
  52. 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}}},
  53. },
  54. "bar": {
  55. Name: "bar",
  56. Flags: 0,
  57. Modified: 0,
  58. 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}}},
  59. },
  60. }
  61. func init() {
  62. // Fix expected test data to match reality
  63. for n, f := range testDataExpected {
  64. fi, _ := os.Stat("testdata/" + n)
  65. f.Flags = uint32(fi.Mode())
  66. f.Modified = fi.ModTime().Unix()
  67. testDataExpected[n] = f
  68. }
  69. }
  70. func TestRequest(t *testing.T) {
  71. db := db.OpenMemory()
  72. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  73. // device1 shares default, but device2 doesn't
  74. m.AddFolder(defaultFolderConfig)
  75. m.StartFolderRO("default")
  76. m.ServeBackground()
  77. m.ScanFolder("default")
  78. bs := make([]byte, protocol.BlockSize)
  79. // Existing, shared file
  80. bs = bs[:6]
  81. err := m.Request(device1, "default", "foo", 0, nil, 0, nil, bs)
  82. if err != nil {
  83. t.Error(err)
  84. }
  85. if bytes.Compare(bs, []byte("foobar")) != 0 {
  86. t.Errorf("Incorrect data from request: %q", string(bs))
  87. }
  88. // Existing, nonshared file
  89. err = m.Request(device2, "default", "foo", 0, nil, 0, nil, bs)
  90. if err == nil {
  91. t.Error("Unexpected nil error on insecure file read")
  92. }
  93. // Nonexistent file
  94. err = m.Request(device1, "default", "nonexistent", 0, nil, 0, nil, bs)
  95. if err == nil {
  96. t.Error("Unexpected nil error on insecure file read")
  97. }
  98. // Shared folder, but disallowed file name
  99. err = m.Request(device1, "default", "../walk.go", 0, nil, 0, nil, bs)
  100. if err == nil {
  101. t.Error("Unexpected nil error on insecure file read")
  102. }
  103. // Negative offset
  104. err = m.Request(device1, "default", "foo", -4, nil, 0, nil, bs[:0])
  105. if err == nil {
  106. t.Error("Unexpected nil error on insecure file read")
  107. }
  108. // Larger block than available
  109. bs = bs[:42]
  110. err = m.Request(device1, "default", "foo", 0, nil, 0, nil, bs)
  111. if err == nil {
  112. t.Error("Unexpected nil error on insecure file read")
  113. }
  114. }
  115. func genFiles(n int) []protocol.FileInfo {
  116. files := make([]protocol.FileInfo, n)
  117. t := time.Now().Unix()
  118. for i := 0; i < n; i++ {
  119. files[i] = protocol.FileInfo{
  120. Name: fmt.Sprintf("file%d", i),
  121. Modified: t,
  122. Blocks: []protocol.BlockInfo{{0, 100, []byte("some hash bytes")}},
  123. }
  124. }
  125. return files
  126. }
  127. func BenchmarkIndex_10000(b *testing.B) {
  128. benchmarkIndex(b, 10000)
  129. }
  130. func BenchmarkIndex_100(b *testing.B) {
  131. benchmarkIndex(b, 100)
  132. }
  133. func benchmarkIndex(b *testing.B, nfiles int) {
  134. db := db.OpenMemory()
  135. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  136. m.AddFolder(defaultFolderConfig)
  137. m.StartFolderRO("default")
  138. m.ServeBackground()
  139. files := genFiles(nfiles)
  140. m.Index(device1, "default", files, 0, nil)
  141. b.ResetTimer()
  142. for i := 0; i < b.N; i++ {
  143. m.Index(device1, "default", files, 0, nil)
  144. }
  145. b.ReportAllocs()
  146. }
  147. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  148. benchmarkIndexUpdate(b, 10000, 10000)
  149. }
  150. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  151. benchmarkIndexUpdate(b, 10000, 100)
  152. }
  153. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  154. benchmarkIndexUpdate(b, 10000, 1)
  155. }
  156. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  157. db := db.OpenMemory()
  158. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  159. m.AddFolder(defaultFolderConfig)
  160. m.StartFolderRO("default")
  161. m.ServeBackground()
  162. files := genFiles(nfiles)
  163. ufiles := genFiles(nufiles)
  164. m.Index(device1, "default", files, 0, nil)
  165. b.ResetTimer()
  166. for i := 0; i < b.N; i++ {
  167. m.IndexUpdate(device1, "default", ufiles, 0, nil)
  168. }
  169. b.ReportAllocs()
  170. }
  171. type FakeConnection struct {
  172. id protocol.DeviceID
  173. requestData []byte
  174. }
  175. func (FakeConnection) Close() error {
  176. return nil
  177. }
  178. func (f FakeConnection) Start() {
  179. }
  180. func (f FakeConnection) ID() protocol.DeviceID {
  181. return f.id
  182. }
  183. func (f FakeConnection) Name() string {
  184. return ""
  185. }
  186. func (f FakeConnection) Option(string) string {
  187. return ""
  188. }
  189. func (FakeConnection) Index(string, []protocol.FileInfo, uint32, []protocol.Option) error {
  190. return nil
  191. }
  192. func (FakeConnection) IndexUpdate(string, []protocol.FileInfo, uint32, []protocol.Option) error {
  193. return nil
  194. }
  195. func (f FakeConnection) Request(folder, name string, offset int64, size int, hash []byte, flags uint32, options []protocol.Option) ([]byte, error) {
  196. return f.requestData, nil
  197. }
  198. func (FakeConnection) ClusterConfig(protocol.ClusterConfigMessage) {}
  199. func (FakeConnection) Ping() bool {
  200. return true
  201. }
  202. func (FakeConnection) Statistics() protocol.Statistics {
  203. return protocol.Statistics{}
  204. }
  205. func BenchmarkRequest(b *testing.B) {
  206. db := db.OpenMemory()
  207. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  208. m.AddFolder(defaultFolderConfig)
  209. m.ServeBackground()
  210. m.ScanFolder("default")
  211. const n = 1000
  212. files := make([]protocol.FileInfo, n)
  213. t := time.Now().Unix()
  214. for i := 0; i < n; i++ {
  215. files[i] = protocol.FileInfo{
  216. Name: fmt.Sprintf("file%d", i),
  217. Modified: t,
  218. Blocks: []protocol.BlockInfo{{0, 100, []byte("some hash bytes")}},
  219. }
  220. }
  221. fc := FakeConnection{
  222. id: device1,
  223. requestData: []byte("some data to return"),
  224. }
  225. m.AddConnection(Connection{
  226. &net.TCPConn{},
  227. fc,
  228. ConnectionTypeDirectAccept,
  229. })
  230. m.Index(device1, "default", files, 0, nil)
  231. b.ResetTimer()
  232. for i := 0; i < b.N; i++ {
  233. data, err := m.requestGlobal(device1, "default", files[i%n].Name, 0, 32, nil, 0, nil)
  234. if err != nil {
  235. b.Error(err)
  236. }
  237. if data == nil {
  238. b.Error("nil data")
  239. }
  240. }
  241. }
  242. func TestDeviceRename(t *testing.T) {
  243. ccm := protocol.ClusterConfigMessage{
  244. ClientName: "syncthing",
  245. ClientVersion: "v0.9.4",
  246. }
  247. defer os.Remove("tmpconfig.xml")
  248. rawCfg := config.New(device1)
  249. rawCfg.Devices = []config.DeviceConfiguration{
  250. {
  251. DeviceID: device1,
  252. },
  253. }
  254. cfg := config.Wrap("tmpconfig.xml", rawCfg)
  255. db := db.OpenMemory()
  256. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  257. fc := FakeConnection{
  258. id: device1,
  259. requestData: []byte("some data to return"),
  260. }
  261. m.AddConnection(Connection{
  262. &net.TCPConn{},
  263. fc,
  264. ConnectionTypeDirectAccept,
  265. })
  266. m.ServeBackground()
  267. if cfg.Devices()[device1].Name != "" {
  268. t.Errorf("Device already has a name")
  269. }
  270. m.ClusterConfig(device1, ccm)
  271. if cfg.Devices()[device1].Name != "" {
  272. t.Errorf("Device already has a name")
  273. }
  274. ccm.DeviceName = "tester"
  275. m.ClusterConfig(device1, ccm)
  276. if cfg.Devices()[device1].Name != "tester" {
  277. t.Errorf("Device did not get a name")
  278. }
  279. ccm.DeviceName = "tester2"
  280. m.ClusterConfig(device1, ccm)
  281. if cfg.Devices()[device1].Name != "tester" {
  282. t.Errorf("Device name got overwritten")
  283. }
  284. cfgw, err := config.Load("tmpconfig.xml", protocol.LocalDeviceID)
  285. if err != nil {
  286. t.Error(err)
  287. return
  288. }
  289. if cfgw.Devices()[device1].Name != "tester" {
  290. t.Errorf("Device name not saved in config")
  291. }
  292. }
  293. func TestClusterConfig(t *testing.T) {
  294. cfg := config.New(device1)
  295. cfg.Devices = []config.DeviceConfiguration{
  296. {
  297. DeviceID: device1,
  298. Introducer: true,
  299. },
  300. {
  301. DeviceID: device2,
  302. },
  303. }
  304. cfg.Folders = []config.FolderConfiguration{
  305. {
  306. ID: "folder1",
  307. Devices: []config.FolderDeviceConfiguration{
  308. {DeviceID: device1},
  309. {DeviceID: device2},
  310. },
  311. },
  312. {
  313. ID: "folder2",
  314. Devices: []config.FolderDeviceConfiguration{
  315. {DeviceID: device1},
  316. {DeviceID: device2},
  317. },
  318. },
  319. }
  320. db := db.OpenMemory()
  321. m := NewModel(config.Wrap("/tmp/test", cfg), protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  322. m.AddFolder(cfg.Folders[0])
  323. m.AddFolder(cfg.Folders[1])
  324. m.ServeBackground()
  325. cm := m.generateClusterConfig(device2)
  326. if l := len(cm.Folders); l != 2 {
  327. t.Fatalf("Incorrect number of folders %d != 2", l)
  328. }
  329. r := cm.Folders[0]
  330. if r.ID != "folder1" {
  331. t.Errorf("Incorrect folder %q != folder1", r.ID)
  332. }
  333. if l := len(r.Devices); l != 2 {
  334. t.Errorf("Incorrect number of devices %d != 2", l)
  335. }
  336. if id := r.Devices[0].ID; bytes.Compare(id, device1[:]) != 0 {
  337. t.Errorf("Incorrect device ID %x != %x", id, device1)
  338. }
  339. if r.Devices[0].Flags&protocol.FlagIntroducer == 0 {
  340. t.Error("Device1 should be flagged as Introducer")
  341. }
  342. if id := r.Devices[1].ID; bytes.Compare(id, device2[:]) != 0 {
  343. t.Errorf("Incorrect device ID %x != %x", id, device2)
  344. }
  345. if r.Devices[1].Flags&protocol.FlagIntroducer != 0 {
  346. t.Error("Device2 should not be flagged as Introducer")
  347. }
  348. r = cm.Folders[1]
  349. if r.ID != "folder2" {
  350. t.Errorf("Incorrect folder %q != folder2", r.ID)
  351. }
  352. if l := len(r.Devices); l != 2 {
  353. t.Errorf("Incorrect number of devices %d != 2", l)
  354. }
  355. if id := r.Devices[0].ID; bytes.Compare(id, device1[:]) != 0 {
  356. t.Errorf("Incorrect device ID %x != %x", id, device1)
  357. }
  358. if r.Devices[0].Flags&protocol.FlagIntroducer == 0 {
  359. t.Error("Device1 should be flagged as Introducer")
  360. }
  361. if id := r.Devices[1].ID; bytes.Compare(id, device2[:]) != 0 {
  362. t.Errorf("Incorrect device ID %x != %x", id, device2)
  363. }
  364. if r.Devices[1].Flags&protocol.FlagIntroducer != 0 {
  365. t.Error("Device2 should not be flagged as Introducer")
  366. }
  367. }
  368. func TestIgnores(t *testing.T) {
  369. arrEqual := func(a, b []string) bool {
  370. if len(a) != len(b) {
  371. return false
  372. }
  373. for i := range a {
  374. if a[i] != b[i] {
  375. return false
  376. }
  377. }
  378. return true
  379. }
  380. // Assure a clean start state
  381. ioutil.WriteFile("testdata/.stfolder", nil, 0644)
  382. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  383. db := db.OpenMemory()
  384. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  385. m.AddFolder(defaultFolderConfig)
  386. m.StartFolderRO("default")
  387. m.ServeBackground()
  388. expected := []string{
  389. ".*",
  390. "quux",
  391. }
  392. ignores, _, err := m.GetIgnores("default")
  393. if err != nil {
  394. t.Error(err)
  395. }
  396. if !arrEqual(ignores, expected) {
  397. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  398. }
  399. ignores = append(ignores, "pox")
  400. err = m.SetIgnores("default", ignores)
  401. if err != nil {
  402. t.Error(err)
  403. }
  404. ignores2, _, err := m.GetIgnores("default")
  405. if err != nil {
  406. t.Error(err)
  407. }
  408. if arrEqual(expected, ignores2) {
  409. t.Errorf("Incorrect ignores: %v == %v", ignores2, expected)
  410. }
  411. if !arrEqual(ignores, ignores2) {
  412. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  413. }
  414. err = m.SetIgnores("default", expected)
  415. if err != nil {
  416. t.Error(err)
  417. }
  418. ignores, _, err = m.GetIgnores("default")
  419. if err != nil {
  420. t.Error(err)
  421. }
  422. if !arrEqual(ignores, expected) {
  423. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  424. }
  425. ignores, _, err = m.GetIgnores("doesnotexist")
  426. if err == nil {
  427. t.Error("No error")
  428. }
  429. err = m.SetIgnores("doesnotexist", expected)
  430. if err == nil {
  431. t.Error("No error")
  432. }
  433. m.AddFolder(config.FolderConfiguration{ID: "fresh", RawPath: "XXX"})
  434. ignores, _, err = m.GetIgnores("fresh")
  435. if err != nil {
  436. t.Error(err)
  437. }
  438. if len(ignores) > 0 {
  439. t.Errorf("Expected no ignores, got: %v", ignores)
  440. }
  441. }
  442. func TestRefuseUnknownBits(t *testing.T) {
  443. db := db.OpenMemory()
  444. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  445. m.AddFolder(defaultFolderConfig)
  446. m.ServeBackground()
  447. m.ScanFolder("default")
  448. m.Index(device1, "default", []protocol.FileInfo{
  449. {
  450. Name: "invalid1",
  451. Flags: (protocol.FlagsAll + 1) &^ protocol.FlagInvalid,
  452. },
  453. {
  454. Name: "invalid2",
  455. Flags: (protocol.FlagsAll + 2) &^ protocol.FlagInvalid,
  456. },
  457. {
  458. Name: "invalid3",
  459. Flags: (1 << 31) &^ protocol.FlagInvalid,
  460. },
  461. {
  462. Name: "valid",
  463. Flags: protocol.FlagsAll &^ (protocol.FlagInvalid | protocol.FlagSymlink),
  464. },
  465. }, 0, nil)
  466. for _, name := range []string{"invalid1", "invalid2", "invalid3"} {
  467. f, ok := m.CurrentGlobalFile("default", name)
  468. if ok || f.Name == name {
  469. t.Error("Invalid file found or name match")
  470. }
  471. }
  472. f, ok := m.CurrentGlobalFile("default", "valid")
  473. if !ok || f.Name != "valid" {
  474. t.Error("Valid file not found or name mismatch", ok, f)
  475. }
  476. }
  477. func TestROScanRecovery(t *testing.T) {
  478. ldb := db.OpenMemory()
  479. set := db.NewFileSet("default", ldb)
  480. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  481. {Name: "dummyfile"},
  482. })
  483. fcfg := config.FolderConfiguration{
  484. ID: "default",
  485. RawPath: "testdata/rotestfolder",
  486. RescanIntervalS: 1,
  487. }
  488. cfg := config.Wrap("/tmp/test", config.Configuration{
  489. Folders: []config.FolderConfiguration{fcfg},
  490. Devices: []config.DeviceConfiguration{
  491. {
  492. DeviceID: device1,
  493. },
  494. },
  495. })
  496. os.RemoveAll(fcfg.RawPath)
  497. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  498. m.AddFolder(fcfg)
  499. m.StartFolderRO("default")
  500. m.ServeBackground()
  501. waitFor := func(status string) error {
  502. timeout := time.Now().Add(2 * time.Second)
  503. for {
  504. if time.Now().After(timeout) {
  505. return fmt.Errorf("Timed out waiting for status: %s, current status: %s", status, m.cfg.Folders()["default"].Invalid)
  506. }
  507. _, _, err := m.State("default")
  508. if err == nil && status == "" {
  509. return nil
  510. }
  511. if err != nil && err.Error() == status {
  512. return nil
  513. }
  514. time.Sleep(10 * time.Millisecond)
  515. }
  516. }
  517. if err := waitFor("folder path missing"); err != nil {
  518. t.Error(err)
  519. return
  520. }
  521. os.Mkdir(fcfg.RawPath, 0700)
  522. if err := waitFor("folder marker missing"); err != nil {
  523. t.Error(err)
  524. return
  525. }
  526. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  527. if err != nil {
  528. t.Error(err)
  529. return
  530. }
  531. fd.Close()
  532. if err := waitFor(""); err != nil {
  533. t.Error(err)
  534. return
  535. }
  536. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  537. if err := waitFor("folder marker missing"); err != nil {
  538. t.Error(err)
  539. return
  540. }
  541. os.Remove(fcfg.RawPath)
  542. if err := waitFor("folder path missing"); err != nil {
  543. t.Error(err)
  544. return
  545. }
  546. }
  547. func TestRWScanRecovery(t *testing.T) {
  548. ldb := db.OpenMemory()
  549. set := db.NewFileSet("default", ldb)
  550. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  551. {Name: "dummyfile"},
  552. })
  553. fcfg := config.FolderConfiguration{
  554. ID: "default",
  555. RawPath: "testdata/rwtestfolder",
  556. RescanIntervalS: 1,
  557. }
  558. cfg := config.Wrap("/tmp/test", config.Configuration{
  559. Folders: []config.FolderConfiguration{fcfg},
  560. Devices: []config.DeviceConfiguration{
  561. {
  562. DeviceID: device1,
  563. },
  564. },
  565. })
  566. os.RemoveAll(fcfg.RawPath)
  567. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  568. m.AddFolder(fcfg)
  569. m.StartFolderRW("default")
  570. m.ServeBackground()
  571. waitFor := func(status string) error {
  572. timeout := time.Now().Add(2 * time.Second)
  573. for {
  574. if time.Now().After(timeout) {
  575. return fmt.Errorf("Timed out waiting for status: %s, current status: %s", status, m.cfg.Folders()["default"].Invalid)
  576. }
  577. _, _, err := m.State("default")
  578. if err == nil && status == "" {
  579. return nil
  580. }
  581. if err != nil && err.Error() == status {
  582. return nil
  583. }
  584. time.Sleep(10 * time.Millisecond)
  585. }
  586. }
  587. if err := waitFor("folder path missing"); err != nil {
  588. t.Error(err)
  589. return
  590. }
  591. os.Mkdir(fcfg.RawPath, 0700)
  592. if err := waitFor("folder marker missing"); err != nil {
  593. t.Error(err)
  594. return
  595. }
  596. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  597. if err != nil {
  598. t.Error(err)
  599. return
  600. }
  601. fd.Close()
  602. if err := waitFor(""); err != nil {
  603. t.Error(err)
  604. return
  605. }
  606. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  607. if err := waitFor("folder marker missing"); err != nil {
  608. t.Error(err)
  609. return
  610. }
  611. os.Remove(fcfg.RawPath)
  612. if err := waitFor("folder path missing"); err != nil {
  613. t.Error(err)
  614. return
  615. }
  616. }
  617. func TestGlobalDirectoryTree(t *testing.T) {
  618. db := db.OpenMemory()
  619. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  620. m.AddFolder(defaultFolderConfig)
  621. m.ServeBackground()
  622. b := func(isfile bool, path ...string) protocol.FileInfo {
  623. flags := uint32(protocol.FlagDirectory)
  624. blocks := []protocol.BlockInfo{}
  625. if isfile {
  626. flags = 0
  627. 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}}}
  628. }
  629. return protocol.FileInfo{
  630. Name: filepath.Join(path...),
  631. Flags: flags,
  632. Modified: 0x666,
  633. Blocks: blocks,
  634. }
  635. }
  636. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  637. testdata := []protocol.FileInfo{
  638. b(false, "another"),
  639. b(false, "another", "directory"),
  640. b(true, "another", "directory", "afile"),
  641. b(false, "another", "directory", "with"),
  642. b(false, "another", "directory", "with", "a"),
  643. b(true, "another", "directory", "with", "a", "file"),
  644. b(true, "another", "directory", "with", "file"),
  645. b(true, "another", "file"),
  646. b(false, "other"),
  647. b(false, "other", "rand"),
  648. b(false, "other", "random"),
  649. b(false, "other", "random", "dir"),
  650. b(false, "other", "random", "dirx"),
  651. b(false, "other", "randomx"),
  652. b(false, "some"),
  653. b(false, "some", "directory"),
  654. b(false, "some", "directory", "with"),
  655. b(false, "some", "directory", "with", "a"),
  656. b(true, "some", "directory", "with", "a", "file"),
  657. b(true, "rootfile"),
  658. }
  659. expectedResult := map[string]interface{}{
  660. "another": map[string]interface{}{
  661. "directory": map[string]interface{}{
  662. "afile": filedata,
  663. "with": map[string]interface{}{
  664. "a": map[string]interface{}{
  665. "file": filedata,
  666. },
  667. "file": filedata,
  668. },
  669. },
  670. "file": filedata,
  671. },
  672. "other": map[string]interface{}{
  673. "rand": map[string]interface{}{},
  674. "random": map[string]interface{}{
  675. "dir": map[string]interface{}{},
  676. "dirx": map[string]interface{}{},
  677. },
  678. "randomx": map[string]interface{}{},
  679. },
  680. "some": map[string]interface{}{
  681. "directory": map[string]interface{}{
  682. "with": map[string]interface{}{
  683. "a": map[string]interface{}{
  684. "file": filedata,
  685. },
  686. },
  687. },
  688. },
  689. "rootfile": filedata,
  690. }
  691. mm := func(data interface{}) string {
  692. bytes, err := json.Marshal(data)
  693. if err != nil {
  694. panic(err)
  695. }
  696. return string(bytes)
  697. }
  698. m.Index(device1, "default", testdata, 0, nil)
  699. result := m.GlobalDirectoryTree("default", "", -1, false)
  700. if mm(result) != mm(expectedResult) {
  701. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  702. }
  703. result = m.GlobalDirectoryTree("default", "another", -1, false)
  704. if mm(result) != mm(expectedResult["another"]) {
  705. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  706. }
  707. result = m.GlobalDirectoryTree("default", "", 0, false)
  708. currentResult := map[string]interface{}{
  709. "another": map[string]interface{}{},
  710. "other": map[string]interface{}{},
  711. "some": map[string]interface{}{},
  712. "rootfile": filedata,
  713. }
  714. if mm(result) != mm(currentResult) {
  715. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  716. }
  717. result = m.GlobalDirectoryTree("default", "", 1, false)
  718. currentResult = map[string]interface{}{
  719. "another": map[string]interface{}{
  720. "directory": map[string]interface{}{},
  721. "file": filedata,
  722. },
  723. "other": map[string]interface{}{
  724. "rand": map[string]interface{}{},
  725. "random": map[string]interface{}{},
  726. "randomx": map[string]interface{}{},
  727. },
  728. "some": map[string]interface{}{
  729. "directory": map[string]interface{}{},
  730. },
  731. "rootfile": filedata,
  732. }
  733. if mm(result) != mm(currentResult) {
  734. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  735. }
  736. result = m.GlobalDirectoryTree("default", "", -1, true)
  737. currentResult = map[string]interface{}{
  738. "another": map[string]interface{}{
  739. "directory": map[string]interface{}{
  740. "with": map[string]interface{}{
  741. "a": map[string]interface{}{},
  742. },
  743. },
  744. },
  745. "other": map[string]interface{}{
  746. "rand": map[string]interface{}{},
  747. "random": map[string]interface{}{
  748. "dir": map[string]interface{}{},
  749. "dirx": map[string]interface{}{},
  750. },
  751. "randomx": map[string]interface{}{},
  752. },
  753. "some": map[string]interface{}{
  754. "directory": map[string]interface{}{
  755. "with": map[string]interface{}{
  756. "a": map[string]interface{}{},
  757. },
  758. },
  759. },
  760. }
  761. if mm(result) != mm(currentResult) {
  762. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  763. }
  764. result = m.GlobalDirectoryTree("default", "", 1, true)
  765. currentResult = map[string]interface{}{
  766. "another": map[string]interface{}{
  767. "directory": map[string]interface{}{},
  768. },
  769. "other": map[string]interface{}{
  770. "rand": map[string]interface{}{},
  771. "random": map[string]interface{}{},
  772. "randomx": map[string]interface{}{},
  773. },
  774. "some": map[string]interface{}{
  775. "directory": map[string]interface{}{},
  776. },
  777. }
  778. if mm(result) != mm(currentResult) {
  779. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  780. }
  781. result = m.GlobalDirectoryTree("default", "another", 0, false)
  782. currentResult = map[string]interface{}{
  783. "directory": map[string]interface{}{},
  784. "file": filedata,
  785. }
  786. if mm(result) != mm(currentResult) {
  787. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  788. }
  789. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  790. currentResult = map[string]interface{}{
  791. "with": map[string]interface{}{},
  792. }
  793. if mm(result) != mm(currentResult) {
  794. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  795. }
  796. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  797. currentResult = map[string]interface{}{
  798. "with": map[string]interface{}{
  799. "a": map[string]interface{}{},
  800. },
  801. }
  802. if mm(result) != mm(currentResult) {
  803. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  804. }
  805. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  806. currentResult = map[string]interface{}{
  807. "with": map[string]interface{}{
  808. "a": map[string]interface{}{
  809. "file": filedata,
  810. },
  811. },
  812. }
  813. if mm(result) != mm(currentResult) {
  814. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  815. }
  816. result = m.GlobalDirectoryTree("default", "another", -1, true)
  817. currentResult = map[string]interface{}{
  818. "directory": map[string]interface{}{
  819. "with": map[string]interface{}{
  820. "a": map[string]interface{}{},
  821. },
  822. },
  823. }
  824. if mm(result) != mm(currentResult) {
  825. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  826. }
  827. // No prefix matching!
  828. result = m.GlobalDirectoryTree("default", "som", -1, false)
  829. currentResult = map[string]interface{}{}
  830. if mm(result) != mm(currentResult) {
  831. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  832. }
  833. }
  834. func TestGlobalDirectorySelfFixing(t *testing.T) {
  835. db := db.OpenMemory()
  836. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  837. m.AddFolder(defaultFolderConfig)
  838. m.ServeBackground()
  839. b := func(isfile bool, path ...string) protocol.FileInfo {
  840. flags := uint32(protocol.FlagDirectory)
  841. blocks := []protocol.BlockInfo{}
  842. if isfile {
  843. flags = 0
  844. 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}}}
  845. }
  846. return protocol.FileInfo{
  847. Name: filepath.Join(path...),
  848. Flags: flags,
  849. Modified: 0x666,
  850. Blocks: blocks,
  851. }
  852. }
  853. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  854. testdata := []protocol.FileInfo{
  855. b(true, "another", "directory", "afile"),
  856. b(true, "another", "directory", "with", "a", "file"),
  857. b(true, "another", "directory", "with", "file"),
  858. b(false, "other", "random", "dirx"),
  859. b(false, "other", "randomx"),
  860. b(false, "some", "directory", "with", "x"),
  861. b(true, "some", "directory", "with", "a", "file"),
  862. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  863. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  864. }
  865. expectedResult := map[string]interface{}{
  866. "another": map[string]interface{}{
  867. "directory": map[string]interface{}{
  868. "afile": filedata,
  869. "with": map[string]interface{}{
  870. "a": map[string]interface{}{
  871. "file": filedata,
  872. },
  873. "file": filedata,
  874. },
  875. },
  876. },
  877. "other": map[string]interface{}{
  878. "random": map[string]interface{}{
  879. "dirx": map[string]interface{}{},
  880. },
  881. "randomx": map[string]interface{}{},
  882. },
  883. "some": map[string]interface{}{
  884. "directory": map[string]interface{}{
  885. "with": map[string]interface{}{
  886. "a": map[string]interface{}{
  887. "file": filedata,
  888. },
  889. "x": map[string]interface{}{},
  890. },
  891. },
  892. },
  893. "this": map[string]interface{}{
  894. "is": map[string]interface{}{
  895. "a": map[string]interface{}{
  896. "deep": map[string]interface{}{
  897. "invalid": map[string]interface{}{
  898. "directory": map[string]interface{}{},
  899. },
  900. },
  901. },
  902. },
  903. },
  904. "xthis": map[string]interface{}{
  905. "is": map[string]interface{}{
  906. "a": map[string]interface{}{
  907. "deep": map[string]interface{}{
  908. "invalid": map[string]interface{}{
  909. "file": filedata,
  910. },
  911. },
  912. },
  913. },
  914. },
  915. }
  916. mm := func(data interface{}) string {
  917. bytes, err := json.Marshal(data)
  918. if err != nil {
  919. panic(err)
  920. }
  921. return string(bytes)
  922. }
  923. m.Index(device1, "default", testdata, 0, nil)
  924. result := m.GlobalDirectoryTree("default", "", -1, false)
  925. if mm(result) != mm(expectedResult) {
  926. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  927. }
  928. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  929. currentResult := map[string]interface{}{
  930. "invalid": map[string]interface{}{
  931. "file": filedata,
  932. },
  933. }
  934. if mm(result) != mm(currentResult) {
  935. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  936. }
  937. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  938. currentResult = map[string]interface{}{
  939. "invalid": map[string]interface{}{},
  940. }
  941. if mm(result) != mm(currentResult) {
  942. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  943. }
  944. // !!! This is actually BAD, because we don't have enough level allowance
  945. // to accept this file, hence the tree is left unbuilt !!!
  946. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  947. currentResult = map[string]interface{}{}
  948. if mm(result) != mm(currentResult) {
  949. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  950. }
  951. }
  952. func genDeepFiles(n, d int) []protocol.FileInfo {
  953. rand.Seed(int64(n))
  954. files := make([]protocol.FileInfo, n)
  955. t := time.Now().Unix()
  956. for i := 0; i < n; i++ {
  957. path := ""
  958. for i := 0; i <= d; i++ {
  959. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  960. }
  961. sofar := ""
  962. for _, path := range filepath.SplitList(path) {
  963. sofar = filepath.Join(sofar, path)
  964. files[i] = protocol.FileInfo{
  965. Name: sofar,
  966. }
  967. i++
  968. }
  969. files[i].Modified = t
  970. files[i].Blocks = []protocol.BlockInfo{{0, 100, []byte("some hash bytes")}}
  971. }
  972. return files
  973. }
  974. func BenchmarkTree_10000_50(b *testing.B) {
  975. benchmarkTree(b, 10000, 50)
  976. }
  977. func BenchmarkTree_100_50(b *testing.B) {
  978. benchmarkTree(b, 100, 50)
  979. }
  980. func BenchmarkTree_100_10(b *testing.B) {
  981. benchmarkTree(b, 100, 10)
  982. }
  983. func benchmarkTree(b *testing.B, n1, n2 int) {
  984. db := db.OpenMemory()
  985. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  986. m.AddFolder(defaultFolderConfig)
  987. m.ServeBackground()
  988. m.ScanFolder("default")
  989. files := genDeepFiles(n1, n2)
  990. m.Index(device1, "default", files, 0, nil)
  991. b.ResetTimer()
  992. for i := 0; i < b.N; i++ {
  993. m.GlobalDirectoryTree("default", "", -1, false)
  994. }
  995. b.ReportAllocs()
  996. }
  997. func TestIgnoreDelete(t *testing.T) {
  998. db := db.OpenMemory()
  999. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1000. // This folder should ignore external deletes
  1001. cfg := defaultFolderConfig
  1002. cfg.IgnoreDelete = true
  1003. m.AddFolder(cfg)
  1004. m.ServeBackground()
  1005. m.StartFolderRW("default")
  1006. m.ScanFolder("default")
  1007. // Get a currently existing file
  1008. f, ok := m.CurrentGlobalFile("default", "foo")
  1009. if !ok {
  1010. t.Fatal("foo should exist")
  1011. }
  1012. // Mark it for deletion
  1013. f.Flags = protocol.FlagDeleted
  1014. f.Version = f.Version.Update(142) // arbitrary short remote ID
  1015. f.Blocks = nil
  1016. // Send the index
  1017. m.Index(device1, "default", []protocol.FileInfo{f}, 0, nil)
  1018. // Make sure we ignored it
  1019. f, ok = m.CurrentGlobalFile("default", "foo")
  1020. if !ok {
  1021. t.Fatal("foo should exist")
  1022. }
  1023. if f.IsDeleted() {
  1024. t.Fatal("foo should not be marked for deletion")
  1025. }
  1026. }