model_test.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807
  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. ModifiedS: 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. ModifiedS: 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. ModifiedS: 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.ModifiedS = 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. defer m.Stop()
  86. m.ScanFolder("default")
  87. bs := make([]byte, protocol.BlockSize)
  88. // Existing, shared file
  89. bs = bs[:6]
  90. err := m.Request(device1, "default", "foo", 0, nil, false, bs)
  91. if err != nil {
  92. t.Error(err)
  93. }
  94. if !bytes.Equal(bs, []byte("foobar")) {
  95. t.Errorf("Incorrect data from request: %q", string(bs))
  96. }
  97. // Existing, nonshared file
  98. err = m.Request(device2, "default", "foo", 0, nil, false, bs)
  99. if err == nil {
  100. t.Error("Unexpected nil error on insecure file read")
  101. }
  102. // Nonexistent file
  103. err = m.Request(device1, "default", "nonexistent", 0, nil, false, bs)
  104. if err == nil {
  105. t.Error("Unexpected nil error on insecure file read")
  106. }
  107. // Shared folder, but disallowed file name
  108. err = m.Request(device1, "default", "../walk.go", 0, nil, false, bs)
  109. if err == nil {
  110. t.Error("Unexpected nil error on insecure file read")
  111. }
  112. // Negative offset
  113. err = m.Request(device1, "default", "foo", -4, nil, false, bs[:0])
  114. if err == nil {
  115. t.Error("Unexpected nil error on insecure file read")
  116. }
  117. // Larger block than available
  118. bs = bs[:42]
  119. err = m.Request(device1, "default", "foo", 0, nil, false, bs)
  120. if err == nil {
  121. t.Error("Unexpected nil error on insecure file read")
  122. }
  123. }
  124. func genFiles(n int) []protocol.FileInfo {
  125. files := make([]protocol.FileInfo, n)
  126. t := time.Now().Unix()
  127. for i := 0; i < n; i++ {
  128. files[i] = protocol.FileInfo{
  129. Name: fmt.Sprintf("file%d", i),
  130. ModifiedS: t,
  131. Sequence: int64(i + 1),
  132. Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
  133. }
  134. }
  135. return files
  136. }
  137. func BenchmarkIndex_10000(b *testing.B) {
  138. benchmarkIndex(b, 10000)
  139. }
  140. func BenchmarkIndex_100(b *testing.B) {
  141. benchmarkIndex(b, 100)
  142. }
  143. func benchmarkIndex(b *testing.B, nfiles int) {
  144. db := db.OpenMemory()
  145. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  146. m.AddFolder(defaultFolderConfig)
  147. m.StartFolder("default")
  148. m.ServeBackground()
  149. defer m.Stop()
  150. files := genFiles(nfiles)
  151. m.Index(device1, "default", files)
  152. b.ResetTimer()
  153. for i := 0; i < b.N; i++ {
  154. m.Index(device1, "default", files)
  155. }
  156. b.ReportAllocs()
  157. }
  158. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  159. benchmarkIndexUpdate(b, 10000, 10000)
  160. }
  161. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  162. benchmarkIndexUpdate(b, 10000, 100)
  163. }
  164. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  165. benchmarkIndexUpdate(b, 10000, 1)
  166. }
  167. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  168. db := db.OpenMemory()
  169. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  170. m.AddFolder(defaultFolderConfig)
  171. m.StartFolder("default")
  172. m.ServeBackground()
  173. defer m.Stop()
  174. files := genFiles(nfiles)
  175. ufiles := genFiles(nufiles)
  176. m.Index(device1, "default", files)
  177. b.ResetTimer()
  178. for i := 0; i < b.N; i++ {
  179. m.IndexUpdate(device1, "default", ufiles)
  180. }
  181. b.ReportAllocs()
  182. }
  183. type downloadProgressMessage struct {
  184. folder string
  185. updates []protocol.FileDownloadProgressUpdate
  186. }
  187. type FakeConnection struct {
  188. id protocol.DeviceID
  189. requestData []byte
  190. downloadProgressMessages []downloadProgressMessage
  191. }
  192. func (FakeConnection) Close() error {
  193. return nil
  194. }
  195. func (f FakeConnection) Start() {
  196. }
  197. func (f FakeConnection) ID() protocol.DeviceID {
  198. return f.id
  199. }
  200. func (f FakeConnection) Name() string {
  201. return ""
  202. }
  203. func (f FakeConnection) Option(string) string {
  204. return ""
  205. }
  206. func (FakeConnection) Index(string, []protocol.FileInfo) error {
  207. return nil
  208. }
  209. func (FakeConnection) IndexUpdate(string, []protocol.FileInfo) error {
  210. return nil
  211. }
  212. func (f FakeConnection) Request(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  213. return f.requestData, nil
  214. }
  215. func (FakeConnection) ClusterConfig(protocol.ClusterConfig) {}
  216. func (FakeConnection) Ping() bool {
  217. return true
  218. }
  219. func (FakeConnection) Closed() bool {
  220. return false
  221. }
  222. func (FakeConnection) Statistics() protocol.Statistics {
  223. return protocol.Statistics{}
  224. }
  225. func (f *FakeConnection) DownloadProgress(folder string, updates []protocol.FileDownloadProgressUpdate) {
  226. f.downloadProgressMessages = append(f.downloadProgressMessages, downloadProgressMessage{
  227. folder: folder,
  228. updates: updates,
  229. })
  230. }
  231. func BenchmarkRequest(b *testing.B) {
  232. db := db.OpenMemory()
  233. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  234. m.AddFolder(defaultFolderConfig)
  235. m.ServeBackground()
  236. defer m.Stop()
  237. m.ScanFolder("default")
  238. const n = 1000
  239. files := genFiles(n)
  240. fc := &FakeConnection{
  241. id: device1,
  242. requestData: []byte("some data to return"),
  243. }
  244. m.AddConnection(connections.Connection{
  245. IntermediateConnection: connections.IntermediateConnection{
  246. Conn: tls.Client(&fakeConn{}, nil),
  247. Type: "foo",
  248. Priority: 10,
  249. },
  250. Connection: fc,
  251. }, protocol.HelloResult{})
  252. m.Index(device1, "default", files)
  253. b.ResetTimer()
  254. for i := 0; i < b.N; i++ {
  255. data, err := m.requestGlobal(device1, "default", files[i%n].Name, 0, 32, nil, false)
  256. if err != nil {
  257. b.Error(err)
  258. }
  259. if data == nil {
  260. b.Error("nil data")
  261. }
  262. }
  263. }
  264. func TestDeviceRename(t *testing.T) {
  265. hello := protocol.HelloResult{
  266. ClientName: "syncthing",
  267. ClientVersion: "v0.9.4",
  268. }
  269. defer os.Remove("tmpconfig.xml")
  270. rawCfg := config.New(device1)
  271. rawCfg.Devices = []config.DeviceConfiguration{
  272. {
  273. DeviceID: device1,
  274. },
  275. }
  276. cfg := config.Wrap("tmpconfig.xml", rawCfg)
  277. db := db.OpenMemory()
  278. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  279. if cfg.Devices()[device1].Name != "" {
  280. t.Errorf("Device already has a name")
  281. }
  282. conn := connections.Connection{
  283. IntermediateConnection: connections.IntermediateConnection{
  284. Conn: tls.Client(&fakeConn{}, nil),
  285. Type: "foo",
  286. Priority: 10,
  287. },
  288. Connection: &FakeConnection{
  289. id: device1,
  290. requestData: []byte("some data to return"),
  291. },
  292. }
  293. m.AddConnection(conn, hello)
  294. m.ServeBackground()
  295. defer m.Stop()
  296. if cfg.Devices()[device1].Name != "" {
  297. t.Errorf("Device already has a name")
  298. }
  299. m.Closed(conn, protocol.ErrTimeout)
  300. hello.DeviceName = "tester"
  301. m.AddConnection(conn, hello)
  302. if cfg.Devices()[device1].Name != "tester" {
  303. t.Errorf("Device did not get a name")
  304. }
  305. m.Closed(conn, protocol.ErrTimeout)
  306. hello.DeviceName = "tester2"
  307. m.AddConnection(conn, hello)
  308. if cfg.Devices()[device1].Name != "tester" {
  309. t.Errorf("Device name got overwritten")
  310. }
  311. cfgw, err := config.Load("tmpconfig.xml", protocol.LocalDeviceID)
  312. if err != nil {
  313. t.Error(err)
  314. return
  315. }
  316. if cfgw.Devices()[device1].Name != "tester" {
  317. t.Errorf("Device name not saved in config")
  318. }
  319. m.Closed(conn, protocol.ErrTimeout)
  320. opts := cfg.Options()
  321. opts.OverwriteRemoteDevNames = true
  322. cfg.SetOptions(opts)
  323. hello.DeviceName = "tester2"
  324. m.AddConnection(conn, hello)
  325. if cfg.Devices()[device1].Name != "tester2" {
  326. t.Errorf("Device name not overwritten")
  327. }
  328. }
  329. func TestClusterConfig(t *testing.T) {
  330. cfg := config.New(device1)
  331. cfg.Devices = []config.DeviceConfiguration{
  332. {
  333. DeviceID: device1,
  334. Introducer: true,
  335. },
  336. {
  337. DeviceID: device2,
  338. },
  339. }
  340. cfg.Folders = []config.FolderConfiguration{
  341. {
  342. ID: "folder1",
  343. Devices: []config.FolderDeviceConfiguration{
  344. {DeviceID: device1},
  345. {DeviceID: device2},
  346. },
  347. },
  348. {
  349. ID: "folder2",
  350. Devices: []config.FolderDeviceConfiguration{
  351. {DeviceID: device1},
  352. {DeviceID: device2},
  353. },
  354. },
  355. }
  356. db := db.OpenMemory()
  357. m := NewModel(config.Wrap("/tmp/test", cfg), protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  358. m.AddFolder(cfg.Folders[0])
  359. m.AddFolder(cfg.Folders[1])
  360. m.ServeBackground()
  361. defer m.Stop()
  362. cm := m.generateClusterConfig(device2)
  363. if l := len(cm.Folders); l != 2 {
  364. t.Fatalf("Incorrect number of folders %d != 2", l)
  365. }
  366. r := cm.Folders[0]
  367. if r.ID != "folder1" {
  368. t.Errorf("Incorrect folder %q != folder1", r.ID)
  369. }
  370. if l := len(r.Devices); l != 2 {
  371. t.Errorf("Incorrect number of devices %d != 2", l)
  372. }
  373. if id := r.Devices[0].ID; id != device1 {
  374. t.Errorf("Incorrect device ID %x != %x", id, device1)
  375. }
  376. if !r.Devices[0].Introducer {
  377. t.Error("Device1 should be flagged as Introducer")
  378. }
  379. if id := r.Devices[1].ID; id != device2 {
  380. t.Errorf("Incorrect device ID %x != %x", id, device2)
  381. }
  382. if r.Devices[1].Introducer {
  383. t.Error("Device2 should not be flagged as Introducer")
  384. }
  385. r = cm.Folders[1]
  386. if r.ID != "folder2" {
  387. t.Errorf("Incorrect folder %q != folder2", r.ID)
  388. }
  389. if l := len(r.Devices); l != 2 {
  390. t.Errorf("Incorrect number of devices %d != 2", l)
  391. }
  392. if id := r.Devices[0].ID; id != device1 {
  393. t.Errorf("Incorrect device ID %x != %x", id, device1)
  394. }
  395. if !r.Devices[0].Introducer {
  396. t.Error("Device1 should be flagged as Introducer")
  397. }
  398. if id := r.Devices[1].ID; id != device2 {
  399. t.Errorf("Incorrect device ID %x != %x", id, device2)
  400. }
  401. if r.Devices[1].Introducer {
  402. t.Error("Device2 should not be flagged as Introducer")
  403. }
  404. }
  405. func TestIgnores(t *testing.T) {
  406. arrEqual := func(a, b []string) bool {
  407. if len(a) != len(b) {
  408. return false
  409. }
  410. for i := range a {
  411. if a[i] != b[i] {
  412. return false
  413. }
  414. }
  415. return true
  416. }
  417. // Assure a clean start state
  418. ioutil.WriteFile("testdata/.stfolder", nil, 0644)
  419. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  420. db := db.OpenMemory()
  421. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  422. m.AddFolder(defaultFolderConfig)
  423. m.StartFolder("default")
  424. m.ServeBackground()
  425. defer m.Stop()
  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. defer m.Stop()
  504. waitFor := func(status string) error {
  505. timeout := time.Now().Add(2 * time.Second)
  506. for {
  507. _, _, err := m.State("default")
  508. if err == nil && status == "" {
  509. return nil
  510. }
  511. if err != nil && err.Error() == status {
  512. return nil
  513. }
  514. if time.Now().After(timeout) {
  515. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  516. }
  517. time.Sleep(10 * time.Millisecond)
  518. }
  519. }
  520. if err := waitFor("folder path missing"); err != nil {
  521. t.Error(err)
  522. return
  523. }
  524. os.Mkdir(fcfg.RawPath, 0700)
  525. if err := waitFor("folder marker missing"); err != nil {
  526. t.Error(err)
  527. return
  528. }
  529. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  530. if err != nil {
  531. t.Error(err)
  532. return
  533. }
  534. fd.Close()
  535. if err := waitFor(""); err != nil {
  536. t.Error(err)
  537. return
  538. }
  539. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  540. if err := waitFor("folder marker missing"); err != nil {
  541. t.Error(err)
  542. return
  543. }
  544. os.Remove(fcfg.RawPath)
  545. if err := waitFor("folder path missing"); err != nil {
  546. t.Error(err)
  547. return
  548. }
  549. }
  550. func TestRWScanRecovery(t *testing.T) {
  551. ldb := db.OpenMemory()
  552. set := db.NewFileSet("default", ldb)
  553. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  554. {Name: "dummyfile"},
  555. })
  556. fcfg := config.FolderConfiguration{
  557. ID: "default",
  558. RawPath: "testdata/rwtestfolder",
  559. Type: config.FolderTypeReadWrite,
  560. RescanIntervalS: 1,
  561. }
  562. cfg := config.Wrap("/tmp/test", config.Configuration{
  563. Folders: []config.FolderConfiguration{fcfg},
  564. Devices: []config.DeviceConfiguration{
  565. {
  566. DeviceID: device1,
  567. },
  568. },
  569. })
  570. os.RemoveAll(fcfg.RawPath)
  571. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb, nil)
  572. m.AddFolder(fcfg)
  573. m.StartFolder("default")
  574. m.ServeBackground()
  575. defer m.Stop()
  576. waitFor := func(status string) error {
  577. timeout := time.Now().Add(2 * time.Second)
  578. for {
  579. _, _, err := m.State("default")
  580. if err == nil && status == "" {
  581. return nil
  582. }
  583. if err != nil && err.Error() == status {
  584. return nil
  585. }
  586. if time.Now().After(timeout) {
  587. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  588. }
  589. time.Sleep(10 * time.Millisecond)
  590. }
  591. }
  592. if err := waitFor("folder path missing"); err != nil {
  593. t.Error(err)
  594. return
  595. }
  596. os.Mkdir(fcfg.RawPath, 0700)
  597. if err := waitFor("folder marker missing"); err != nil {
  598. t.Error(err)
  599. return
  600. }
  601. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  602. if err != nil {
  603. t.Error(err)
  604. return
  605. }
  606. fd.Close()
  607. if err := waitFor(""); err != nil {
  608. t.Error(err)
  609. return
  610. }
  611. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  612. if err := waitFor("folder marker missing"); err != nil {
  613. t.Error(err)
  614. return
  615. }
  616. os.Remove(fcfg.RawPath)
  617. if err := waitFor("folder path missing"); err != nil {
  618. t.Error(err)
  619. return
  620. }
  621. }
  622. func TestGlobalDirectoryTree(t *testing.T) {
  623. db := db.OpenMemory()
  624. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  625. m.AddFolder(defaultFolderConfig)
  626. m.ServeBackground()
  627. defer m.Stop()
  628. b := func(isfile bool, path ...string) protocol.FileInfo {
  629. typ := protocol.FileInfoTypeDirectory
  630. blocks := []protocol.BlockInfo{}
  631. if isfile {
  632. typ = protocol.FileInfoTypeFile
  633. 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}}}
  634. }
  635. return protocol.FileInfo{
  636. Name: filepath.Join(path...),
  637. Type: typ,
  638. ModifiedS: 0x666,
  639. Blocks: blocks,
  640. Size: 0xa,
  641. }
  642. }
  643. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  644. testdata := []protocol.FileInfo{
  645. b(false, "another"),
  646. b(false, "another", "directory"),
  647. b(true, "another", "directory", "afile"),
  648. b(false, "another", "directory", "with"),
  649. b(false, "another", "directory", "with", "a"),
  650. b(true, "another", "directory", "with", "a", "file"),
  651. b(true, "another", "directory", "with", "file"),
  652. b(true, "another", "file"),
  653. b(false, "other"),
  654. b(false, "other", "rand"),
  655. b(false, "other", "random"),
  656. b(false, "other", "random", "dir"),
  657. b(false, "other", "random", "dirx"),
  658. b(false, "other", "randomx"),
  659. b(false, "some"),
  660. b(false, "some", "directory"),
  661. b(false, "some", "directory", "with"),
  662. b(false, "some", "directory", "with", "a"),
  663. b(true, "some", "directory", "with", "a", "file"),
  664. b(true, "rootfile"),
  665. }
  666. expectedResult := map[string]interface{}{
  667. "another": map[string]interface{}{
  668. "directory": map[string]interface{}{
  669. "afile": filedata,
  670. "with": map[string]interface{}{
  671. "a": map[string]interface{}{
  672. "file": filedata,
  673. },
  674. "file": filedata,
  675. },
  676. },
  677. "file": filedata,
  678. },
  679. "other": map[string]interface{}{
  680. "rand": map[string]interface{}{},
  681. "random": map[string]interface{}{
  682. "dir": map[string]interface{}{},
  683. "dirx": map[string]interface{}{},
  684. },
  685. "randomx": map[string]interface{}{},
  686. },
  687. "some": map[string]interface{}{
  688. "directory": map[string]interface{}{
  689. "with": map[string]interface{}{
  690. "a": map[string]interface{}{
  691. "file": filedata,
  692. },
  693. },
  694. },
  695. },
  696. "rootfile": filedata,
  697. }
  698. mm := func(data interface{}) string {
  699. bytes, err := json.Marshal(data)
  700. if err != nil {
  701. panic(err)
  702. }
  703. return string(bytes)
  704. }
  705. m.Index(device1, "default", testdata)
  706. result := m.GlobalDirectoryTree("default", "", -1, false)
  707. if mm(result) != mm(expectedResult) {
  708. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  709. }
  710. result = m.GlobalDirectoryTree("default", "another", -1, false)
  711. if mm(result) != mm(expectedResult["another"]) {
  712. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  713. }
  714. result = m.GlobalDirectoryTree("default", "", 0, false)
  715. currentResult := map[string]interface{}{
  716. "another": map[string]interface{}{},
  717. "other": map[string]interface{}{},
  718. "some": map[string]interface{}{},
  719. "rootfile": filedata,
  720. }
  721. if mm(result) != mm(currentResult) {
  722. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  723. }
  724. result = m.GlobalDirectoryTree("default", "", 1, false)
  725. currentResult = map[string]interface{}{
  726. "another": map[string]interface{}{
  727. "directory": map[string]interface{}{},
  728. "file": filedata,
  729. },
  730. "other": map[string]interface{}{
  731. "rand": map[string]interface{}{},
  732. "random": map[string]interface{}{},
  733. "randomx": map[string]interface{}{},
  734. },
  735. "some": map[string]interface{}{
  736. "directory": map[string]interface{}{},
  737. },
  738. "rootfile": filedata,
  739. }
  740. if mm(result) != mm(currentResult) {
  741. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  742. }
  743. result = m.GlobalDirectoryTree("default", "", -1, true)
  744. currentResult = map[string]interface{}{
  745. "another": map[string]interface{}{
  746. "directory": map[string]interface{}{
  747. "with": map[string]interface{}{
  748. "a": map[string]interface{}{},
  749. },
  750. },
  751. },
  752. "other": map[string]interface{}{
  753. "rand": map[string]interface{}{},
  754. "random": map[string]interface{}{
  755. "dir": map[string]interface{}{},
  756. "dirx": map[string]interface{}{},
  757. },
  758. "randomx": map[string]interface{}{},
  759. },
  760. "some": map[string]interface{}{
  761. "directory": map[string]interface{}{
  762. "with": map[string]interface{}{
  763. "a": map[string]interface{}{},
  764. },
  765. },
  766. },
  767. }
  768. if mm(result) != mm(currentResult) {
  769. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  770. }
  771. result = m.GlobalDirectoryTree("default", "", 1, true)
  772. currentResult = map[string]interface{}{
  773. "another": map[string]interface{}{
  774. "directory": map[string]interface{}{},
  775. },
  776. "other": map[string]interface{}{
  777. "rand": map[string]interface{}{},
  778. "random": map[string]interface{}{},
  779. "randomx": map[string]interface{}{},
  780. },
  781. "some": map[string]interface{}{
  782. "directory": map[string]interface{}{},
  783. },
  784. }
  785. if mm(result) != mm(currentResult) {
  786. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  787. }
  788. result = m.GlobalDirectoryTree("default", "another", 0, false)
  789. currentResult = map[string]interface{}{
  790. "directory": map[string]interface{}{},
  791. "file": filedata,
  792. }
  793. if mm(result) != mm(currentResult) {
  794. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  795. }
  796. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  797. currentResult = map[string]interface{}{
  798. "with": map[string]interface{}{},
  799. }
  800. if mm(result) != mm(currentResult) {
  801. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  802. }
  803. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  804. currentResult = map[string]interface{}{
  805. "with": map[string]interface{}{
  806. "a": map[string]interface{}{},
  807. },
  808. }
  809. if mm(result) != mm(currentResult) {
  810. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  811. }
  812. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  813. currentResult = map[string]interface{}{
  814. "with": map[string]interface{}{
  815. "a": map[string]interface{}{
  816. "file": filedata,
  817. },
  818. },
  819. }
  820. if mm(result) != mm(currentResult) {
  821. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  822. }
  823. result = m.GlobalDirectoryTree("default", "another", -1, true)
  824. currentResult = map[string]interface{}{
  825. "directory": map[string]interface{}{
  826. "with": map[string]interface{}{
  827. "a": map[string]interface{}{},
  828. },
  829. },
  830. }
  831. if mm(result) != mm(currentResult) {
  832. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  833. }
  834. // No prefix matching!
  835. result = m.GlobalDirectoryTree("default", "som", -1, false)
  836. currentResult = map[string]interface{}{}
  837. if mm(result) != mm(currentResult) {
  838. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  839. }
  840. }
  841. func TestGlobalDirectorySelfFixing(t *testing.T) {
  842. db := db.OpenMemory()
  843. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  844. m.AddFolder(defaultFolderConfig)
  845. m.ServeBackground()
  846. b := func(isfile bool, path ...string) protocol.FileInfo {
  847. typ := protocol.FileInfoTypeDirectory
  848. blocks := []protocol.BlockInfo{}
  849. if isfile {
  850. typ = protocol.FileInfoTypeFile
  851. 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}}}
  852. }
  853. return protocol.FileInfo{
  854. Name: filepath.Join(path...),
  855. Type: typ,
  856. ModifiedS: 0x666,
  857. Blocks: blocks,
  858. Size: 0xa,
  859. }
  860. }
  861. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  862. testdata := []protocol.FileInfo{
  863. b(true, "another", "directory", "afile"),
  864. b(true, "another", "directory", "with", "a", "file"),
  865. b(true, "another", "directory", "with", "file"),
  866. b(false, "other", "random", "dirx"),
  867. b(false, "other", "randomx"),
  868. b(false, "some", "directory", "with", "x"),
  869. b(true, "some", "directory", "with", "a", "file"),
  870. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  871. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  872. }
  873. expectedResult := map[string]interface{}{
  874. "another": map[string]interface{}{
  875. "directory": map[string]interface{}{
  876. "afile": filedata,
  877. "with": map[string]interface{}{
  878. "a": map[string]interface{}{
  879. "file": filedata,
  880. },
  881. "file": filedata,
  882. },
  883. },
  884. },
  885. "other": map[string]interface{}{
  886. "random": map[string]interface{}{
  887. "dirx": map[string]interface{}{},
  888. },
  889. "randomx": map[string]interface{}{},
  890. },
  891. "some": map[string]interface{}{
  892. "directory": map[string]interface{}{
  893. "with": map[string]interface{}{
  894. "a": map[string]interface{}{
  895. "file": filedata,
  896. },
  897. "x": map[string]interface{}{},
  898. },
  899. },
  900. },
  901. "this": map[string]interface{}{
  902. "is": map[string]interface{}{
  903. "a": map[string]interface{}{
  904. "deep": map[string]interface{}{
  905. "invalid": map[string]interface{}{
  906. "directory": map[string]interface{}{},
  907. },
  908. },
  909. },
  910. },
  911. },
  912. "xthis": map[string]interface{}{
  913. "is": map[string]interface{}{
  914. "a": map[string]interface{}{
  915. "deep": map[string]interface{}{
  916. "invalid": map[string]interface{}{
  917. "file": filedata,
  918. },
  919. },
  920. },
  921. },
  922. },
  923. }
  924. mm := func(data interface{}) string {
  925. bytes, err := json.Marshal(data)
  926. if err != nil {
  927. panic(err)
  928. }
  929. return string(bytes)
  930. }
  931. m.Index(device1, "default", testdata)
  932. result := m.GlobalDirectoryTree("default", "", -1, false)
  933. if mm(result) != mm(expectedResult) {
  934. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  935. }
  936. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  937. currentResult := map[string]interface{}{
  938. "invalid": map[string]interface{}{
  939. "file": filedata,
  940. },
  941. }
  942. if mm(result) != mm(currentResult) {
  943. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  944. }
  945. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  946. currentResult = map[string]interface{}{
  947. "invalid": map[string]interface{}{},
  948. }
  949. if mm(result) != mm(currentResult) {
  950. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  951. }
  952. // !!! This is actually BAD, because we don't have enough level allowance
  953. // to accept this file, hence the tree is left unbuilt !!!
  954. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  955. currentResult = map[string]interface{}{}
  956. if mm(result) != mm(currentResult) {
  957. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  958. }
  959. }
  960. func genDeepFiles(n, d int) []protocol.FileInfo {
  961. rand.Seed(int64(n))
  962. files := make([]protocol.FileInfo, n)
  963. t := time.Now().Unix()
  964. for i := 0; i < n; i++ {
  965. path := ""
  966. for i := 0; i <= d; i++ {
  967. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  968. }
  969. sofar := ""
  970. for _, path := range filepath.SplitList(path) {
  971. sofar = filepath.Join(sofar, path)
  972. files[i] = protocol.FileInfo{
  973. Name: sofar,
  974. }
  975. i++
  976. }
  977. files[i].ModifiedS = t
  978. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  979. }
  980. return files
  981. }
  982. func BenchmarkTree_10000_50(b *testing.B) {
  983. benchmarkTree(b, 10000, 50)
  984. }
  985. func BenchmarkTree_100_50(b *testing.B) {
  986. benchmarkTree(b, 100, 50)
  987. }
  988. func BenchmarkTree_100_10(b *testing.B) {
  989. benchmarkTree(b, 100, 10)
  990. }
  991. func benchmarkTree(b *testing.B, n1, n2 int) {
  992. db := db.OpenMemory()
  993. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  994. m.AddFolder(defaultFolderConfig)
  995. m.ServeBackground()
  996. m.ScanFolder("default")
  997. files := genDeepFiles(n1, n2)
  998. m.Index(device1, "default", files)
  999. b.ResetTimer()
  1000. for i := 0; i < b.N; i++ {
  1001. m.GlobalDirectoryTree("default", "", -1, false)
  1002. }
  1003. b.ReportAllocs()
  1004. }
  1005. func TestUnifySubs(t *testing.T) {
  1006. cases := []struct {
  1007. in []string // input to unifySubs
  1008. exists []string // paths that exist in the database
  1009. out []string // expected output
  1010. }{
  1011. {
  1012. // 0. trailing slashes are cleaned, known paths are just passed on
  1013. []string{"foo/", "bar//"},
  1014. []string{"foo", "bar"},
  1015. []string{"bar", "foo"}, // the output is sorted
  1016. },
  1017. {
  1018. // 1. "foo/bar" gets trimmed as it's covered by foo
  1019. []string{"foo", "bar/", "foo/bar/"},
  1020. []string{"foo", "bar"},
  1021. []string{"bar", "foo"},
  1022. },
  1023. {
  1024. // 2. "" gets simplified to the empty list; ie scan all
  1025. []string{"foo", ""},
  1026. []string{"foo"},
  1027. nil,
  1028. },
  1029. {
  1030. // 3. "foo/bar" is unknown, but it's kept
  1031. // because its parent is known
  1032. []string{"foo/bar"},
  1033. []string{"foo"},
  1034. []string{"foo/bar"},
  1035. },
  1036. {
  1037. // 4. two independent known paths, both are kept
  1038. // "usr/lib" is not a prefix of "usr/libexec"
  1039. []string{"usr/lib", "usr/libexec"},
  1040. []string{"usr", "usr/lib", "usr/libexec"},
  1041. []string{"usr/lib", "usr/libexec"},
  1042. },
  1043. {
  1044. // 5. "usr/lib" is a prefix of "usr/lib/exec"
  1045. []string{"usr/lib", "usr/lib/exec"},
  1046. []string{"usr", "usr/lib", "usr/libexec"},
  1047. []string{"usr/lib"},
  1048. },
  1049. {
  1050. // 6. .stignore and .stfolder are special and are passed on
  1051. // verbatim even though they are unknown
  1052. []string{".stfolder", ".stignore"},
  1053. []string{},
  1054. []string{".stfolder", ".stignore"},
  1055. },
  1056. {
  1057. // 7. but the presence of something else unknown forces an actual
  1058. // scan
  1059. []string{".stfolder", ".stignore", "foo/bar"},
  1060. []string{},
  1061. []string{".stfolder", ".stignore", "foo"},
  1062. },
  1063. {
  1064. // 8. explicit request to scan all
  1065. nil,
  1066. []string{"foo"},
  1067. nil,
  1068. },
  1069. {
  1070. // 9. empty list of subs
  1071. []string{},
  1072. []string{"foo"},
  1073. nil,
  1074. },
  1075. }
  1076. if runtime.GOOS == "windows" {
  1077. // Fixup path separators
  1078. for i := range cases {
  1079. for j, p := range cases[i].in {
  1080. cases[i].in[j] = filepath.FromSlash(p)
  1081. }
  1082. for j, p := range cases[i].exists {
  1083. cases[i].exists[j] = filepath.FromSlash(p)
  1084. }
  1085. for j, p := range cases[i].out {
  1086. cases[i].out[j] = filepath.FromSlash(p)
  1087. }
  1088. }
  1089. }
  1090. for i, tc := range cases {
  1091. exists := func(f string) bool {
  1092. for _, e := range tc.exists {
  1093. if f == e {
  1094. return true
  1095. }
  1096. }
  1097. return false
  1098. }
  1099. out := unifySubs(tc.in, exists)
  1100. if diff, equal := messagediff.PrettyDiff(tc.out, out); !equal {
  1101. t.Errorf("Case %d failed; got %v, expected %v, diff:\n%s", i, out, tc.out, diff)
  1102. }
  1103. }
  1104. }
  1105. func TestIssue3028(t *testing.T) {
  1106. // Create two files that we'll delete, one with a name that is a prefix of the other.
  1107. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  1108. t.Fatal(err)
  1109. }
  1110. defer os.Remove("testdata/testrm")
  1111. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  1112. t.Fatal(err)
  1113. }
  1114. defer os.Remove("testdata/testrm2")
  1115. // Create a model and default folder
  1116. db := db.OpenMemory()
  1117. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1118. defCfg := defaultFolderConfig.Copy()
  1119. defCfg.RescanIntervalS = 86400
  1120. m.AddFolder(defCfg)
  1121. m.StartFolder("default")
  1122. m.ServeBackground()
  1123. // Ugly hack for testing: reach into the model for the rwfolder and wait
  1124. // for it to complete the initial scan. The risk is that it otherwise
  1125. // runs during our modifications and screws up the test.
  1126. m.fmut.RLock()
  1127. folder := m.folderRunners["default"].(*rwFolder)
  1128. m.fmut.RUnlock()
  1129. <-folder.initialScanCompleted
  1130. // Get a count of how many files are there now
  1131. locorigfiles := m.LocalSize("default").Files
  1132. globorigfiles := m.GlobalSize("default").Files
  1133. // Delete and rescan specifically these two
  1134. os.Remove("testdata/testrm")
  1135. os.Remove("testdata/testrm2")
  1136. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  1137. // Verify that the number of files decreased by two and the number of
  1138. // deleted files increases by two
  1139. loc := m.LocalSize("default")
  1140. glob := m.GlobalSize("default")
  1141. if loc.Files != locorigfiles-2 {
  1142. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  1143. }
  1144. if glob.Files != globorigfiles-2 {
  1145. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  1146. }
  1147. if loc.Deleted != 2 {
  1148. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  1149. }
  1150. if glob.Deleted != 2 {
  1151. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  1152. }
  1153. }
  1154. func TestIssue3164(t *testing.T) {
  1155. os.RemoveAll("testdata/issue3164")
  1156. defer os.RemoveAll("testdata/issue3164")
  1157. if err := os.MkdirAll("testdata/issue3164/oktodelete/foobar", 0777); err != nil {
  1158. t.Fatal(err)
  1159. }
  1160. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  1161. t.Fatal(err)
  1162. }
  1163. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  1164. t.Fatal(err)
  1165. }
  1166. f := protocol.FileInfo{
  1167. Name: "issue3164",
  1168. }
  1169. m := ignore.New(false)
  1170. if err := m.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  1171. t.Fatal(err)
  1172. }
  1173. fl := rwFolder{
  1174. dbUpdates: make(chan dbUpdateJob, 1),
  1175. dir: "testdata",
  1176. }
  1177. fl.deleteDir(f, m)
  1178. if _, err := os.Stat("testdata/issue3164"); !os.IsNotExist(err) {
  1179. t.Fatal(err)
  1180. }
  1181. }
  1182. func TestScanNoDatabaseWrite(t *testing.T) {
  1183. // When scanning, nothing should be committed to database unless
  1184. // something actually changed.
  1185. db := db.OpenMemory()
  1186. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1187. m.AddFolder(defaultFolderConfig)
  1188. m.StartFolder("default")
  1189. m.ServeBackground()
  1190. // Start with no ignores, and restore the previous state when the test completes
  1191. curIgn, _, err := m.GetIgnores("default")
  1192. if err != nil {
  1193. t.Fatal(err)
  1194. }
  1195. defer m.SetIgnores("default", curIgn)
  1196. m.SetIgnores("default", nil)
  1197. // Scan the folder twice. The second scan should be a no-op database wise
  1198. m.ScanFolder("default")
  1199. c0 := db.Committed()
  1200. m.ScanFolder("default")
  1201. c1 := db.Committed()
  1202. if c1 != c0 {
  1203. t.Errorf("scan should not commit data when nothing changed but %d != %d", c1, c0)
  1204. }
  1205. // Ignore a file we know exists. It'll be updated in the database.
  1206. m.SetIgnores("default", []string{"foo"})
  1207. m.ScanFolder("default")
  1208. c2 := db.Committed()
  1209. if c2 <= c1 {
  1210. t.Errorf("scan should commit data when something got ignored but %d <= %d", c2, c1)
  1211. }
  1212. // Scan again. Nothing should happen.
  1213. m.ScanFolder("default")
  1214. c3 := db.Committed()
  1215. if c3 != c2 {
  1216. t.Errorf("scan should not commit data when nothing changed (with ignores) but %d != %d", c3, c2)
  1217. }
  1218. }
  1219. func TestIssue2782(t *testing.T) {
  1220. // CheckFolderHealth should accept a symlinked folder, when using tilde-expanded path.
  1221. if runtime.GOOS == "windows" {
  1222. t.Skip("not reliable on Windows")
  1223. return
  1224. }
  1225. home := os.Getenv("HOME")
  1226. if home == "" {
  1227. t.Skip("no home")
  1228. }
  1229. // Create the test env. Needs to be based on $HOME as tilde expansion is
  1230. // part of the issue. Skip the test if any of this fails, as we are a
  1231. // bit outside of our stated domain here...
  1232. testName := ".syncthing-test." + srand.String(16)
  1233. testDir := filepath.Join(home, testName)
  1234. if err := os.RemoveAll(testDir); err != nil {
  1235. t.Skip(err)
  1236. }
  1237. if err := osutil.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  1238. t.Skip(err)
  1239. }
  1240. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  1241. t.Skip(err)
  1242. }
  1243. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  1244. t.Skip(err)
  1245. }
  1246. defer os.RemoveAll(testDir)
  1247. db := db.OpenMemory()
  1248. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  1249. m.AddFolder(config.NewFolderConfiguration("default", "~/"+testName+"/synclink/"))
  1250. m.StartFolder("default")
  1251. m.ServeBackground()
  1252. defer m.Stop()
  1253. if err := m.ScanFolder("default"); err != nil {
  1254. t.Error("scan error:", err)
  1255. }
  1256. if err := m.CheckFolderHealth("default"); err != nil {
  1257. t.Error("health check error:", err)
  1258. }
  1259. }
  1260. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  1261. dbi := db.OpenMemory()
  1262. files := db.NewFileSet("default", dbi)
  1263. files.Replace(device1, genFiles(1))
  1264. files.Replace(device2, genFiles(1))
  1265. if len(files.ListDevices()) != 2 {
  1266. t.Error("expected two devices")
  1267. }
  1268. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1269. m.AddFolder(defaultFolderConfig)
  1270. m.StartFolder("default")
  1271. // Remote sequence is cached, hence need to recreated.
  1272. files = db.NewFileSet("default", dbi)
  1273. if len(files.ListDevices()) != 1 {
  1274. t.Error("Expected one device")
  1275. }
  1276. }
  1277. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  1278. dbi := db.OpenMemory()
  1279. fcfg := config.NewFolderConfiguration("default", "testdata")
  1280. fcfg.Devices = []config.FolderDeviceConfiguration{
  1281. {DeviceID: device1},
  1282. {DeviceID: device2},
  1283. }
  1284. cfg := config.Configuration{
  1285. Folders: []config.FolderConfiguration{fcfg},
  1286. Devices: []config.DeviceConfiguration{
  1287. config.NewDeviceConfiguration(device1, "device1"),
  1288. config.NewDeviceConfiguration(device2, "device2"),
  1289. },
  1290. Options: config.OptionsConfiguration{
  1291. // Don't remove temporaries directly on startup
  1292. KeepTemporariesH: 1,
  1293. },
  1294. }
  1295. wcfg := config.Wrap("/tmp/test", cfg)
  1296. d2c := &fakeConn{}
  1297. m := NewModel(wcfg, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1298. m.AddFolder(fcfg)
  1299. m.StartFolder(fcfg.ID)
  1300. m.ServeBackground()
  1301. conn1 := connections.Connection{
  1302. IntermediateConnection: connections.IntermediateConnection{
  1303. Conn: tls.Client(&fakeConn{}, nil),
  1304. Type: "foo",
  1305. Priority: 10,
  1306. },
  1307. Connection: &FakeConnection{
  1308. id: device1,
  1309. },
  1310. }
  1311. m.AddConnection(conn1, protocol.HelloResult{})
  1312. conn2 := connections.Connection{
  1313. IntermediateConnection: connections.IntermediateConnection{
  1314. Conn: tls.Client(d2c, nil),
  1315. Type: "foo",
  1316. Priority: 10,
  1317. },
  1318. Connection: &FakeConnection{
  1319. id: device2,
  1320. },
  1321. }
  1322. m.AddConnection(conn2, protocol.HelloResult{})
  1323. m.ClusterConfig(device1, protocol.ClusterConfig{
  1324. Folders: []protocol.Folder{
  1325. {
  1326. ID: "default",
  1327. Devices: []protocol.Device{
  1328. {ID: device1},
  1329. {ID: device2},
  1330. },
  1331. },
  1332. },
  1333. })
  1334. m.ClusterConfig(device2, protocol.ClusterConfig{
  1335. Folders: []protocol.Folder{
  1336. {
  1337. ID: "default",
  1338. Devices: []protocol.Device{
  1339. {ID: device1},
  1340. {ID: device2},
  1341. },
  1342. },
  1343. },
  1344. })
  1345. if !m.folderSharedWith("default", device1) {
  1346. t.Error("not shared with device1")
  1347. }
  1348. if !m.folderSharedWith("default", device2) {
  1349. t.Error("not shared with device2")
  1350. }
  1351. if d2c.closed {
  1352. t.Error("conn already closed")
  1353. }
  1354. cfg = cfg.Copy()
  1355. cfg.Devices = cfg.Devices[:1]
  1356. if err := wcfg.Replace(cfg); err != nil {
  1357. t.Error(err)
  1358. }
  1359. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  1360. if !m.folderSharedWith("default", device1) {
  1361. t.Error("not shared with device1")
  1362. }
  1363. if m.folderSharedWith("default", device2) { // checks m.deviceFolders
  1364. t.Error("shared with device2")
  1365. }
  1366. if !d2c.closed {
  1367. t.Error("connection not closed")
  1368. }
  1369. if _, ok := wcfg.Devices()[device2]; ok {
  1370. t.Error("device still in config")
  1371. }
  1372. fdevs, ok := m.folderDevices["default"]
  1373. if !ok {
  1374. t.Error("folder missing?")
  1375. }
  1376. for _, id := range fdevs {
  1377. if id == device2 {
  1378. t.Error("still there")
  1379. }
  1380. }
  1381. if _, ok := m.conn[device2]; !ok {
  1382. t.Error("conn missing early")
  1383. }
  1384. if _, ok := m.helloMessages[device2]; !ok {
  1385. t.Error("hello missing early")
  1386. }
  1387. if _, ok := m.deviceDownloads[device2]; !ok {
  1388. t.Error("downloads missing early")
  1389. }
  1390. m.Closed(conn2, fmt.Errorf("foo"))
  1391. if _, ok := m.conn[device2]; ok {
  1392. t.Error("conn not missing")
  1393. }
  1394. if _, ok := m.helloMessages[device2]; ok {
  1395. t.Error("hello not missing")
  1396. }
  1397. if _, ok := m.deviceDownloads[device2]; ok {
  1398. t.Error("downloads not missing")
  1399. }
  1400. }
  1401. func TestIssue3496(t *testing.T) {
  1402. // It seems like lots of deleted files can cause negative completion
  1403. // percentages. Lets make sure that doesn't happen. Also do some general
  1404. // checks on the completion calculation stuff.
  1405. dbi := db.OpenMemory()
  1406. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", dbi, nil)
  1407. m.AddFolder(defaultFolderConfig)
  1408. m.StartFolder("default")
  1409. m.ServeBackground()
  1410. defer m.Stop()
  1411. m.ScanFolder("default")
  1412. addFakeConn(m, device1)
  1413. addFakeConn(m, device2)
  1414. // Reach into the model and grab the current file list...
  1415. m.fmut.RLock()
  1416. fs := m.folderFiles["default"]
  1417. m.fmut.RUnlock()
  1418. var localFiles []protocol.FileInfo
  1419. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  1420. localFiles = append(localFiles, i.(protocol.FileInfo))
  1421. return true
  1422. })
  1423. // Mark all files as deleted and fake it as update from device1
  1424. for i := range localFiles {
  1425. localFiles[i].Deleted = true
  1426. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  1427. localFiles[i].Blocks = nil
  1428. }
  1429. // Also add a small file that we're supposed to need, or the global size
  1430. // stuff will bail out early due to the entire folder being zero size.
  1431. localFiles = append(localFiles, protocol.FileInfo{
  1432. Name: "fake",
  1433. Size: 1234,
  1434. Type: protocol.FileInfoTypeFile,
  1435. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  1436. })
  1437. m.IndexUpdate(device1, "default", localFiles)
  1438. // Check that the completion percentage for us makes sense
  1439. comp := m.Completion(protocol.LocalDeviceID, "default")
  1440. if comp.NeedBytes > comp.GlobalBytes {
  1441. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  1442. }
  1443. if comp.CompletionPct < 0 {
  1444. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  1445. }
  1446. if comp.NeedBytes == 0 {
  1447. t.Error("Need no bytes even though some files are deleted")
  1448. }
  1449. if comp.CompletionPct == 100 {
  1450. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  1451. }
  1452. t.Log(comp)
  1453. // Check that NeedSize does the correct thing
  1454. need := m.NeedSize("default")
  1455. if need.Files != 1 || need.Bytes != 1234 {
  1456. // The one we added synthetically above
  1457. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  1458. }
  1459. if need.Deleted != len(localFiles)-1 {
  1460. // The rest
  1461. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  1462. }
  1463. }
  1464. func addFakeConn(m *Model, dev protocol.DeviceID) {
  1465. conn1 := connections.Connection{
  1466. IntermediateConnection: connections.IntermediateConnection{
  1467. Conn: tls.Client(&fakeConn{}, nil),
  1468. Type: "foo",
  1469. Priority: 10,
  1470. },
  1471. Connection: &FakeConnection{
  1472. id: dev,
  1473. },
  1474. }
  1475. m.AddConnection(conn1, protocol.HelloResult{})
  1476. m.ClusterConfig(device1, protocol.ClusterConfig{
  1477. Folders: []protocol.Folder{
  1478. {
  1479. ID: "default",
  1480. Devices: []protocol.Device{
  1481. {ID: device1},
  1482. {ID: device2},
  1483. },
  1484. },
  1485. },
  1486. })
  1487. }
  1488. type fakeAddr struct{}
  1489. func (fakeAddr) Network() string {
  1490. return "network"
  1491. }
  1492. func (fakeAddr) String() string {
  1493. return "address"
  1494. }
  1495. type fakeConn struct {
  1496. closed bool
  1497. }
  1498. func (c *fakeConn) Close() error {
  1499. c.closed = true
  1500. return nil
  1501. }
  1502. func (fakeConn) LocalAddr() net.Addr {
  1503. return &fakeAddr{}
  1504. }
  1505. func (fakeConn) RemoteAddr() net.Addr {
  1506. return &fakeAddr{}
  1507. }
  1508. func (fakeConn) Read([]byte) (int, error) {
  1509. return 0, nil
  1510. }
  1511. func (fakeConn) Write([]byte) (int, error) {
  1512. return 0, nil
  1513. }
  1514. func (fakeConn) SetDeadline(time.Time) error {
  1515. return nil
  1516. }
  1517. func (fakeConn) SetReadDeadline(time.Time) error {
  1518. return nil
  1519. }
  1520. func (fakeConn) SetWriteDeadline(time.Time) error {
  1521. return nil
  1522. }