config_test.go 26 KB

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