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