config_test.go 16 KB

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