config_test.go 37 KB

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