config_test.go 31 KB

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