config_test.go 29 KB

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