model_test.go 30 KB

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