model_test.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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. srand "github.com/syncthing/syncthing/lib/rand"
  29. )
  30. var device1, device2 protocol.DeviceID
  31. var defaultConfig *config.Wrapper
  32. var defaultFolderConfig config.FolderConfiguration
  33. func init() {
  34. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  35. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  36. defaultFolderConfig = config.NewFolderConfiguration("default", "testdata")
  37. defaultFolderConfig.Devices = []config.FolderDeviceConfiguration{{DeviceID: device1}}
  38. _defaultConfig := config.Configuration{
  39. Folders: []config.FolderConfiguration{defaultFolderConfig},
  40. Devices: []config.DeviceConfiguration{config.NewDeviceConfiguration(device1, "device1")},
  41. Options: config.OptionsConfiguration{
  42. // Don't remove temporaries directly on startup
  43. KeepTemporariesH: 1,
  44. },
  45. }
  46. defaultConfig = config.Wrap("/tmp/test", _defaultConfig)
  47. }
  48. var testDataExpected = map[string]protocol.FileInfo{
  49. "foo": {
  50. Name: "foo",
  51. Type: protocol.FileInfoTypeFile,
  52. Modified: 0,
  53. 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}}},
  54. },
  55. "empty": {
  56. Name: "empty",
  57. Type: protocol.FileInfoTypeFile,
  58. Modified: 0,
  59. 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}}},
  60. },
  61. "bar": {
  62. Name: "bar",
  63. Type: protocol.FileInfoTypeFile,
  64. Modified: 0,
  65. 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}}},
  66. },
  67. }
  68. func init() {
  69. // Fix expected test data to match reality
  70. for n, f := range testDataExpected {
  71. fi, _ := os.Stat("testdata/" + n)
  72. f.Permissions = uint32(fi.Mode())
  73. f.Modified = fi.ModTime().Unix()
  74. f.Size = fi.Size()
  75. testDataExpected[n] = f
  76. }
  77. }
  78. func TestRequest(t *testing.T) {
  79. db := db.OpenMemory()
  80. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  81. // device1 shares default, but device2 doesn't
  82. m.AddFolder(defaultFolderConfig)
  83. m.StartFolder("default")
  84. m.ServeBackground()
  85. m.ScanFolder("default")
  86. bs := make([]byte, protocol.BlockSize)
  87. // Existing, shared file
  88. bs = bs[:6]
  89. err := m.Request(device1, "default", "foo", 0, nil, false, bs)
  90. if err != nil {
  91. t.Error(err)
  92. }
  93. if !bytes.Equal(bs, []byte("foobar")) {
  94. t.Errorf("Incorrect data from request: %q", string(bs))
  95. }
  96. // Existing, nonshared file
  97. err = m.Request(device2, "default", "foo", 0, nil, false, bs)
  98. if err == nil {
  99. t.Error("Unexpected nil error on insecure file read")
  100. }
  101. // Nonexistent file
  102. err = m.Request(device1, "default", "nonexistent", 0, nil, false, bs)
  103. if err == nil {
  104. t.Error("Unexpected nil error on insecure file read")
  105. }
  106. // Shared folder, but disallowed file name
  107. err = m.Request(device1, "default", "../walk.go", 0, nil, false, bs)
  108. if err == nil {
  109. t.Error("Unexpected nil error on insecure file read")
  110. }
  111. // Negative offset
  112. err = m.Request(device1, "default", "foo", -4, nil, false, bs[:0])
  113. if err == nil {
  114. t.Error("Unexpected nil error on insecure file read")
  115. }
  116. // Larger block than available
  117. bs = bs[:42]
  118. err = m.Request(device1, "default", "foo", 0, nil, false, bs)
  119. if err == nil {
  120. t.Error("Unexpected nil error on insecure file read")
  121. }
  122. }
  123. func genFiles(n int) []protocol.FileInfo {
  124. files := make([]protocol.FileInfo, n)
  125. t := time.Now().Unix()
  126. for i := 0; i < n; i++ {
  127. files[i] = protocol.FileInfo{
  128. Name: fmt.Sprintf("file%d", i),
  129. Modified: t,
  130. Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
  131. }
  132. }
  133. return files
  134. }
  135. func BenchmarkIndex_10000(b *testing.B) {
  136. benchmarkIndex(b, 10000)
  137. }
  138. func BenchmarkIndex_100(b *testing.B) {
  139. benchmarkIndex(b, 100)
  140. }
  141. func benchmarkIndex(b *testing.B, nfiles int) {
  142. db := db.OpenMemory()
  143. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  144. m.AddFolder(defaultFolderConfig)
  145. m.StartFolder("default")
  146. m.ServeBackground()
  147. files := genFiles(nfiles)
  148. m.Index(device1, "default", files)
  149. b.ResetTimer()
  150. for i := 0; i < b.N; i++ {
  151. m.Index(device1, "default", files)
  152. }
  153. b.ReportAllocs()
  154. }
  155. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  156. benchmarkIndexUpdate(b, 10000, 10000)
  157. }
  158. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  159. benchmarkIndexUpdate(b, 10000, 100)
  160. }
  161. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  162. benchmarkIndexUpdate(b, 10000, 1)
  163. }
  164. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  165. db := db.OpenMemory()
  166. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  167. m.AddFolder(defaultFolderConfig)
  168. m.StartFolder("default")
  169. m.ServeBackground()
  170. files := genFiles(nfiles)
  171. ufiles := genFiles(nufiles)
  172. m.Index(device1, "default", files)
  173. b.ResetTimer()
  174. for i := 0; i < b.N; i++ {
  175. m.IndexUpdate(device1, "default", ufiles)
  176. }
  177. b.ReportAllocs()
  178. }
  179. type downloadProgressMessage struct {
  180. folder string
  181. updates []protocol.FileDownloadProgressUpdate
  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) error {
  203. return nil
  204. }
  205. func (FakeConnection) IndexUpdate(string, []protocol.FileInfo) 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.ClusterConfig) {}
  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) {
  222. f.downloadProgressMessages = append(f.downloadProgressMessages, downloadProgressMessage{
  223. folder: folder,
  224. updates: updates,
  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{{Offset: 0, Size: 100, Hash: []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.HelloResult{})
  255. m.Index(device1, "default", files)
  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.HelloResult{
  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.OverwriteRemoteDevNames = 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].Introducer {
  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].Introducer {
  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].Introducer {
  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].Introducer {
  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. _, _, err = m.GetIgnores("fresh")
  474. if err == nil {
  475. t.Error("No error")
  476. }
  477. }
  478. func TestROScanRecovery(t *testing.T) {
  479. ldb := db.OpenMemory()
  480. set := db.NewFileSet("default", ldb)
  481. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  482. {Name: "dummyfile"},
  483. })
  484. fcfg := config.FolderConfiguration{
  485. ID: "default",
  486. RawPath: "testdata/rotestfolder",
  487. Type: config.FolderTypeReadOnly,
  488. RescanIntervalS: 1,
  489. }
  490. cfg := config.Wrap("/tmp/test", config.Configuration{
  491. Folders: []config.FolderConfiguration{fcfg},
  492. Devices: []config.DeviceConfiguration{
  493. {
  494. DeviceID: device1,
  495. },
  496. },
  497. })
  498. os.RemoveAll(fcfg.RawPath)
  499. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  500. m.AddFolder(fcfg)
  501. m.StartFolder("default")
  502. m.ServeBackground()
  503. waitFor := func(status string) error {
  504. timeout := time.Now().Add(2 * time.Second)
  505. for {
  506. _, _, err := m.State("default")
  507. if err == nil && status == "" {
  508. return nil
  509. }
  510. if err != nil && err.Error() == status {
  511. return nil
  512. }
  513. if time.Now().After(timeout) {
  514. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  515. }
  516. time.Sleep(10 * time.Millisecond)
  517. }
  518. }
  519. if err := waitFor("folder path missing"); err != nil {
  520. t.Error(err)
  521. return
  522. }
  523. os.Mkdir(fcfg.RawPath, 0700)
  524. if err := waitFor("folder marker missing"); err != nil {
  525. t.Error(err)
  526. return
  527. }
  528. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  529. if err != nil {
  530. t.Error(err)
  531. return
  532. }
  533. fd.Close()
  534. if err := waitFor(""); err != nil {
  535. t.Error(err)
  536. return
  537. }
  538. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  539. if err := waitFor("folder marker missing"); err != nil {
  540. t.Error(err)
  541. return
  542. }
  543. os.Remove(fcfg.RawPath)
  544. if err := waitFor("folder path missing"); err != nil {
  545. t.Error(err)
  546. return
  547. }
  548. }
  549. func TestRWScanRecovery(t *testing.T) {
  550. ldb := db.OpenMemory()
  551. set := db.NewFileSet("default", ldb)
  552. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  553. {Name: "dummyfile"},
  554. })
  555. fcfg := config.FolderConfiguration{
  556. ID: "default",
  557. RawPath: "testdata/rwtestfolder",
  558. Type: config.FolderTypeReadWrite,
  559. RescanIntervalS: 1,
  560. }
  561. cfg := config.Wrap("/tmp/test", config.Configuration{
  562. Folders: []config.FolderConfiguration{fcfg},
  563. Devices: []config.DeviceConfiguration{
  564. {
  565. DeviceID: device1,
  566. },
  567. },
  568. })
  569. os.RemoveAll(fcfg.RawPath)
  570. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  571. m.AddFolder(fcfg)
  572. m.StartFolder("default")
  573. m.ServeBackground()
  574. waitFor := func(status string) error {
  575. timeout := time.Now().Add(2 * time.Second)
  576. for {
  577. _, _, err := m.State("default")
  578. if err == nil && status == "" {
  579. return nil
  580. }
  581. if err != nil && err.Error() == status {
  582. return nil
  583. }
  584. if time.Now().After(timeout) {
  585. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  586. }
  587. time.Sleep(10 * time.Millisecond)
  588. }
  589. }
  590. if err := waitFor("folder path missing"); err != nil {
  591. t.Error(err)
  592. return
  593. }
  594. os.Mkdir(fcfg.RawPath, 0700)
  595. if err := waitFor("folder marker missing"); err != nil {
  596. t.Error(err)
  597. return
  598. }
  599. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  600. if err != nil {
  601. t.Error(err)
  602. return
  603. }
  604. fd.Close()
  605. if err := waitFor(""); err != nil {
  606. t.Error(err)
  607. return
  608. }
  609. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  610. if err := waitFor("folder marker missing"); err != nil {
  611. t.Error(err)
  612. return
  613. }
  614. os.Remove(fcfg.RawPath)
  615. if err := waitFor("folder path missing"); err != nil {
  616. t.Error(err)
  617. return
  618. }
  619. }
  620. func TestGlobalDirectoryTree(t *testing.T) {
  621. db := db.OpenMemory()
  622. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  623. m.AddFolder(defaultFolderConfig)
  624. m.ServeBackground()
  625. b := func(isfile bool, path ...string) protocol.FileInfo {
  626. typ := protocol.FileInfoTypeDirectory
  627. blocks := []protocol.BlockInfo{}
  628. if isfile {
  629. typ = protocol.FileInfoTypeFile
  630. 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}}}
  631. }
  632. return protocol.FileInfo{
  633. Name: filepath.Join(path...),
  634. Type: typ,
  635. Modified: 0x666,
  636. Blocks: blocks,
  637. Size: 0xa,
  638. }
  639. }
  640. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  641. testdata := []protocol.FileInfo{
  642. b(false, "another"),
  643. b(false, "another", "directory"),
  644. b(true, "another", "directory", "afile"),
  645. b(false, "another", "directory", "with"),
  646. b(false, "another", "directory", "with", "a"),
  647. b(true, "another", "directory", "with", "a", "file"),
  648. b(true, "another", "directory", "with", "file"),
  649. b(true, "another", "file"),
  650. b(false, "other"),
  651. b(false, "other", "rand"),
  652. b(false, "other", "random"),
  653. b(false, "other", "random", "dir"),
  654. b(false, "other", "random", "dirx"),
  655. b(false, "other", "randomx"),
  656. b(false, "some"),
  657. b(false, "some", "directory"),
  658. b(false, "some", "directory", "with"),
  659. b(false, "some", "directory", "with", "a"),
  660. b(true, "some", "directory", "with", "a", "file"),
  661. b(true, "rootfile"),
  662. }
  663. expectedResult := map[string]interface{}{
  664. "another": map[string]interface{}{
  665. "directory": map[string]interface{}{
  666. "afile": filedata,
  667. "with": map[string]interface{}{
  668. "a": map[string]interface{}{
  669. "file": filedata,
  670. },
  671. "file": filedata,
  672. },
  673. },
  674. "file": filedata,
  675. },
  676. "other": map[string]interface{}{
  677. "rand": map[string]interface{}{},
  678. "random": map[string]interface{}{
  679. "dir": map[string]interface{}{},
  680. "dirx": map[string]interface{}{},
  681. },
  682. "randomx": map[string]interface{}{},
  683. },
  684. "some": map[string]interface{}{
  685. "directory": map[string]interface{}{
  686. "with": map[string]interface{}{
  687. "a": map[string]interface{}{
  688. "file": filedata,
  689. },
  690. },
  691. },
  692. },
  693. "rootfile": filedata,
  694. }
  695. mm := func(data interface{}) string {
  696. bytes, err := json.Marshal(data)
  697. if err != nil {
  698. panic(err)
  699. }
  700. return string(bytes)
  701. }
  702. m.Index(device1, "default", testdata)
  703. result := m.GlobalDirectoryTree("default", "", -1, false)
  704. if mm(result) != mm(expectedResult) {
  705. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  706. }
  707. result = m.GlobalDirectoryTree("default", "another", -1, false)
  708. if mm(result) != mm(expectedResult["another"]) {
  709. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  710. }
  711. result = m.GlobalDirectoryTree("default", "", 0, false)
  712. currentResult := map[string]interface{}{
  713. "another": map[string]interface{}{},
  714. "other": map[string]interface{}{},
  715. "some": map[string]interface{}{},
  716. "rootfile": filedata,
  717. }
  718. if mm(result) != mm(currentResult) {
  719. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  720. }
  721. result = m.GlobalDirectoryTree("default", "", 1, false)
  722. currentResult = map[string]interface{}{
  723. "another": map[string]interface{}{
  724. "directory": map[string]interface{}{},
  725. "file": filedata,
  726. },
  727. "other": map[string]interface{}{
  728. "rand": map[string]interface{}{},
  729. "random": map[string]interface{}{},
  730. "randomx": map[string]interface{}{},
  731. },
  732. "some": map[string]interface{}{
  733. "directory": map[string]interface{}{},
  734. },
  735. "rootfile": filedata,
  736. }
  737. if mm(result) != mm(currentResult) {
  738. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  739. }
  740. result = m.GlobalDirectoryTree("default", "", -1, true)
  741. currentResult = map[string]interface{}{
  742. "another": map[string]interface{}{
  743. "directory": map[string]interface{}{
  744. "with": map[string]interface{}{
  745. "a": map[string]interface{}{},
  746. },
  747. },
  748. },
  749. "other": map[string]interface{}{
  750. "rand": map[string]interface{}{},
  751. "random": map[string]interface{}{
  752. "dir": map[string]interface{}{},
  753. "dirx": map[string]interface{}{},
  754. },
  755. "randomx": map[string]interface{}{},
  756. },
  757. "some": map[string]interface{}{
  758. "directory": map[string]interface{}{
  759. "with": map[string]interface{}{
  760. "a": map[string]interface{}{},
  761. },
  762. },
  763. },
  764. }
  765. if mm(result) != mm(currentResult) {
  766. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  767. }
  768. result = m.GlobalDirectoryTree("default", "", 1, true)
  769. currentResult = map[string]interface{}{
  770. "another": map[string]interface{}{
  771. "directory": map[string]interface{}{},
  772. },
  773. "other": map[string]interface{}{
  774. "rand": map[string]interface{}{},
  775. "random": map[string]interface{}{},
  776. "randomx": map[string]interface{}{},
  777. },
  778. "some": map[string]interface{}{
  779. "directory": map[string]interface{}{},
  780. },
  781. }
  782. if mm(result) != mm(currentResult) {
  783. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  784. }
  785. result = m.GlobalDirectoryTree("default", "another", 0, false)
  786. currentResult = map[string]interface{}{
  787. "directory": map[string]interface{}{},
  788. "file": filedata,
  789. }
  790. if mm(result) != mm(currentResult) {
  791. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  792. }
  793. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  794. currentResult = map[string]interface{}{
  795. "with": map[string]interface{}{},
  796. }
  797. if mm(result) != mm(currentResult) {
  798. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  799. }
  800. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  801. currentResult = map[string]interface{}{
  802. "with": map[string]interface{}{
  803. "a": map[string]interface{}{},
  804. },
  805. }
  806. if mm(result) != mm(currentResult) {
  807. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  808. }
  809. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  810. currentResult = map[string]interface{}{
  811. "with": map[string]interface{}{
  812. "a": map[string]interface{}{
  813. "file": filedata,
  814. },
  815. },
  816. }
  817. if mm(result) != mm(currentResult) {
  818. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  819. }
  820. result = m.GlobalDirectoryTree("default", "another", -1, true)
  821. currentResult = map[string]interface{}{
  822. "directory": map[string]interface{}{
  823. "with": map[string]interface{}{
  824. "a": map[string]interface{}{},
  825. },
  826. },
  827. }
  828. if mm(result) != mm(currentResult) {
  829. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  830. }
  831. // No prefix matching!
  832. result = m.GlobalDirectoryTree("default", "som", -1, false)
  833. currentResult = map[string]interface{}{}
  834. if mm(result) != mm(currentResult) {
  835. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  836. }
  837. }
  838. func TestGlobalDirectorySelfFixing(t *testing.T) {
  839. db := db.OpenMemory()
  840. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  841. m.AddFolder(defaultFolderConfig)
  842. m.ServeBackground()
  843. b := func(isfile bool, path ...string) protocol.FileInfo {
  844. typ := protocol.FileInfoTypeDirectory
  845. blocks := []protocol.BlockInfo{}
  846. if isfile {
  847. typ = protocol.FileInfoTypeFile
  848. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  849. }
  850. return protocol.FileInfo{
  851. Name: filepath.Join(path...),
  852. Type: typ,
  853. Modified: 0x666,
  854. Blocks: blocks,
  855. Size: 0xa,
  856. }
  857. }
  858. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  859. testdata := []protocol.FileInfo{
  860. b(true, "another", "directory", "afile"),
  861. b(true, "another", "directory", "with", "a", "file"),
  862. b(true, "another", "directory", "with", "file"),
  863. b(false, "other", "random", "dirx"),
  864. b(false, "other", "randomx"),
  865. b(false, "some", "directory", "with", "x"),
  866. b(true, "some", "directory", "with", "a", "file"),
  867. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  868. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  869. }
  870. expectedResult := map[string]interface{}{
  871. "another": map[string]interface{}{
  872. "directory": map[string]interface{}{
  873. "afile": filedata,
  874. "with": map[string]interface{}{
  875. "a": map[string]interface{}{
  876. "file": filedata,
  877. },
  878. "file": filedata,
  879. },
  880. },
  881. },
  882. "other": map[string]interface{}{
  883. "random": map[string]interface{}{
  884. "dirx": map[string]interface{}{},
  885. },
  886. "randomx": map[string]interface{}{},
  887. },
  888. "some": map[string]interface{}{
  889. "directory": map[string]interface{}{
  890. "with": map[string]interface{}{
  891. "a": map[string]interface{}{
  892. "file": filedata,
  893. },
  894. "x": map[string]interface{}{},
  895. },
  896. },
  897. },
  898. "this": map[string]interface{}{
  899. "is": map[string]interface{}{
  900. "a": map[string]interface{}{
  901. "deep": map[string]interface{}{
  902. "invalid": map[string]interface{}{
  903. "directory": map[string]interface{}{},
  904. },
  905. },
  906. },
  907. },
  908. },
  909. "xthis": map[string]interface{}{
  910. "is": map[string]interface{}{
  911. "a": map[string]interface{}{
  912. "deep": map[string]interface{}{
  913. "invalid": map[string]interface{}{
  914. "file": filedata,
  915. },
  916. },
  917. },
  918. },
  919. },
  920. }
  921. mm := func(data interface{}) string {
  922. bytes, err := json.Marshal(data)
  923. if err != nil {
  924. panic(err)
  925. }
  926. return string(bytes)
  927. }
  928. m.Index(device1, "default", testdata)
  929. result := m.GlobalDirectoryTree("default", "", -1, false)
  930. if mm(result) != mm(expectedResult) {
  931. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  932. }
  933. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  934. currentResult := map[string]interface{}{
  935. "invalid": map[string]interface{}{
  936. "file": filedata,
  937. },
  938. }
  939. if mm(result) != mm(currentResult) {
  940. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  941. }
  942. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  943. currentResult = map[string]interface{}{
  944. "invalid": map[string]interface{}{},
  945. }
  946. if mm(result) != mm(currentResult) {
  947. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  948. }
  949. // !!! This is actually BAD, because we don't have enough level allowance
  950. // to accept this file, hence the tree is left unbuilt !!!
  951. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  952. currentResult = map[string]interface{}{}
  953. if mm(result) != mm(currentResult) {
  954. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  955. }
  956. }
  957. func genDeepFiles(n, d int) []protocol.FileInfo {
  958. rand.Seed(int64(n))
  959. files := make([]protocol.FileInfo, n)
  960. t := time.Now().Unix()
  961. for i := 0; i < n; i++ {
  962. path := ""
  963. for i := 0; i <= d; i++ {
  964. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  965. }
  966. sofar := ""
  967. for _, path := range filepath.SplitList(path) {
  968. sofar = filepath.Join(sofar, path)
  969. files[i] = protocol.FileInfo{
  970. Name: sofar,
  971. }
  972. i++
  973. }
  974. files[i].Modified = t
  975. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  976. }
  977. return files
  978. }
  979. func BenchmarkTree_10000_50(b *testing.B) {
  980. benchmarkTree(b, 10000, 50)
  981. }
  982. func BenchmarkTree_100_50(b *testing.B) {
  983. benchmarkTree(b, 100, 50)
  984. }
  985. func BenchmarkTree_100_10(b *testing.B) {
  986. benchmarkTree(b, 100, 10)
  987. }
  988. func benchmarkTree(b *testing.B, n1, n2 int) {
  989. db := db.OpenMemory()
  990. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  991. m.AddFolder(defaultFolderConfig)
  992. m.ServeBackground()
  993. m.ScanFolder("default")
  994. files := genDeepFiles(n1, n2)
  995. m.Index(device1, "default", files)
  996. b.ResetTimer()
  997. for i := 0; i < b.N; i++ {
  998. m.GlobalDirectoryTree("default", "", -1, false)
  999. }
  1000. b.ReportAllocs()
  1001. }
  1002. func TestIgnoreDelete(t *testing.T) {
  1003. db := db.OpenMemory()
  1004. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1005. // This folder should ignore external deletes
  1006. cfg := defaultFolderConfig
  1007. cfg.IgnoreDelete = true
  1008. m.AddFolder(cfg)
  1009. m.ServeBackground()
  1010. m.StartFolder("default")
  1011. m.ScanFolder("default")
  1012. // Get a currently existing file
  1013. f, ok := m.CurrentGlobalFile("default", "foo")
  1014. if !ok {
  1015. t.Fatal("foo should exist")
  1016. }
  1017. // Mark it for deletion
  1018. f.Deleted = true
  1019. f.Version = f.Version.Update(142) // arbitrary short remote ID
  1020. f.Blocks = nil
  1021. // Send the index
  1022. m.Index(device1, "default", []protocol.FileInfo{f})
  1023. // Make sure we ignored it
  1024. f, ok = m.CurrentGlobalFile("default", "foo")
  1025. if !ok {
  1026. t.Fatal("foo should exist")
  1027. }
  1028. if f.IsDeleted() {
  1029. t.Fatal("foo should not be marked for deletion")
  1030. }
  1031. }
  1032. func TestUnifySubs(t *testing.T) {
  1033. cases := []struct {
  1034. in []string // input to unifySubs
  1035. exists []string // paths that exist in the database
  1036. out []string // expected output
  1037. }{
  1038. {
  1039. // 0. trailing slashes are cleaned, known paths are just passed on
  1040. []string{"foo/", "bar//"},
  1041. []string{"foo", "bar"},
  1042. []string{"bar", "foo"}, // the output is sorted
  1043. },
  1044. {
  1045. // 1. "foo/bar" gets trimmed as it's covered by foo
  1046. []string{"foo", "bar/", "foo/bar/"},
  1047. []string{"foo", "bar"},
  1048. []string{"bar", "foo"},
  1049. },
  1050. {
  1051. // 2. "" gets simplified to the empty list; ie scan all
  1052. []string{"foo", ""},
  1053. []string{"foo"},
  1054. nil,
  1055. },
  1056. {
  1057. // 3. "foo/bar" is unknown, but it's kept
  1058. // because its parent is known
  1059. []string{"foo/bar"},
  1060. []string{"foo"},
  1061. []string{"foo/bar"},
  1062. },
  1063. {
  1064. // 4. two independent known paths, both are kept
  1065. // "usr/lib" is not a prefix of "usr/libexec"
  1066. []string{"usr/lib", "usr/libexec"},
  1067. []string{"usr", "usr/lib", "usr/libexec"},
  1068. []string{"usr/lib", "usr/libexec"},
  1069. },
  1070. {
  1071. // 5. "usr/lib" is a prefix of "usr/lib/exec"
  1072. []string{"usr/lib", "usr/lib/exec"},
  1073. []string{"usr", "usr/lib", "usr/libexec"},
  1074. []string{"usr/lib"},
  1075. },
  1076. {
  1077. // 6. .stignore and .stfolder are special and are passed on
  1078. // verbatim even though they are unknown
  1079. []string{".stfolder", ".stignore"},
  1080. []string{},
  1081. []string{".stfolder", ".stignore"},
  1082. },
  1083. {
  1084. // 7. but the presence of something else unknown forces an actual
  1085. // scan
  1086. []string{".stfolder", ".stignore", "foo/bar"},
  1087. []string{},
  1088. []string{".stfolder", ".stignore", "foo"},
  1089. },
  1090. {
  1091. // 8. explicit request to scan all
  1092. nil,
  1093. []string{"foo"},
  1094. nil,
  1095. },
  1096. {
  1097. // 9. empty list of subs
  1098. []string{},
  1099. []string{"foo"},
  1100. nil,
  1101. },
  1102. }
  1103. if runtime.GOOS == "windows" {
  1104. // Fixup path separators
  1105. for i := range cases {
  1106. for j, p := range cases[i].in {
  1107. cases[i].in[j] = filepath.FromSlash(p)
  1108. }
  1109. for j, p := range cases[i].exists {
  1110. cases[i].exists[j] = filepath.FromSlash(p)
  1111. }
  1112. for j, p := range cases[i].out {
  1113. cases[i].out[j] = filepath.FromSlash(p)
  1114. }
  1115. }
  1116. }
  1117. for i, tc := range cases {
  1118. exists := func(f string) bool {
  1119. for _, e := range tc.exists {
  1120. if f == e {
  1121. return true
  1122. }
  1123. }
  1124. return false
  1125. }
  1126. out := unifySubs(tc.in, exists)
  1127. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1128. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1129. }
  1130. }
  1131. }
  1132. func TestIssue3028(t *testing.T) {
  1133. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1134. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1135. t.Fatal(err)
  1136. }
  1137. defer os.Remove("testdata/testrm")
  1138. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1139. t.Fatal(err)
  1140. }
  1141. defer os.Remove("testdata/testrm2")
  1142. // Create a model and default folder
  1143. db := db.OpenMemory()
  1144. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1145. defCfg := defaultFolderConfig.Copy()
  1146. defCfg.RescanIntervalS = 86400
  1147. m.AddFolder(defCfg)
  1148. m.StartFolder("default")
  1149. m.ServeBackground()
  1150. // Ugly hack for testing: reach into the model for the rwfolder and wait
  1151. // for it to complete the initial scan. The risk is that it otherwise
  1152. // runs during our modifications and screws up the test.
  1153. m.fmut.RLock()
  1154. folder := m.folderRunners["default"].(*rwFolder)
  1155. m.fmut.RUnlock()
  1156. <-folder.initialScanCompleted
  1157. // Get a count of how many files are there now
  1158. locorigfiles, _, _ := m.LocalSize("default")
  1159. globorigfiles, _, _ := m.GlobalSize("default")
  1160. // Delete and rescan specifically these two
  1161. os.Remove("testdata/testrm")
  1162. os.Remove("testdata/testrm2")
  1163. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1164. // Verify that the number of files decreased by two and the number of
  1165. // deleted files increases by two
  1166. locnowfiles, locdelfiles, _ := m.LocalSize("default")
  1167. globnowfiles, globdelfiles, _ := m.GlobalSize("default")
  1168. if locnowfiles != locorigfiles-2 {
  1169. t.Errorf("Incorrect local accounting; got %d current files, expected %d", locnowfiles, locorigfiles-2)
  1170. }
  1171. if globnowfiles != globorigfiles-2 {
  1172. t.Errorf("Incorrect global accounting; got %d current files, expected %d", globnowfiles, globorigfiles-2)
  1173. }
  1174. if locdelfiles != 2 {
  1175. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", locdelfiles)
  1176. }
  1177. if globdelfiles != 2 {
  1178. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", globdelfiles)
  1179. }
  1180. }
  1181. func TestIssue3164(t *testing.T) {
  1182. osutil.RemoveAll("testdata/issue3164")
  1183. defer osutil.RemoveAll("testdata/issue3164")
  1184. if err := os.MkdirAll("testdata/issue3164/oktodelete/foobar", 0777); err != nil {
  1185. t.Fatal(err)
  1186. }
  1187. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  1188. t.Fatal(err)
  1189. }
  1190. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  1191. t.Fatal(err)
  1192. }
  1193. f := protocol.FileInfo{
  1194. Name: "issue3164",
  1195. }
  1196. m := ignore.New(false)
  1197. if err := m.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  1198. t.Fatal(err)
  1199. }
  1200. fl := rwFolder{
  1201. dbUpdates: make(chan dbUpdateJob, 1),
  1202. dir: "testdata",
  1203. }
  1204. fl.deleteDir(f, m)
  1205. if _, err := os.Stat("testdata/issue3164"); !os.IsNotExist(err) {
  1206. t.Fatal(err)
  1207. }
  1208. }
  1209. func TestScanNoDatabaseWrite(t *testing.T) {
  1210. // When scanning, nothing should be committed to database unless
  1211. // something actually changed.
  1212. db := db.OpenMemory()
  1213. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1214. m.AddFolder(defaultFolderConfig)
  1215. m.StartFolder("default")
  1216. m.ServeBackground()
  1217. // Start with no ignores, and restore the previous state when the test completes
  1218. curIgn, _, err := m.GetIgnores("default")
  1219. if err != nil {
  1220. t.Fatal(err)
  1221. }
  1222. defer m.SetIgnores("default", curIgn)
  1223. m.SetIgnores("default", nil)
  1224. // Scan the folder twice. The second scan should be a no-op database wise
  1225. m.ScanFolder("default")
  1226. c0 := db.Committed()
  1227. m.ScanFolder("default")
  1228. c1 := db.Committed()
  1229. if c1 != c0 {
  1230. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  1231. }
  1232. // Ignore a file we know exists. It'll be updated in the database.
  1233. m.SetIgnores("default", []string{"foo"})
  1234. m.ScanFolder("default")
  1235. c2 := db.Committed()
  1236. if c2 <= c1 {
  1237. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  1238. }
  1239. // Scan again. Nothing should happen.
  1240. m.ScanFolder("default")
  1241. c3 := db.Committed()
  1242. if c3 != c2 {
  1243. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  1244. }
  1245. }
  1246. func TestIssue2782(t *testing.T) {
  1247. // CheckFolderHealth should accept a symlinked folder, when using tilde-expanded path.
  1248. if runtime.GOOS == "windows" {
  1249. t.Skip("not reliable on Windows")
  1250. return
  1251. }
  1252. home := os.Getenv("HOME")
  1253. if home == "" {
  1254. t.Skip("no home")
  1255. }
  1256. // Create the test env. Needs to be based on $HOME as tilde expansion is
  1257. // part of the issue. Skip the test if any of this fails, as we are a
  1258. // bit outside of our stated domain here...
  1259. testName := ".syncthing-test." + srand.String(16)
  1260. testDir := filepath.Join(home, testName)
  1261. if err := osutil.RemoveAll(testDir); err != nil {
  1262. t.Skip(err)
  1263. }
  1264. if err := osutil.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  1265. t.Skip(err)
  1266. }
  1267. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  1268. t.Skip(err)
  1269. }
  1270. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  1271. t.Skip(err)
  1272. }
  1273. defer osutil.RemoveAll(testDir)
  1274. db := db.OpenMemory()
  1275. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1276. m.AddFolder(config.NewFolderConfiguration("default", "~/"+testName+"/synclink/"))
  1277. m.StartFolder("default")
  1278. m.ServeBackground()
  1279. defer m.Stop()
  1280. if err := m.ScanFolder("default"); err != nil {
  1281. t.Error("scan error:", err)
  1282. }
  1283. if err := m.CheckFolderHealth("default"); err != nil {
  1284. t.Error("health check error:", err)
  1285. }
  1286. }
  1287. type fakeAddr struct{}
  1288. func (fakeAddr) Network() string {
  1289. return "network"
  1290. }
  1291. func (fakeAddr) String() string {
  1292. return "address"
  1293. }
  1294. type fakeConn struct{}
  1295. func (fakeConn) Close() error {
  1296. return nil
  1297. }
  1298. func (fakeConn) LocalAddr() net.Addr {
  1299. return &fakeAddr{}
  1300. }
  1301. func (fakeConn) RemoteAddr() net.Addr {
  1302. return &fakeAddr{}
  1303. }
  1304. func (fakeConn) Read([]byte) (int, error) {
  1305. return 0, nil
  1306. }
  1307. func (fakeConn) Write([]byte) (int, error) {
  1308. return 0, nil
  1309. }
  1310. func (fakeConn) SetDeadline(time.Time) error {
  1311. return nil
  1312. }
  1313. func (fakeConn) SetReadDeadline(time.Time) error {
  1314. return nil
  1315. }
  1316. func (fakeConn) SetWriteDeadline(time.Time) error {
  1317. return nil
  1318. }