config_test.go 15 KB

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