config_test.go 36 KB

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