config_test.go 26 KB

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