config_test.go 32 KB

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