1
0

config_test.go 32 KB

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