model_test.go 38 KB

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