model_test.go 37 KB

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