config_test.go 32 KB

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