config_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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 https://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "bytes"
  9. "encoding/json"
  10. "fmt"
  11. "io/ioutil"
  12. "os"
  13. "path/filepath"
  14. "reflect"
  15. "runtime"
  16. "sort"
  17. "strings"
  18. "testing"
  19. "github.com/d4l3k/messagediff"
  20. "github.com/syncthing/syncthing/lib/fs"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. )
  24. var device1, device2, device3, device4 protocol.DeviceID
  25. func init() {
  26. device1, _ = protocol.DeviceIDFromString("AIR6LPZ7K4PTTUXQSMUUCPQ5YWOEDFIIQJUG7772YQXXR5YD6AWQ")
  27. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  28. device3, _ = protocol.DeviceIDFromString("LGFPDIT-7SKNNJL-VJZA4FC-7QNCRKA-CE753K7-2BW5QDK-2FOZ7FR-FEP57QJ")
  29. device4, _ = protocol.DeviceIDFromString("P56IOI7-MZJNU2Y-IQGDREY-DM2MGTI-MGL3BXN-PQ6W5BM-TBBZ4TJ-XZWICQ2")
  30. }
  31. func TestDefaultValues(t *testing.T) {
  32. expected := OptionsConfiguration{
  33. ListenAddresses: []string{"default"},
  34. GlobalAnnServers: []string{"default"},
  35. GlobalAnnEnabled: true,
  36. LocalAnnEnabled: true,
  37. LocalAnnPort: 21027,
  38. LocalAnnMCAddr: "[ff12::8384]:21027",
  39. MaxSendKbps: 0,
  40. MaxRecvKbps: 0,
  41. ReconnectIntervalS: 60,
  42. RelaysEnabled: true,
  43. RelayReconnectIntervalM: 10,
  44. StartBrowser: true,
  45. NATEnabled: true,
  46. NATLeaseM: 60,
  47. NATRenewalM: 30,
  48. NATTimeoutS: 10,
  49. RestartOnWakeup: true,
  50. AutoUpgradeIntervalH: 12,
  51. KeepTemporariesH: 24,
  52. CacheIgnoredFiles: false,
  53. ProgressUpdateIntervalS: 5,
  54. LimitBandwidthInLan: false,
  55. MinHomeDiskFree: Size{1, "%"},
  56. URURL: "https://data.syncthing.net/newdata",
  57. URInitialDelayS: 1800,
  58. URPostInsecurely: false,
  59. ReleasesURL: "https://upgrades.syncthing.net/meta.json",
  60. AlwaysLocalNets: []string{},
  61. OverwriteRemoteDevNames: false,
  62. TempIndexMinBlocks: 10,
  63. UnackedNotificationIDs: []string{},
  64. WeakHashSelectionMethod: WeakHashAuto,
  65. StunKeepaliveS: 24,
  66. StunServers: []string{"default"},
  67. KCPCongestionControl: true,
  68. KCPReceiveWindowSize: 128,
  69. KCPSendWindowSize: 128,
  70. KCPUpdateIntervalMs: 25,
  71. KCPFastResend: false,
  72. DefaultFolderPath: "~",
  73. }
  74. cfg := New(device1)
  75. if diff, equal := messagediff.PrettyDiff(expected, cfg.Options); !equal {
  76. t.Errorf("Default config differs. Diff:\n%s", diff)
  77. }
  78. }
  79. func TestDeviceConfig(t *testing.T) {
  80. for i := OldestHandledVersion; i <= CurrentVersion; i++ {
  81. os.RemoveAll(filepath.Join("testdata", DefaultMarkerName))
  82. wr, err := Load(fmt.Sprintf("testdata/v%d.xml", i), device1)
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. _, err = os.Stat(filepath.Join("testdata", DefaultMarkerName))
  87. if i < 6 && err != nil {
  88. t.Fatal(err)
  89. } else if i >= 6 && err == nil {
  90. t.Fatal("Unexpected file")
  91. }
  92. cfg := wr.cfg
  93. expectedFolders := []FolderConfiguration{
  94. {
  95. ID: "test",
  96. FilesystemType: fs.FilesystemTypeBasic,
  97. Path: "testdata",
  98. Devices: []FolderDeviceConfiguration{{DeviceID: device1}, {DeviceID: device4}},
  99. Type: FolderTypeSendOnly,
  100. RescanIntervalS: 600,
  101. FSWatcherEnabled: false,
  102. FSWatcherDelayS: 10,
  103. Copiers: 0,
  104. Pullers: 0,
  105. Hashers: 0,
  106. AutoNormalize: true,
  107. MinDiskFree: Size{1, "%"},
  108. MaxConflicts: -1,
  109. Versioning: VersioningConfiguration{
  110. Params: map[string]string{},
  111. },
  112. WeakHashThresholdPct: 25,
  113. MarkerName: DefaultMarkerName,
  114. },
  115. }
  116. // The cachedFilesystem will have been resolved to an absolute path,
  117. // depending on where the tests are running. Zero it out so we don't
  118. // fail based on that.
  119. for i := range cfg.Folders {
  120. cfg.Folders[i].cachedFilesystem = nil
  121. }
  122. expectedDevices := []DeviceConfiguration{
  123. {
  124. DeviceID: device1,
  125. Name: "node one",
  126. Addresses: []string{"tcp://a"},
  127. Compression: protocol.CompressMetadata,
  128. AllowedNetworks: []string{},
  129. },
  130. {
  131. DeviceID: device4,
  132. Name: "node two",
  133. Addresses: []string{"tcp://b"},
  134. Compression: protocol.CompressMetadata,
  135. AllowedNetworks: []string{},
  136. },
  137. }
  138. expectedDeviceIDs := []protocol.DeviceID{device1, device4}
  139. if cfg.Version != CurrentVersion {
  140. t.Errorf("%d: Incorrect version %d != %d", i, cfg.Version, CurrentVersion)
  141. }
  142. if diff, equal := messagediff.PrettyDiff(expectedFolders, cfg.Folders); !equal {
  143. t.Errorf("%d: Incorrect Folders. Diff:\n%s", i, diff)
  144. }
  145. if diff, equal := messagediff.PrettyDiff(expectedDevices, cfg.Devices); !equal {
  146. t.Errorf("%d: Incorrect Devices. Diff:\n%s", i, diff)
  147. }
  148. if diff, equal := messagediff.PrettyDiff(expectedDeviceIDs, cfg.Folders[0].DeviceIDs()); !equal {
  149. t.Errorf("%d: Incorrect DeviceIDs. Diff:\n%s", i, diff)
  150. }
  151. }
  152. }
  153. func TestNoListenAddresses(t *testing.T) {
  154. cfg, err := Load("testdata/nolistenaddress.xml", device1)
  155. if err != nil {
  156. t.Error(err)
  157. }
  158. expected := []string{""}
  159. actual := cfg.Options().ListenAddresses
  160. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  161. t.Errorf("Unexpected ListenAddresses. Diff:\n%s", diff)
  162. }
  163. }
  164. func TestOverriddenValues(t *testing.T) {
  165. expected := OptionsConfiguration{
  166. ListenAddresses: []string{"tcp://:23000"},
  167. GlobalAnnServers: []string{"udp4://syncthing.nym.se:22026"},
  168. GlobalAnnEnabled: false,
  169. LocalAnnEnabled: false,
  170. LocalAnnPort: 42123,
  171. LocalAnnMCAddr: "quux:3232",
  172. MaxSendKbps: 1234,
  173. MaxRecvKbps: 2341,
  174. ReconnectIntervalS: 6000,
  175. RelaysEnabled: false,
  176. RelayReconnectIntervalM: 20,
  177. StartBrowser: false,
  178. NATEnabled: false,
  179. NATLeaseM: 90,
  180. NATRenewalM: 15,
  181. NATTimeoutS: 15,
  182. RestartOnWakeup: false,
  183. AutoUpgradeIntervalH: 24,
  184. KeepTemporariesH: 48,
  185. CacheIgnoredFiles: true,
  186. ProgressUpdateIntervalS: 10,
  187. LimitBandwidthInLan: true,
  188. MinHomeDiskFree: Size{5.2, "%"},
  189. URSeen: 2,
  190. URURL: "https://localhost/newdata",
  191. URInitialDelayS: 800,
  192. URPostInsecurely: true,
  193. ReleasesURL: "https://localhost/releases",
  194. AlwaysLocalNets: []string{},
  195. OverwriteRemoteDevNames: true,
  196. TempIndexMinBlocks: 100,
  197. UnackedNotificationIDs: []string{
  198. "channelNotification", // added in 17->18 migration
  199. },
  200. WeakHashSelectionMethod: WeakHashNever,
  201. StunKeepaliveS: 10,
  202. StunServers: []string{"a.stun.com", "b.stun.com"},
  203. KCPCongestionControl: false,
  204. KCPReceiveWindowSize: 1280,
  205. KCPSendWindowSize: 1280,
  206. KCPUpdateIntervalMs: 1000,
  207. KCPFastResend: true,
  208. DefaultFolderPath: "/media/syncthing",
  209. }
  210. os.Unsetenv("STNOUPGRADE")
  211. cfg, err := Load("testdata/overridenvalues.xml", device1)
  212. if err != nil {
  213. t.Error(err)
  214. }
  215. if diff, equal := messagediff.PrettyDiff(expected, cfg.Options()); !equal {
  216. t.Errorf("Overridden config differs. Diff:\n%s", diff)
  217. }
  218. }
  219. func TestDeviceAddressesDynamic(t *testing.T) {
  220. name, _ := os.Hostname()
  221. expected := map[protocol.DeviceID]DeviceConfiguration{
  222. device1: {
  223. DeviceID: device1,
  224. Addresses: []string{"dynamic"},
  225. AllowedNetworks: []string{},
  226. },
  227. device2: {
  228. DeviceID: device2,
  229. Addresses: []string{"dynamic"},
  230. AllowedNetworks: []string{},
  231. },
  232. device3: {
  233. DeviceID: device3,
  234. Addresses: []string{"dynamic"},
  235. AllowedNetworks: []string{},
  236. },
  237. device4: {
  238. DeviceID: device4,
  239. Name: name, // Set when auto created
  240. Addresses: []string{"dynamic"},
  241. Compression: protocol.CompressMetadata,
  242. AllowedNetworks: []string{},
  243. },
  244. }
  245. cfg, err := Load("testdata/deviceaddressesdynamic.xml", device4)
  246. if err != nil {
  247. t.Error(err)
  248. }
  249. actual := cfg.Devices()
  250. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  251. t.Errorf("Devices differ. Diff:\n%s", diff)
  252. }
  253. }
  254. func TestDeviceCompression(t *testing.T) {
  255. name, _ := os.Hostname()
  256. expected := map[protocol.DeviceID]DeviceConfiguration{
  257. device1: {
  258. DeviceID: device1,
  259. Addresses: []string{"dynamic"},
  260. Compression: protocol.CompressMetadata,
  261. AllowedNetworks: []string{},
  262. },
  263. device2: {
  264. DeviceID: device2,
  265. Addresses: []string{"dynamic"},
  266. Compression: protocol.CompressMetadata,
  267. AllowedNetworks: []string{},
  268. },
  269. device3: {
  270. DeviceID: device3,
  271. Addresses: []string{"dynamic"},
  272. Compression: protocol.CompressNever,
  273. AllowedNetworks: []string{},
  274. },
  275. device4: {
  276. DeviceID: device4,
  277. Name: name, // Set when auto created
  278. Addresses: []string{"dynamic"},
  279. Compression: protocol.CompressMetadata,
  280. AllowedNetworks: []string{},
  281. },
  282. }
  283. cfg, err := Load("testdata/devicecompression.xml", device4)
  284. if err != nil {
  285. t.Error(err)
  286. }
  287. actual := cfg.Devices()
  288. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  289. t.Errorf("Devices differ. Diff:\n%s", diff)
  290. }
  291. }
  292. func TestDeviceAddressesStatic(t *testing.T) {
  293. name, _ := os.Hostname()
  294. expected := map[protocol.DeviceID]DeviceConfiguration{
  295. device1: {
  296. DeviceID: device1,
  297. Addresses: []string{"tcp://192.0.2.1", "tcp://192.0.2.2"},
  298. AllowedNetworks: []string{},
  299. },
  300. device2: {
  301. DeviceID: device2,
  302. Addresses: []string{"tcp://192.0.2.3:6070", "tcp://[2001:db8::42]:4242"},
  303. AllowedNetworks: []string{},
  304. },
  305. device3: {
  306. DeviceID: device3,
  307. Addresses: []string{"tcp://[2001:db8::44]:4444", "tcp://192.0.2.4:6090"},
  308. AllowedNetworks: []string{},
  309. },
  310. device4: {
  311. DeviceID: device4,
  312. Name: name, // Set when auto created
  313. Addresses: []string{"dynamic"},
  314. Compression: protocol.CompressMetadata,
  315. AllowedNetworks: []string{},
  316. },
  317. }
  318. cfg, err := Load("testdata/deviceaddressesstatic.xml", device4)
  319. if err != nil {
  320. t.Error(err)
  321. }
  322. actual := cfg.Devices()
  323. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  324. t.Errorf("Devices differ. Diff:\n%s", diff)
  325. }
  326. }
  327. func TestVersioningConfig(t *testing.T) {
  328. cfg, err := Load("testdata/versioningconfig.xml", device4)
  329. if err != nil {
  330. t.Error(err)
  331. }
  332. vc := cfg.Folders()["test"].Versioning
  333. if vc.Type != "simple" {
  334. t.Errorf(`vc.Type %q != "simple"`, vc.Type)
  335. }
  336. if l := len(vc.Params); l != 2 {
  337. t.Errorf("len(vc.Params) %d != 2", l)
  338. }
  339. expected := map[string]string{
  340. "foo": "bar",
  341. "baz": "quux",
  342. }
  343. if diff, equal := messagediff.PrettyDiff(expected, vc.Params); !equal {
  344. t.Errorf("vc.Params differ. Diff:\n%s", diff)
  345. }
  346. }
  347. func TestIssue1262(t *testing.T) {
  348. if runtime.GOOS != "windows" {
  349. t.Skipf("path gets converted to absolute as part of the filesystem initialization on linux")
  350. }
  351. cfg, err := Load("testdata/issue-1262.xml", device4)
  352. if err != nil {
  353. t.Fatal(err)
  354. }
  355. actual := cfg.Folders()["test"].Filesystem().URI()
  356. expected := `e:\`
  357. if actual != expected {
  358. t.Errorf("%q != %q", actual, expected)
  359. }
  360. }
  361. func TestIssue1750(t *testing.T) {
  362. cfg, err := Load("testdata/issue-1750.xml", device4)
  363. if err != nil {
  364. t.Fatal(err)
  365. }
  366. if cfg.Options().ListenAddresses[0] != "tcp://:23000" {
  367. t.Errorf("%q != %q", cfg.Options().ListenAddresses[0], "tcp://:23000")
  368. }
  369. if cfg.Options().ListenAddresses[1] != "tcp://:23001" {
  370. t.Errorf("%q != %q", cfg.Options().ListenAddresses[1], "tcp://:23001")
  371. }
  372. if cfg.Options().GlobalAnnServers[0] != "udp4://syncthing.nym.se:22026" {
  373. t.Errorf("%q != %q", cfg.Options().GlobalAnnServers[0], "udp4://syncthing.nym.se:22026")
  374. }
  375. if cfg.Options().GlobalAnnServers[1] != "udp4://syncthing.nym.se:22027" {
  376. t.Errorf("%q != %q", cfg.Options().GlobalAnnServers[1], "udp4://syncthing.nym.se:22027")
  377. }
  378. }
  379. func TestFolderPath(t *testing.T) {
  380. folder := FolderConfiguration{
  381. Path: "~/tmp",
  382. }
  383. realPath := folder.Filesystem().URI()
  384. if !filepath.IsAbs(realPath) {
  385. t.Error(realPath, "should be absolute")
  386. }
  387. if strings.Contains(realPath, "~") {
  388. t.Error(realPath, "should not contain ~")
  389. }
  390. }
  391. func TestFolderCheckPath(t *testing.T) {
  392. n, err := ioutil.TempDir("", "")
  393. if err != nil {
  394. t.Fatal(err)
  395. }
  396. err = os.MkdirAll(filepath.Join(n, "dir", ".stfolder"), os.FileMode(0777))
  397. if err != nil {
  398. t.Fatal(err)
  399. }
  400. testcases := []struct {
  401. path string
  402. err error
  403. }{
  404. {
  405. path: "",
  406. err: errMarkerMissing,
  407. },
  408. {
  409. path: "does not exist",
  410. err: errPathMissing,
  411. },
  412. {
  413. path: "dir",
  414. err: nil,
  415. },
  416. }
  417. err = osutil.DebugSymlinkForTestsOnly(filepath.Join(n, "dir"), filepath.Join(n, "link"))
  418. if err == nil {
  419. t.Log("running with symlink check")
  420. testcases = append(testcases, struct {
  421. path string
  422. err error
  423. }{
  424. path: "link",
  425. err: nil,
  426. })
  427. } else if runtime.GOOS != "windows" {
  428. t.Log("running without symlink check")
  429. t.Fatal(err)
  430. }
  431. for _, testcase := range testcases {
  432. cfg := FolderConfiguration{
  433. Path: filepath.Join(n, testcase.path),
  434. MarkerName: DefaultMarkerName,
  435. }
  436. if err := cfg.CheckPath(); testcase.err != err {
  437. t.Errorf("unexpected error in case %s: %s != %s", testcase.path, err, testcase.err)
  438. }
  439. }
  440. }
  441. func TestNewSaveLoad(t *testing.T) {
  442. path := "testdata/temp.xml"
  443. os.Remove(path)
  444. exists := func(path string) bool {
  445. _, err := os.Stat(path)
  446. return err == nil
  447. }
  448. intCfg := New(device1)
  449. cfg := Wrap(path, intCfg)
  450. // To make the equality pass later
  451. cfg.cfg.XMLName.Local = "configuration"
  452. if exists(path) {
  453. t.Error(path, "exists")
  454. }
  455. err := cfg.Save()
  456. if err != nil {
  457. t.Error(err)
  458. }
  459. if !exists(path) {
  460. t.Error(path, "does not exist")
  461. }
  462. cfg2, err := Load(path, device1)
  463. if err != nil {
  464. t.Error(err)
  465. }
  466. if diff, equal := messagediff.PrettyDiff(cfg.RawCopy(), cfg2.RawCopy()); !equal {
  467. t.Errorf("Configs are not equal. Diff:\n%s", diff)
  468. }
  469. os.Remove(path)
  470. }
  471. func TestPrepare(t *testing.T) {
  472. var cfg Configuration
  473. if cfg.Folders != nil || cfg.Devices != nil || cfg.Options.ListenAddresses != nil {
  474. t.Error("Expected nil")
  475. }
  476. cfg.prepare(device1)
  477. if cfg.Folders == nil || cfg.Devices == nil || cfg.Options.ListenAddresses == nil {
  478. t.Error("Unexpected nil")
  479. }
  480. }
  481. func TestCopy(t *testing.T) {
  482. wrapper, err := Load("testdata/example.xml", device1)
  483. if err != nil {
  484. t.Fatal(err)
  485. }
  486. cfg := wrapper.RawCopy()
  487. bsOrig, err := json.MarshalIndent(cfg, "", " ")
  488. if err != nil {
  489. t.Fatal(err)
  490. }
  491. copy := cfg.Copy()
  492. cfg.Devices[0].Addresses[0] = "wrong"
  493. cfg.Folders[0].Devices[0].DeviceID = protocol.DeviceID{0, 1, 2, 3}
  494. cfg.Options.ListenAddresses[0] = "wrong"
  495. cfg.GUI.APIKey = "wrong"
  496. bsChanged, err := json.MarshalIndent(cfg, "", " ")
  497. if err != nil {
  498. t.Fatal(err)
  499. }
  500. bsCopy, err := json.MarshalIndent(copy, "", " ")
  501. if err != nil {
  502. t.Fatal(err)
  503. }
  504. if bytes.Equal(bsOrig, bsChanged) {
  505. t.Error("Config should have changed")
  506. }
  507. if !bytes.Equal(bsOrig, bsCopy) {
  508. //ioutil.WriteFile("a", bsOrig, 0644)
  509. //ioutil.WriteFile("b", bsCopy, 0644)
  510. t.Error("Copy should be unchanged")
  511. }
  512. }
  513. func TestPullOrder(t *testing.T) {
  514. wrapper, err := Load("testdata/pullorder.xml", device1)
  515. if err != nil {
  516. t.Fatal(err)
  517. }
  518. folders := wrapper.Folders()
  519. expected := []struct {
  520. name string
  521. order PullOrder
  522. }{
  523. {"f1", OrderRandom}, // empty value, default
  524. {"f2", OrderRandom}, // explicit
  525. {"f3", OrderAlphabetic}, // explicit
  526. {"f4", OrderRandom}, // unknown value, default
  527. {"f5", OrderSmallestFirst}, // explicit
  528. {"f6", OrderLargestFirst}, // explicit
  529. {"f7", OrderOldestFirst}, // explicit
  530. {"f8", OrderNewestFirst}, // explicit
  531. }
  532. // Verify values are deserialized correctly
  533. for _, tc := range expected {
  534. if actual := folders[tc.name].Order; actual != tc.order {
  535. t.Errorf("Incorrect pull order for %q: %v != %v", tc.name, actual, tc.order)
  536. }
  537. }
  538. // Serialize and deserialize again to verify it survives the transformation
  539. buf := new(bytes.Buffer)
  540. cfg := wrapper.RawCopy()
  541. cfg.WriteXML(buf)
  542. t.Logf("%s", buf.Bytes())
  543. cfg, err = ReadXML(buf, device1)
  544. if err != nil {
  545. t.Fatal(err)
  546. }
  547. wrapper = Wrap("testdata/pullorder.xml", cfg)
  548. folders = wrapper.Folders()
  549. for _, tc := range expected {
  550. if actual := folders[tc.name].Order; actual != tc.order {
  551. t.Errorf("Incorrect pull order for %q: %v != %v", tc.name, actual, tc.order)
  552. }
  553. }
  554. }
  555. func TestLargeRescanInterval(t *testing.T) {
  556. wrapper, err := Load("testdata/largeinterval.xml", device1)
  557. if err != nil {
  558. t.Fatal(err)
  559. }
  560. if wrapper.Folders()["l1"].RescanIntervalS != MaxRescanIntervalS {
  561. t.Error("too large rescan interval should be maxed out")
  562. }
  563. if wrapper.Folders()["l2"].RescanIntervalS != 0 {
  564. t.Error("negative rescan interval should become zero")
  565. }
  566. }
  567. func TestGUIConfigURL(t *testing.T) {
  568. testcases := [][2]string{
  569. {"192.0.2.42:8080", "http://192.0.2.42:8080/"},
  570. {":8080", "http://127.0.0.1:8080/"},
  571. {"0.0.0.0:8080", "http://127.0.0.1:8080/"},
  572. {"127.0.0.1:8080", "http://127.0.0.1:8080/"},
  573. {"127.0.0.2:8080", "http://127.0.0.2:8080/"},
  574. {"[::]:8080", "http://[::1]:8080/"},
  575. {"[2001::42]:8080", "http://[2001::42]:8080/"},
  576. }
  577. for _, tc := range testcases {
  578. c := GUIConfiguration{
  579. RawAddress: tc[0],
  580. }
  581. u := c.URL()
  582. if u != tc[1] {
  583. t.Errorf("Incorrect URL %s != %s for addr %s", u, tc[1], tc[0])
  584. }
  585. }
  586. }
  587. func TestDuplicateDevices(t *testing.T) {
  588. // Duplicate devices should be removed
  589. wrapper, err := Load("testdata/dupdevices.xml", device1)
  590. if err != nil {
  591. t.Fatal(err)
  592. }
  593. if l := len(wrapper.RawCopy().Devices); l != 3 {
  594. t.Errorf("Incorrect number of devices, %d != 3", l)
  595. }
  596. f := wrapper.Folders()["f2"]
  597. if l := len(f.Devices); l != 2 {
  598. t.Errorf("Incorrect number of folder devices, %d != 2", l)
  599. }
  600. }
  601. func TestDuplicateFolders(t *testing.T) {
  602. // Duplicate folders are a loading error
  603. _, err := Load("testdata/dupfolders.xml", device1)
  604. if err == nil || !strings.HasPrefix(err.Error(), "duplicate folder ID") {
  605. t.Fatal(`Expected error to mention "duplicate folder ID":`, err)
  606. }
  607. }
  608. func TestEmptyFolderPaths(t *testing.T) {
  609. // Empty folder paths are allowed at the loading stage, and should not
  610. // get messed up by the prepare steps (e.g., become the current dir or
  611. // get a slash added so that it becomes the root directory or similar).
  612. wrapper, err := Load("testdata/nopath.xml", device1)
  613. if err != nil {
  614. t.Fatal(err)
  615. }
  616. folder := wrapper.Folders()["f1"]
  617. if folder.cachedFilesystem != nil {
  618. t.Errorf("Expected %q to be empty", folder.cachedFilesystem)
  619. }
  620. }
  621. func TestV14ListenAddressesMigration(t *testing.T) {
  622. tcs := [][3][]string{
  623. // Default listen plus default relays is now "default"
  624. {
  625. {"tcp://0.0.0.0:22000"},
  626. {"dynamic+https://relays.syncthing.net/endpoint"},
  627. {"default"},
  628. },
  629. // Default listen address without any relay addresses gets converted
  630. // to just the listen address. It's easier this way, and frankly the
  631. // user has gone to some trouble to get the empty string in the
  632. // config to start with...
  633. {
  634. {"tcp://0.0.0.0:22000"}, // old listen addrs
  635. {""}, // old relay addrs
  636. {"tcp://0.0.0.0:22000"}, // new listen addrs
  637. },
  638. // Default listen plus non-default relays gets copied verbatim
  639. {
  640. {"tcp://0.0.0.0:22000"},
  641. {"dynamic+https://other.example.com"},
  642. {"tcp://0.0.0.0:22000", "dynamic+https://other.example.com"},
  643. },
  644. // Non-default listen plus default relays gets copied verbatim
  645. {
  646. {"tcp://1.2.3.4:22000"},
  647. {"dynamic+https://relays.syncthing.net/endpoint"},
  648. {"tcp://1.2.3.4:22000", "dynamic+https://relays.syncthing.net/endpoint"},
  649. },
  650. // Default stuff gets sucked into "default", the rest gets copied
  651. {
  652. {"tcp://0.0.0.0:22000", "tcp://1.2.3.4:22000"},
  653. {"dynamic+https://relays.syncthing.net/endpoint", "relay://other.example.com"},
  654. {"default", "tcp://1.2.3.4:22000", "relay://other.example.com"},
  655. },
  656. }
  657. for _, tc := range tcs {
  658. cfg := Configuration{
  659. Version: 13,
  660. Options: OptionsConfiguration{
  661. ListenAddresses: tc[0],
  662. DeprecatedRelayServers: tc[1],
  663. },
  664. }
  665. convertV13V14(&cfg)
  666. if cfg.Version != 14 {
  667. t.Error("Configuration was not converted")
  668. }
  669. sort.Strings(tc[2])
  670. if !reflect.DeepEqual(cfg.Options.ListenAddresses, tc[2]) {
  671. t.Errorf("Migration error; actual %#v != expected %#v", cfg.Options.ListenAddresses, tc[2])
  672. }
  673. }
  674. }
  675. func TestIgnoredDevices(t *testing.T) {
  676. // Verify that ignored devices that are also present in the
  677. // configuration are not in fact ignored.
  678. wrapper, err := Load("testdata/ignoreddevices.xml", device1)
  679. if err != nil {
  680. t.Fatal(err)
  681. }
  682. if wrapper.IgnoredDevice(device1) {
  683. t.Errorf("Device %v should not be ignored", device1)
  684. }
  685. if !wrapper.IgnoredDevice(device3) {
  686. t.Errorf("Device %v should be ignored", device3)
  687. }
  688. }
  689. func TestGetDevice(t *testing.T) {
  690. // Verify that the Device() call does the right thing
  691. wrapper, err := Load("testdata/ignoreddevices.xml", device1)
  692. if err != nil {
  693. t.Fatal(err)
  694. }
  695. // device1 is mentioned in the config
  696. device, ok := wrapper.Device(device1)
  697. if !ok {
  698. t.Error(device1, "should exist")
  699. }
  700. if device.DeviceID != device1 {
  701. t.Error("Should have returned", device1, "not", device.DeviceID)
  702. }
  703. // device3 is not
  704. device, ok = wrapper.Device(device3)
  705. if ok {
  706. t.Error(device3, "should not exist")
  707. }
  708. if device.DeviceID == device3 {
  709. t.Error("Should not returned ID", device3)
  710. }
  711. }
  712. func TestSharesRemovedOnDeviceRemoval(t *testing.T) {
  713. wrapper, err := Load("testdata/example.xml", device1)
  714. if err != nil {
  715. t.Errorf("Failed: %s", err)
  716. }
  717. raw := wrapper.RawCopy()
  718. raw.Devices = raw.Devices[:len(raw.Devices)-1]
  719. if len(raw.Folders[0].Devices) <= len(raw.Devices) {
  720. t.Error("Should have less devices")
  721. }
  722. _, err = wrapper.Replace(raw)
  723. if err != nil {
  724. t.Errorf("Failed: %s", err)
  725. }
  726. raw = wrapper.RawCopy()
  727. if len(raw.Folders[0].Devices) > len(raw.Devices) {
  728. t.Error("Unexpected extra device")
  729. }
  730. }
  731. func TestIssue4219(t *testing.T) {
  732. // Adding a folder that was previously ignored should make it unignored.
  733. r := bytes.NewReader([]byte(`{
  734. "folders": [
  735. {"id": "abcd123"}
  736. ],
  737. "ignoredFolders": ["t1", "abcd123", "t2"]
  738. }`))
  739. cfg, err := ReadJSON(r, protocol.LocalDeviceID)
  740. if err != nil {
  741. t.Fatal(err)
  742. }
  743. if len(cfg.IgnoredFolders) != 2 {
  744. t.Errorf("There should be two ignored folders, not %d", len(cfg.IgnoredFolders))
  745. }
  746. w := Wrap("/tmp/cfg", cfg)
  747. if !w.IgnoredFolder("t1") {
  748. t.Error("Folder t1 should be ignored")
  749. }
  750. if !w.IgnoredFolder("t2") {
  751. t.Error("Folder t2 should be ignored")
  752. }
  753. if w.IgnoredFolder("abcd123") {
  754. t.Error("Folder abcd123 should not be ignored")
  755. }
  756. }