model_test.go 36 KB

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