config_test.go 32 KB

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