config_test.go 36 KB

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