config_test.go 30 KB

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