model_test.go 40 KB

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