config_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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 config
  7. import (
  8. "bytes"
  9. "encoding/json"
  10. "fmt"
  11. "os"
  12. "path/filepath"
  13. "runtime"
  14. "strings"
  15. "testing"
  16. "github.com/d4l3k/messagediff"
  17. "github.com/syncthing/syncthing/lib/protocol"
  18. )
  19. var device1, device2, device3, device4 protocol.DeviceID
  20. func init() {
  21. device1, _ = protocol.DeviceIDFromString("AIR6LPZ7K4PTTUXQSMUUCPQ5YWOEDFIIQJUG7772YQXXR5YD6AWQ")
  22. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  23. device3, _ = protocol.DeviceIDFromString("LGFPDIT-7SKNNJL-VJZA4FC-7QNCRKA-CE753K7-2BW5QDK-2FOZ7FR-FEP57QJ")
  24. device4, _ = protocol.DeviceIDFromString("P56IOI7-MZJNU2Y-IQGDREY-DM2MGTI-MGL3BXN-PQ6W5BM-TBBZ4TJ-XZWICQ2")
  25. }
  26. func TestDefaultValues(t *testing.T) {
  27. expected := OptionsConfiguration{
  28. ListenAddress: []string{"tcp://0.0.0.0:22000"},
  29. GlobalAnnServers: []string{"default"},
  30. GlobalAnnEnabled: true,
  31. LocalAnnEnabled: true,
  32. LocalAnnPort: 21027,
  33. LocalAnnMCAddr: "[ff12::8384]:21027",
  34. RelayServers: []string{"dynamic+https://relays.syncthing.net/endpoint"},
  35. MaxSendKbps: 0,
  36. MaxRecvKbps: 0,
  37. ReconnectIntervalS: 60,
  38. RelaysEnabled: true,
  39. RelayReconnectIntervalM: 10,
  40. StartBrowser: true,
  41. NATEnabled: true,
  42. NATLeaseM: 60,
  43. NATRenewalM: 30,
  44. NATTimeoutS: 10,
  45. RestartOnWakeup: true,
  46. AutoUpgradeIntervalH: 12,
  47. KeepTemporariesH: 24,
  48. CacheIgnoredFiles: false,
  49. ProgressUpdateIntervalS: 5,
  50. SymlinksEnabled: true,
  51. LimitBandwidthInLan: false,
  52. MinHomeDiskFreePct: 1,
  53. URURL: "https://data.syncthing.net/newdata",
  54. URInitialDelayS: 1800,
  55. URPostInsecurely: false,
  56. ReleasesURL: "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30",
  57. AlwaysLocalNets: []string{},
  58. OverwriteNames: false,
  59. TempIndexMinBlocks: 10,
  60. }
  61. cfg := New(device1)
  62. if diff, equal := messagediff.PrettyDiff(expected, cfg.Options); !equal {
  63. t.Errorf("Default config differs. Diff:\n%s", diff)
  64. }
  65. }
  66. func TestDeviceConfig(t *testing.T) {
  67. for i := OldestHandledVersion; i <= CurrentVersion; i++ {
  68. os.Remove("testdata/.stfolder")
  69. wr, err := Load(fmt.Sprintf("testdata/v%d.xml", i), device1)
  70. if err != nil {
  71. t.Fatal(err)
  72. }
  73. _, err = os.Stat("testdata/.stfolder")
  74. if i < 6 && err != nil {
  75. t.Fatal(err)
  76. } else if i >= 6 && err == nil {
  77. t.Fatal("Unexpected file")
  78. }
  79. cfg := wr.cfg
  80. expectedFolders := []FolderConfiguration{
  81. {
  82. ID: "test",
  83. RawPath: "testdata",
  84. Devices: []FolderDeviceConfiguration{{DeviceID: device1}, {DeviceID: device4}},
  85. Type: FolderTypeReadOnly,
  86. RescanIntervalS: 600,
  87. Copiers: 0,
  88. Pullers: 0,
  89. Hashers: 0,
  90. AutoNormalize: true,
  91. MinDiskFreePct: 1,
  92. MaxConflicts: -1,
  93. },
  94. }
  95. // The cachedPath will have been resolved to an absolute path,
  96. // depending on where the tests are running. Zero it out so we don't
  97. // fail based on that.
  98. for i := range cfg.Folders {
  99. cfg.Folders[i].cachedPath = ""
  100. }
  101. if runtime.GOOS != "windows" {
  102. expectedFolders[0].RawPath += string(filepath.Separator)
  103. }
  104. expectedDevices := []DeviceConfiguration{
  105. {
  106. DeviceID: device1,
  107. Name: "node one",
  108. Addresses: []string{"tcp://a"},
  109. Compression: protocol.CompressMetadata,
  110. },
  111. {
  112. DeviceID: device4,
  113. Name: "node two",
  114. Addresses: []string{"tcp://b"},
  115. Compression: protocol.CompressMetadata,
  116. },
  117. }
  118. expectedDeviceIDs := []protocol.DeviceID{device1, device4}
  119. if cfg.Version != CurrentVersion {
  120. t.Errorf("%d: Incorrect version %d != %d", i, cfg.Version, CurrentVersion)
  121. }
  122. if diff, equal := messagediff.PrettyDiff(expectedFolders, cfg.Folders); !equal {
  123. t.Errorf("%d: Incorrect Folders. Diff:\n%s", i, diff)
  124. }
  125. if diff, equal := messagediff.PrettyDiff(expectedDevices, cfg.Devices); !equal {
  126. t.Errorf("%d: Incorrect Devices. Diff:\n%s", i, diff)
  127. }
  128. if diff, equal := messagediff.PrettyDiff(expectedDeviceIDs, cfg.Folders[0].DeviceIDs()); !equal {
  129. t.Errorf("%d: Incorrect DeviceIDs. Diff:\n%s", i, diff)
  130. }
  131. }
  132. }
  133. func TestNoListenAddress(t *testing.T) {
  134. cfg, err := Load("testdata/nolistenaddress.xml", device1)
  135. if err != nil {
  136. t.Error(err)
  137. }
  138. expected := []string{""}
  139. actual := cfg.Options().ListenAddress
  140. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  141. t.Errorf("Unexpected ListenAddress. Diff:\n%s", diff)
  142. }
  143. }
  144. func TestOverriddenValues(t *testing.T) {
  145. expected := OptionsConfiguration{
  146. ListenAddress: []string{"tcp://:23000"},
  147. GlobalAnnServers: []string{"udp4://syncthing.nym.se:22026"},
  148. GlobalAnnEnabled: false,
  149. LocalAnnEnabled: false,
  150. LocalAnnPort: 42123,
  151. LocalAnnMCAddr: "quux:3232",
  152. RelayServers: []string{"relay://123.123.123.123:1234", "relay://125.125.125.125:1255"},
  153. MaxSendKbps: 1234,
  154. MaxRecvKbps: 2341,
  155. ReconnectIntervalS: 6000,
  156. RelaysEnabled: false,
  157. RelayReconnectIntervalM: 20,
  158. StartBrowser: false,
  159. NATEnabled: false,
  160. NATLeaseM: 90,
  161. NATRenewalM: 15,
  162. NATTimeoutS: 15,
  163. RestartOnWakeup: false,
  164. AutoUpgradeIntervalH: 24,
  165. KeepTemporariesH: 48,
  166. CacheIgnoredFiles: true,
  167. ProgressUpdateIntervalS: 10,
  168. SymlinksEnabled: false,
  169. LimitBandwidthInLan: true,
  170. MinHomeDiskFreePct: 5.2,
  171. URURL: "https://localhost/newdata",
  172. URInitialDelayS: 800,
  173. URPostInsecurely: true,
  174. ReleasesURL: "https://localhost/releases",
  175. AlwaysLocalNets: []string{},
  176. OverwriteNames: true,
  177. TempIndexMinBlocks: 100,
  178. }
  179. cfg, err := Load("testdata/overridenvalues.xml", device1)
  180. if err != nil {
  181. t.Error(err)
  182. }
  183. if diff, equal := messagediff.PrettyDiff(expected, cfg.Options()); !equal {
  184. t.Errorf("Overridden config differs. Diff:\n%s", diff)
  185. }
  186. }
  187. func TestDeviceAddressesDynamic(t *testing.T) {
  188. name, _ := os.Hostname()
  189. expected := map[protocol.DeviceID]DeviceConfiguration{
  190. device1: {
  191. DeviceID: device1,
  192. Addresses: []string{"dynamic"},
  193. },
  194. device2: {
  195. DeviceID: device2,
  196. Addresses: []string{"dynamic"},
  197. },
  198. device3: {
  199. DeviceID: device3,
  200. Addresses: []string{"dynamic"},
  201. },
  202. device4: {
  203. DeviceID: device4,
  204. Name: name, // Set when auto created
  205. Addresses: []string{"dynamic"},
  206. Compression: protocol.CompressMetadata,
  207. },
  208. }
  209. cfg, err := Load("testdata/deviceaddressesdynamic.xml", device4)
  210. if err != nil {
  211. t.Error(err)
  212. }
  213. actual := cfg.Devices()
  214. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  215. t.Errorf("Devices differ. Diff:\n%s", diff)
  216. }
  217. }
  218. func TestDeviceCompression(t *testing.T) {
  219. name, _ := os.Hostname()
  220. expected := map[protocol.DeviceID]DeviceConfiguration{
  221. device1: {
  222. DeviceID: device1,
  223. Addresses: []string{"dynamic"},
  224. Compression: protocol.CompressMetadata,
  225. },
  226. device2: {
  227. DeviceID: device2,
  228. Addresses: []string{"dynamic"},
  229. Compression: protocol.CompressMetadata,
  230. },
  231. device3: {
  232. DeviceID: device3,
  233. Addresses: []string{"dynamic"},
  234. Compression: protocol.CompressNever,
  235. },
  236. device4: {
  237. DeviceID: device4,
  238. Name: name, // Set when auto created
  239. Addresses: []string{"dynamic"},
  240. Compression: protocol.CompressMetadata,
  241. },
  242. }
  243. cfg, err := Load("testdata/devicecompression.xml", device4)
  244. if err != nil {
  245. t.Error(err)
  246. }
  247. actual := cfg.Devices()
  248. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  249. t.Errorf("Devices differ. Diff:\n%s", diff)
  250. }
  251. }
  252. func TestDeviceAddressesStatic(t *testing.T) {
  253. name, _ := os.Hostname()
  254. expected := map[protocol.DeviceID]DeviceConfiguration{
  255. device1: {
  256. DeviceID: device1,
  257. Addresses: []string{"tcp://192.0.2.1", "tcp://192.0.2.2"},
  258. },
  259. device2: {
  260. DeviceID: device2,
  261. Addresses: []string{"tcp://192.0.2.3:6070", "tcp://[2001:db8::42]:4242"},
  262. },
  263. device3: {
  264. DeviceID: device3,
  265. Addresses: []string{"tcp://[2001:db8::44]:4444", "tcp://192.0.2.4:6090"},
  266. },
  267. device4: {
  268. DeviceID: device4,
  269. Name: name, // Set when auto created
  270. Addresses: []string{"dynamic"},
  271. Compression: protocol.CompressMetadata,
  272. },
  273. }
  274. cfg, err := Load("testdata/deviceaddressesstatic.xml", device4)
  275. if err != nil {
  276. t.Error(err)
  277. }
  278. actual := cfg.Devices()
  279. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  280. t.Errorf("Devices differ. Diff:\n%s", diff)
  281. }
  282. }
  283. func TestVersioningConfig(t *testing.T) {
  284. cfg, err := Load("testdata/versioningconfig.xml", device4)
  285. if err != nil {
  286. t.Error(err)
  287. }
  288. vc := cfg.Folders()["test"].Versioning
  289. if vc.Type != "simple" {
  290. t.Errorf(`vc.Type %q != "simple"`, vc.Type)
  291. }
  292. if l := len(vc.Params); l != 2 {
  293. t.Errorf("len(vc.Params) %d != 2", l)
  294. }
  295. expected := map[string]string{
  296. "foo": "bar",
  297. "baz": "quux",
  298. }
  299. if diff, equal := messagediff.PrettyDiff(expected, vc.Params); !equal {
  300. t.Errorf("vc.Params differ. Diff:\n%s", diff)
  301. }
  302. }
  303. func TestIssue1262(t *testing.T) {
  304. cfg, err := Load("testdata/issue-1262.xml", device4)
  305. if err != nil {
  306. t.Fatal(err)
  307. }
  308. actual := cfg.Folders()["test"].RawPath
  309. expected := "e:/"
  310. if runtime.GOOS == "windows" {
  311. expected = `e:\`
  312. }
  313. if actual != expected {
  314. t.Errorf("%q != %q", actual, expected)
  315. }
  316. }
  317. func TestIssue1750(t *testing.T) {
  318. cfg, err := Load("testdata/issue-1750.xml", device4)
  319. if err != nil {
  320. t.Fatal(err)
  321. }
  322. if cfg.Options().ListenAddress[0] != "tcp://:23000" {
  323. t.Errorf("%q != %q", cfg.Options().ListenAddress[0], "tcp://:23000")
  324. }
  325. if cfg.Options().ListenAddress[1] != "tcp://:23001" {
  326. t.Errorf("%q != %q", cfg.Options().ListenAddress[1], "tcp://:23001")
  327. }
  328. if cfg.Options().GlobalAnnServers[0] != "udp4://syncthing.nym.se:22026" {
  329. t.Errorf("%q != %q", cfg.Options().GlobalAnnServers[0], "udp4://syncthing.nym.se:22026")
  330. }
  331. if cfg.Options().GlobalAnnServers[1] != "udp4://syncthing.nym.se:22027" {
  332. t.Errorf("%q != %q", cfg.Options().GlobalAnnServers[1], "udp4://syncthing.nym.se:22027")
  333. }
  334. }
  335. func TestWindowsPaths(t *testing.T) {
  336. if runtime.GOOS != "windows" {
  337. t.Skip("Not useful on non-Windows")
  338. return
  339. }
  340. folder := FolderConfiguration{
  341. RawPath: `e:\`,
  342. }
  343. expected := `\\?\e:\`
  344. actual := folder.Path()
  345. if actual != expected {
  346. t.Errorf("%q != %q", actual, expected)
  347. }
  348. folder.RawPath = `\\192.0.2.22\network\share`
  349. expected = folder.RawPath
  350. actual = folder.Path()
  351. if actual != expected {
  352. t.Errorf("%q != %q", actual, expected)
  353. }
  354. folder.RawPath = `relative\path`
  355. expected = folder.RawPath
  356. actual = folder.Path()
  357. if actual == expected || !strings.HasPrefix(actual, "\\\\?\\") {
  358. t.Errorf("%q == %q, expected absolutification", actual, expected)
  359. }
  360. }
  361. func TestFolderPath(t *testing.T) {
  362. folder := FolderConfiguration{
  363. RawPath: "~/tmp",
  364. }
  365. realPath := folder.Path()
  366. if !filepath.IsAbs(realPath) {
  367. t.Error(realPath, "should be absolute")
  368. }
  369. if strings.Contains(realPath, "~") {
  370. t.Error(realPath, "should not contain ~")
  371. }
  372. }
  373. func TestNewSaveLoad(t *testing.T) {
  374. path := "testdata/temp.xml"
  375. os.Remove(path)
  376. exists := func(path string) bool {
  377. _, err := os.Stat(path)
  378. return err == nil
  379. }
  380. intCfg := New(device1)
  381. cfg := Wrap(path, intCfg)
  382. // To make the equality pass later
  383. cfg.cfg.XMLName.Local = "configuration"
  384. if exists(path) {
  385. t.Error(path, "exists")
  386. }
  387. err := cfg.Save()
  388. if err != nil {
  389. t.Error(err)
  390. }
  391. if !exists(path) {
  392. t.Error(path, "does not exist")
  393. }
  394. cfg2, err := Load(path, device1)
  395. if err != nil {
  396. t.Error(err)
  397. }
  398. if diff, equal := messagediff.PrettyDiff(cfg.Raw(), cfg2.Raw()); !equal {
  399. t.Errorf("Configs are not equal. Diff:\n%s", diff)
  400. }
  401. os.Remove(path)
  402. }
  403. func TestPrepare(t *testing.T) {
  404. var cfg Configuration
  405. if cfg.Folders != nil || cfg.Devices != nil || cfg.Options.ListenAddress != nil {
  406. t.Error("Expected nil")
  407. }
  408. cfg.prepare(device1)
  409. if cfg.Folders == nil || cfg.Devices == nil || cfg.Options.ListenAddress == nil {
  410. t.Error("Unexpected nil")
  411. }
  412. }
  413. func TestCopy(t *testing.T) {
  414. wrapper, err := Load("testdata/example.xml", device1)
  415. if err != nil {
  416. t.Fatal(err)
  417. }
  418. cfg := wrapper.Raw()
  419. bsOrig, err := json.MarshalIndent(cfg, "", " ")
  420. if err != nil {
  421. t.Fatal(err)
  422. }
  423. copy := cfg.Copy()
  424. cfg.Devices[0].Addresses[0] = "wrong"
  425. cfg.Folders[0].Devices[0].DeviceID = protocol.DeviceID{0, 1, 2, 3}
  426. cfg.Options.ListenAddress[0] = "wrong"
  427. cfg.GUI.APIKey = "wrong"
  428. bsChanged, err := json.MarshalIndent(cfg, "", " ")
  429. if err != nil {
  430. t.Fatal(err)
  431. }
  432. bsCopy, err := json.MarshalIndent(copy, "", " ")
  433. if err != nil {
  434. t.Fatal(err)
  435. }
  436. if bytes.Equal(bsOrig, bsChanged) {
  437. t.Error("Config should have changed")
  438. }
  439. if !bytes.Equal(bsOrig, bsCopy) {
  440. //ioutil.WriteFile("a", bsOrig, 0644)
  441. //ioutil.WriteFile("b", bsCopy, 0644)
  442. t.Error("Copy should be unchanged")
  443. }
  444. }
  445. func TestPullOrder(t *testing.T) {
  446. wrapper, err := Load("testdata/pullorder.xml", device1)
  447. if err != nil {
  448. t.Fatal(err)
  449. }
  450. folders := wrapper.Folders()
  451. expected := []struct {
  452. name string
  453. order PullOrder
  454. }{
  455. {"f1", OrderRandom}, // empty value, default
  456. {"f2", OrderRandom}, // explicit
  457. {"f3", OrderAlphabetic}, // explicit
  458. {"f4", OrderRandom}, // unknown value, default
  459. {"f5", OrderSmallestFirst}, // explicit
  460. {"f6", OrderLargestFirst}, // explicit
  461. {"f7", OrderOldestFirst}, // explicit
  462. {"f8", OrderNewestFirst}, // explicit
  463. }
  464. // Verify values are deserialized correctly
  465. for _, tc := range expected {
  466. if actual := folders[tc.name].Order; actual != tc.order {
  467. t.Errorf("Incorrect pull order for %q: %v != %v", tc.name, actual, tc.order)
  468. }
  469. }
  470. // Serialize and deserialize again to verify it survives the transformation
  471. buf := new(bytes.Buffer)
  472. cfg := wrapper.Raw()
  473. cfg.WriteXML(buf)
  474. t.Logf("%s", buf.Bytes())
  475. cfg, err = ReadXML(buf, device1)
  476. wrapper = Wrap("testdata/pullorder.xml", cfg)
  477. folders = wrapper.Folders()
  478. for _, tc := range expected {
  479. if actual := folders[tc.name].Order; actual != tc.order {
  480. t.Errorf("Incorrect pull order for %q: %v != %v", tc.name, actual, tc.order)
  481. }
  482. }
  483. }
  484. func TestLargeRescanInterval(t *testing.T) {
  485. wrapper, err := Load("testdata/largeinterval.xml", device1)
  486. if err != nil {
  487. t.Fatal(err)
  488. }
  489. if wrapper.Folders()["l1"].RescanIntervalS != MaxRescanIntervalS {
  490. t.Error("too large rescan interval should be maxed out")
  491. }
  492. if wrapper.Folders()["l2"].RescanIntervalS != 0 {
  493. t.Error("negative rescan interval should become zero")
  494. }
  495. }
  496. func TestGUIConfigURL(t *testing.T) {
  497. testcases := [][2]string{
  498. {"192.0.2.42:8080", "http://192.0.2.42:8080/"},
  499. {":8080", "http://127.0.0.1:8080/"},
  500. {"0.0.0.0:8080", "http://127.0.0.1:8080/"},
  501. {"127.0.0.1:8080", "http://127.0.0.1:8080/"},
  502. {"127.0.0.2:8080", "http://127.0.0.2:8080/"},
  503. {"[::]:8080", "http://[::1]:8080/"},
  504. {"[2001::42]:8080", "http://[2001::42]:8080/"},
  505. }
  506. for _, tc := range testcases {
  507. c := GUIConfiguration{
  508. RawAddress: tc[0],
  509. }
  510. u := c.URL()
  511. if u != tc[1] {
  512. t.Errorf("Incorrect URL %s != %s for addr %s", u, tc[1], tc[0])
  513. }
  514. }
  515. }
  516. func TestRemoveDuplicateDevicesFolders(t *testing.T) {
  517. wrapper, err := Load("testdata/duplicates.xml", device1)
  518. if err != nil {
  519. t.Fatal(err)
  520. }
  521. // All folders are loaded, but the duplicate ones are disabled.
  522. if l := len(wrapper.Raw().Folders); l != 3 {
  523. t.Errorf("Incorrect number of folders, %d != 3", l)
  524. }
  525. for i, f := range wrapper.Raw().Folders {
  526. if f.ID == "f1" && f.Invalid == "" {
  527. t.Errorf("Folder %d (%q) is not set invalid", i, f.ID)
  528. }
  529. }
  530. if l := len(wrapper.Raw().Devices); l != 3 {
  531. t.Errorf("Incorrect number of devices, %d != 3", l)
  532. }
  533. f := wrapper.Folders()["f2"]
  534. if l := len(f.Devices); l != 2 {
  535. t.Errorf("Incorrect number of folder devices, %d != 2", l)
  536. }
  537. }