model_test.go 32 KB

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