config_test.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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, err := os.MkdirTemp("", "")
  462. if err != nil {
  463. t.Fatal(err)
  464. }
  465. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, n)
  466. err = os.MkdirAll(filepath.Join(n, "dir", ".stfolder"), os.FileMode(0777))
  467. if err != nil {
  468. t.Fatal(err)
  469. }
  470. testcases := []struct {
  471. path string
  472. err error
  473. }{
  474. {
  475. path: "",
  476. err: ErrMarkerMissing,
  477. },
  478. {
  479. path: "does not exist",
  480. err: ErrPathMissing,
  481. },
  482. {
  483. path: "dir",
  484. err: nil,
  485. },
  486. }
  487. err = fs.DebugSymlinkForTestsOnly(testFs, testFs, "dir", "link")
  488. if err == nil {
  489. t.Log("running with symlink check")
  490. testcases = append(testcases, struct {
  491. path string
  492. err error
  493. }{
  494. path: "link",
  495. err: nil,
  496. })
  497. } else if runtime.GOOS != "windows" {
  498. t.Log("running without symlink check")
  499. t.Fatal(err)
  500. }
  501. for _, testcase := range testcases {
  502. cfg := FolderConfiguration{
  503. Path: filepath.Join(n, testcase.path),
  504. MarkerName: DefaultMarkerName,
  505. }
  506. if err := cfg.CheckPath(); testcase.err != err {
  507. t.Errorf("unexpected error in case %s: %s != %v", testcase.path, err, testcase.err)
  508. }
  509. }
  510. }
  511. func TestNewSaveLoad(t *testing.T) {
  512. path := "testdata/temp.xml"
  513. os.Remove(path)
  514. defer os.Remove(path)
  515. exists := func(path string) bool {
  516. _, err := os.Stat(path)
  517. return err == nil
  518. }
  519. intCfg := New(device1)
  520. cfg := wrap(path, intCfg, device1)
  521. defer cfg.stop()
  522. if exists(path) {
  523. t.Error(path, "exists")
  524. }
  525. err := cfg.Save()
  526. if err != nil {
  527. t.Error(err)
  528. }
  529. if !exists(path) {
  530. t.Error(path, "does not exist")
  531. }
  532. cfg2, err := load(path, device1)
  533. defer cfg2.stop()
  534. if err != nil {
  535. t.Error(err)
  536. }
  537. if diff, equal := messagediff.PrettyDiff(cfg.RawCopy(), cfg2.RawCopy()); !equal {
  538. t.Errorf("Configs are not equal. Diff:\n%s", diff)
  539. }
  540. }
  541. func TestWindowsLineEndings(t *testing.T) {
  542. if runtime.GOOS != "windows" {
  543. t.Skip("Windows specific")
  544. }
  545. dir, err := os.MkdirTemp("", "syncthing-test")
  546. if err != nil {
  547. t.Fatal(err)
  548. }
  549. defer os.RemoveAll(dir)
  550. path := filepath.Join(dir, "config.xml")
  551. os.Remove(path)
  552. defer os.Remove(path)
  553. intCfg := New(device1)
  554. cfg := wrap(path, intCfg, device1)
  555. defer cfg.stop()
  556. if err := cfg.Save(); err != nil {
  557. t.Error(err)
  558. }
  559. bs, err := os.ReadFile(path)
  560. if err != nil {
  561. t.Error(err)
  562. }
  563. unixLineEndings := bytes.Count(bs, []byte("\n"))
  564. windowsLineEndings := bytes.Count(bs, []byte("\r\n"))
  565. if unixLineEndings == 0 || windowsLineEndings != unixLineEndings {
  566. t.Error("expected there to be a non-zero number of Windows line endings")
  567. }
  568. }
  569. func TestPrepare(t *testing.T) {
  570. var cfg Configuration
  571. if cfg.Folders != nil || cfg.Devices != nil || cfg.Options.RawListenAddresses != nil {
  572. t.Error("Expected nil")
  573. }
  574. cfg.prepare(device1)
  575. if cfg.Folders == nil || cfg.Devices == nil || cfg.Options.RawListenAddresses == nil {
  576. t.Error("Unexpected nil")
  577. }
  578. }
  579. func TestCopy(t *testing.T) {
  580. wrapper, wrapperCancel, err := copyAndLoad("testdata/example.xml", device1)
  581. defer wrapperCancel()
  582. if err != nil {
  583. t.Fatal(err)
  584. }
  585. cfg := wrapper.RawCopy()
  586. bsOrig, err := json.MarshalIndent(cfg, "", " ")
  587. if err != nil {
  588. t.Fatal(err)
  589. }
  590. copy := cfg.Copy()
  591. cfg.Devices[0].Addresses[0] = "wrong"
  592. cfg.Folders[0].Devices[0].DeviceID = protocol.DeviceID{0, 1, 2, 3}
  593. cfg.Options.RawListenAddresses[0] = "wrong"
  594. cfg.GUI.APIKey = "wrong"
  595. bsChanged, err := json.MarshalIndent(cfg, "", " ")
  596. if err != nil {
  597. t.Fatal(err)
  598. }
  599. bsCopy, err := json.MarshalIndent(copy, "", " ")
  600. if err != nil {
  601. t.Fatal(err)
  602. }
  603. if bytes.Equal(bsOrig, bsChanged) {
  604. t.Error("Config should have changed")
  605. }
  606. if !bytes.Equal(bsOrig, bsCopy) {
  607. // os.WriteFile("a", bsOrig, 0644)
  608. // os.WriteFile("b", bsCopy, 0644)
  609. t.Error("Copy should be unchanged")
  610. }
  611. }
  612. func TestPullOrder(t *testing.T) {
  613. wrapper, wrapperCleanup, err := copyAndLoad("testdata/pullorder.xml", device1)
  614. defer wrapperCleanup()
  615. if err != nil {
  616. t.Fatal(err)
  617. }
  618. folders := wrapper.Folders()
  619. expected := []struct {
  620. name string
  621. order PullOrder
  622. }{
  623. {"f1", PullOrderRandom}, // empty value, default
  624. {"f2", PullOrderRandom}, // explicit
  625. {"f3", PullOrderAlphabetic}, // explicit
  626. {"f4", PullOrderRandom}, // unknown value, default
  627. {"f5", PullOrderSmallestFirst}, // explicit
  628. {"f6", PullOrderLargestFirst}, // explicit
  629. {"f7", PullOrderOldestFirst}, // explicit
  630. {"f8", PullOrderNewestFirst}, // explicit
  631. }
  632. // Verify values are deserialized correctly
  633. for _, tc := range expected {
  634. if actual := folders[tc.name].Order; actual != tc.order {
  635. t.Errorf("Incorrect pull order for %q: %v != %v", tc.name, actual, tc.order)
  636. }
  637. }
  638. // Serialize and deserialize again to verify it survives the transformation
  639. buf := new(bytes.Buffer)
  640. cfg := wrapper.RawCopy()
  641. cfg.WriteXML(buf)
  642. t.Logf("%s", buf.Bytes())
  643. cfg, _, err = ReadXML(buf, device1)
  644. if err != nil {
  645. t.Fatal(err)
  646. }
  647. wrapper2 := wrap(wrapper.ConfigPath(), cfg, device1)
  648. defer wrapper2.stop()
  649. folders = wrapper2.Folders()
  650. for _, tc := range expected {
  651. if actual := folders[tc.name].Order; actual != tc.order {
  652. t.Errorf("Incorrect pull order for %q: %v != %v", tc.name, actual, tc.order)
  653. }
  654. }
  655. }
  656. func TestLargeRescanInterval(t *testing.T) {
  657. wrapper, wrapperCancel, err := copyAndLoad("testdata/largeinterval.xml", device1)
  658. defer wrapperCancel()
  659. if err != nil {
  660. t.Fatal(err)
  661. }
  662. if wrapper.Folders()["l1"].RescanIntervalS != MaxRescanIntervalS {
  663. t.Error("too large rescan interval should be maxed out")
  664. }
  665. if wrapper.Folders()["l2"].RescanIntervalS != 0 {
  666. t.Error("negative rescan interval should become zero")
  667. }
  668. }
  669. func TestGUIConfigURL(t *testing.T) {
  670. testcases := [][2]string{
  671. {"192.0.2.42:8080", "http://192.0.2.42:8080/"},
  672. {":8080", "http://127.0.0.1:8080/"},
  673. {"0.0.0.0:8080", "http://127.0.0.1:8080/"},
  674. {"127.0.0.1:8080", "http://127.0.0.1:8080/"},
  675. {"127.0.0.2:8080", "http://127.0.0.2:8080/"},
  676. {"[::]:8080", "http://[::1]:8080/"},
  677. {"[2001::42]:8080", "http://[2001::42]:8080/"},
  678. }
  679. for _, tc := range testcases {
  680. c := GUIConfiguration{
  681. RawAddress: tc[0],
  682. }
  683. u := c.URL()
  684. if u != tc[1] {
  685. t.Errorf("Incorrect URL %s != %s for addr %s", u, tc[1], tc[0])
  686. }
  687. }
  688. }
  689. func TestGUIPasswordHash(t *testing.T) {
  690. var c GUIConfiguration
  691. testPass := "pass"
  692. if err := c.HashAndSetPassword(testPass); err != nil {
  693. t.Fatal(err)
  694. }
  695. if c.Password == testPass {
  696. t.Error("Password hashing resulted in plaintext")
  697. }
  698. if err := c.CompareHashedPassword(testPass); err != nil {
  699. t.Errorf("No match on same password: %v", err)
  700. }
  701. failPass := "different"
  702. if err := c.CompareHashedPassword(failPass); err == nil {
  703. t.Errorf("Match on different password: %v", err)
  704. }
  705. }
  706. func TestDuplicateDevices(t *testing.T) {
  707. // Duplicate devices should be removed
  708. wrapper, wrapperCancel, err := copyAndLoad("testdata/dupdevices.xml", device1)
  709. defer wrapperCancel()
  710. if err != nil {
  711. t.Fatal(err)
  712. }
  713. if l := len(wrapper.RawCopy().Devices); l != 3 {
  714. t.Errorf("Incorrect number of devices, %d != 3", l)
  715. }
  716. f := wrapper.Folders()["f2"]
  717. if l := len(f.Devices); l != 2 {
  718. t.Errorf("Incorrect number of folder devices, %d != 2", l)
  719. }
  720. }
  721. func TestDuplicateFolders(t *testing.T) {
  722. // Duplicate folders are a loading error
  723. _, _Cancel, err := copyAndLoad("testdata/dupfolders.xml", device1)
  724. defer _Cancel()
  725. if err == nil || !strings.Contains(err.Error(), errFolderIDDuplicate.Error()) {
  726. t.Fatal(`Expected error to mention "duplicate folder ID":`, err)
  727. }
  728. }
  729. func TestEmptyFolderPaths(t *testing.T) {
  730. // Empty folder paths are not allowed at the loading stage, and should not
  731. // get messed up by the prepare steps (e.g., become the current dir or
  732. // get a slash added so that it becomes the root directory or similar).
  733. _, _Cancel, err := copyAndLoad("testdata/nopath.xml", device1)
  734. defer _Cancel()
  735. if err == nil || !strings.Contains(err.Error(), errFolderPathEmpty.Error()) {
  736. t.Fatal("Expected error due to empty folder path, got", err)
  737. }
  738. }
  739. func TestV14ListenAddressesMigration(t *testing.T) {
  740. tcs := [][3][]string{
  741. // Default listen plus default relays is now "default"
  742. {
  743. {"tcp://0.0.0.0:22000"},
  744. {"dynamic+https://relays.syncthing.net/endpoint"},
  745. {"default"},
  746. },
  747. // Default listen address without any relay addresses gets converted
  748. // to just the listen address. It's easier this way, and frankly the
  749. // user has gone to some trouble to get the empty string in the
  750. // config to start with...
  751. {
  752. {"tcp://0.0.0.0:22000"}, // old listen addrs
  753. {""}, // old relay addrs
  754. {"tcp://0.0.0.0:22000"}, // new listen addrs
  755. },
  756. // Default listen plus non-default relays gets copied verbatim
  757. {
  758. {"tcp://0.0.0.0:22000"},
  759. {"dynamic+https://other.example.com"},
  760. {"tcp://0.0.0.0:22000", "dynamic+https://other.example.com"},
  761. },
  762. // Non-default listen plus default relays gets copied verbatim
  763. {
  764. {"tcp://1.2.3.4:22000"},
  765. {"dynamic+https://relays.syncthing.net/endpoint"},
  766. {"tcp://1.2.3.4:22000", "dynamic+https://relays.syncthing.net/endpoint"},
  767. },
  768. // Default stuff gets sucked into "default", the rest gets copied
  769. {
  770. {"tcp://0.0.0.0:22000", "tcp://1.2.3.4:22000"},
  771. {"dynamic+https://relays.syncthing.net/endpoint", "relay://other.example.com"},
  772. {"default", "tcp://1.2.3.4:22000", "relay://other.example.com"},
  773. },
  774. }
  775. m := migration{14, migrateToConfigV14}
  776. for _, tc := range tcs {
  777. cfg := Configuration{
  778. Version: 13,
  779. Options: OptionsConfiguration{
  780. RawListenAddresses: tc[0],
  781. DeprecatedRelayServers: tc[1],
  782. },
  783. }
  784. m.apply(&cfg)
  785. if cfg.Version != 14 {
  786. t.Error("Configuration was not converted")
  787. }
  788. sort.Strings(tc[2])
  789. if !reflect.DeepEqual(cfg.Options.RawListenAddresses, tc[2]) {
  790. t.Errorf("Migration error; actual %#v != expected %#v", cfg.Options.RawListenAddresses, tc[2])
  791. }
  792. }
  793. }
  794. func TestIgnoredDevices(t *testing.T) {
  795. // Verify that ignored devices that are also present in the
  796. // configuration are not in fact ignored.
  797. wrapper, wrapperCancel, err := copyAndLoad("testdata/ignoreddevices.xml", device1)
  798. defer wrapperCancel()
  799. if err != nil {
  800. t.Fatal(err)
  801. }
  802. if wrapper.IgnoredDevice(device1) {
  803. t.Errorf("Device %v should not be ignored", device1)
  804. }
  805. if !wrapper.IgnoredDevice(device3) {
  806. t.Errorf("Device %v should be ignored", device3)
  807. }
  808. }
  809. func TestIgnoredFolders(t *testing.T) {
  810. // Verify that ignored folder that are also present in the
  811. // configuration are not in fact ignored.
  812. // Also, verify that folders that are shared with a device are not ignored.
  813. wrapper, wrapperCancel, err := copyAndLoad("testdata/ignoredfolders.xml", device1)
  814. defer wrapperCancel()
  815. if err != nil {
  816. t.Fatal(err)
  817. }
  818. if wrapper.IgnoredFolder(device2, "folder1") {
  819. t.Errorf("Device %v should not be ignored", device2)
  820. }
  821. if !wrapper.IgnoredFolder(device3, "folder1") {
  822. t.Errorf("Device %v should be ignored", device3)
  823. }
  824. // Should be removed, hence not ignored.
  825. if wrapper.IgnoredFolder(device4, "folder1") {
  826. t.Errorf("Device %v should not be ignored", device4)
  827. }
  828. if !wrapper.IgnoredFolder(device2, "folder2") {
  829. t.Errorf("Device %v should not be ignored", device2)
  830. }
  831. if !wrapper.IgnoredFolder(device3, "folder2") {
  832. t.Errorf("Device %v should be ignored", device3)
  833. }
  834. // 2 for folder2, 1 for folder1, as non-existing device and device the folder is shared with is removed.
  835. expectedIgnoredFolders := 3
  836. for _, dev := range wrapper.Devices() {
  837. expectedIgnoredFolders -= len(dev.IgnoredFolders)
  838. }
  839. if expectedIgnoredFolders != 0 {
  840. t.Errorf("Left with %d ignored folders", expectedIgnoredFolders)
  841. }
  842. }
  843. func TestGetDevice(t *testing.T) {
  844. // Verify that the Device() call does the right thing
  845. wrapper, wrapperCancel, err := copyAndLoad("testdata/ignoreddevices.xml", device1)
  846. defer wrapperCancel()
  847. if err != nil {
  848. t.Fatal(err)
  849. }
  850. // device1 is mentioned in the config
  851. device, ok := wrapper.Device(device1)
  852. if !ok {
  853. t.Error(device1, "should exist")
  854. }
  855. if device.DeviceID != device1 {
  856. t.Error("Should have returned", device1, "not", device.DeviceID)
  857. }
  858. // device3 is not
  859. device, ok = wrapper.Device(device3)
  860. if ok {
  861. t.Error(device3, "should not exist")
  862. }
  863. if device.DeviceID == device3 {
  864. t.Error("Should not returned ID", device3)
  865. }
  866. }
  867. func TestSharesRemovedOnDeviceRemoval(t *testing.T) {
  868. wrapper, wrapperCancel, err := copyAndLoad("testdata/example.xml", device1)
  869. defer wrapperCancel()
  870. if err != nil {
  871. t.Errorf("Failed: %s", err)
  872. }
  873. raw := wrapper.RawCopy()
  874. raw.Devices = raw.Devices[:len(raw.Devices)-1]
  875. if len(raw.Folders[0].Devices) <= len(raw.Devices) {
  876. t.Error("Should have less devices")
  877. }
  878. replace(t, wrapper, raw)
  879. raw = wrapper.RawCopy()
  880. if len(raw.Folders[0].Devices) > len(raw.Devices) {
  881. t.Error("Unexpected extra device")
  882. }
  883. }
  884. func TestIssue4219(t *testing.T) {
  885. // Adding a folder that was previously ignored should make it unignored.
  886. r := bytes.NewReader([]byte(`{
  887. "devices": [
  888. {
  889. "deviceID": "GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY",
  890. "ignoredFolders": [
  891. {
  892. "id": "t1"
  893. },
  894. {
  895. "id": "abcd123"
  896. }
  897. ]
  898. },
  899. {
  900. "deviceID": "LGFPDIT-7SKNNJL-VJZA4FC-7QNCRKA-CE753K7-2BW5QDK-2FOZ7FR-FEP57QJ",
  901. "ignoredFolders": [
  902. {
  903. "id": "t1"
  904. },
  905. {
  906. "id": "abcd123"
  907. }
  908. ]
  909. }
  910. ],
  911. "folders": [
  912. {
  913. "id": "abcd123",
  914. "path": "testdata",
  915. "devices":[
  916. {"deviceID": "GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY"}
  917. ]
  918. }
  919. ],
  920. "remoteIgnoredDevices": [
  921. {
  922. "deviceID": "GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY"
  923. }
  924. ]
  925. }`))
  926. myID := protocol.LocalDeviceID
  927. cfg, err := ReadJSON(r, myID)
  928. if err != nil {
  929. t.Fatal(err)
  930. }
  931. if len(cfg.IgnoredDevices) != 0 { // 1 gets removed
  932. t.Errorf("There should be zero ignored devices, not %d", len(cfg.IgnoredDevices))
  933. }
  934. ignoredFolders := 0
  935. for _, dev := range cfg.Devices {
  936. ignoredFolders += len(dev.IgnoredFolders)
  937. }
  938. if ignoredFolders != 3 { // 1 gets removed
  939. t.Errorf("There should be three ignored folders, not %d", ignoredFolders)
  940. }
  941. w := wrap("/tmp/cfg", cfg, myID)
  942. defer w.stop()
  943. if !w.IgnoredFolder(device2, "t1") {
  944. t.Error("Folder device2 t1 should be ignored")
  945. }
  946. if !w.IgnoredFolder(device3, "t1") {
  947. t.Error("Folder device3 t1 should be ignored")
  948. }
  949. if w.IgnoredFolder(device2, "abcd123") {
  950. t.Error("Folder device2 abcd123 should not be ignored")
  951. }
  952. if !w.IgnoredFolder(device3, "abcd123") {
  953. t.Error("Folder device3 abcd123 should be ignored")
  954. }
  955. }
  956. func TestInvalidDeviceIDRejected(t *testing.T) {
  957. // This test verifies that we properly reject invalid device IDs when
  958. // deserializing a JSON config.
  959. cases := []struct {
  960. id string
  961. ok bool
  962. }{
  963. // a genuine device ID
  964. {"GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY", true},
  965. // incorrect check digit
  966. {"GYRZZQB-IRNPV4A-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY", false},
  967. // missing digit
  968. {"GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VA", false},
  969. // clearly broken
  970. {"invalid", false},
  971. // accepted as the empty device ID for historical reasons...
  972. {"", true},
  973. }
  974. for _, tc := range cases {
  975. cfg := defaultConfigAsMap()
  976. // Change the device ID of the first device to "invalid". Fast and loose
  977. // with the type assertions as we know what the JSON decoder returns.
  978. devs := cfg["devices"].([]interface{})
  979. dev0 := devs[0].(map[string]interface{})
  980. dev0["deviceID"] = tc.id
  981. devs[0] = dev0
  982. invalidJSON, err := json.Marshal(cfg)
  983. if err != nil {
  984. t.Fatal(err)
  985. }
  986. _, err = ReadJSON(bytes.NewReader(invalidJSON), device1)
  987. if tc.ok && err != nil {
  988. t.Errorf("unexpected error for device ID %q: %v", tc.id, err)
  989. } else if !tc.ok && err == nil {
  990. t.Errorf("device ID %q, expected error but got nil", tc.id)
  991. }
  992. }
  993. }
  994. func TestInvalidFolderIDRejected(t *testing.T) {
  995. // This test verifies that we properly reject invalid folder IDs when
  996. // deserializing a JSON config.
  997. cases := []struct {
  998. id string
  999. ok bool
  1000. }{
  1001. // a reasonable folder ID
  1002. {"foo", true},
  1003. // empty is not OK
  1004. {"", false},
  1005. }
  1006. for _, tc := range cases {
  1007. cfg := defaultConfigAsMap()
  1008. // Change the folder ID of the first folder to the empty string.
  1009. // Fast and loose with the type assertions as we know what the JSON
  1010. // decoder returns.
  1011. devs := cfg["folders"].([]interface{})
  1012. dev0 := devs[0].(map[string]interface{})
  1013. dev0["id"] = tc.id
  1014. devs[0] = dev0
  1015. invalidJSON, err := json.Marshal(cfg)
  1016. if err != nil {
  1017. t.Fatal(err)
  1018. }
  1019. _, err = ReadJSON(bytes.NewReader(invalidJSON), device1)
  1020. if tc.ok && err != nil {
  1021. t.Errorf("unexpected error for folder ID %q: %v", tc.id, err)
  1022. } else if !tc.ok && err == nil {
  1023. t.Errorf("folder ID %q, expected error but got nil", tc.id)
  1024. }
  1025. }
  1026. }
  1027. func TestFilterURLSchemePrefix(t *testing.T) {
  1028. cases := []struct {
  1029. before []string
  1030. prefix string
  1031. after []string
  1032. }{
  1033. {[]string{}, "kcp", []string{}},
  1034. {[]string{"tcp://foo"}, "kcp", []string{"tcp://foo"}},
  1035. {[]string{"kcp://foo"}, "kcp", []string{}},
  1036. {[]string{"tcp6://foo", "kcp6://foo"}, "kcp", []string{"tcp6://foo"}},
  1037. {[]string{"kcp6://foo", "tcp6://foo"}, "kcp", []string{"tcp6://foo"}},
  1038. {
  1039. []string{"tcp://foo", "tcp4://foo", "kcp://foo", "kcp4://foo", "banana://foo", "banana4://foo", "banananas!"},
  1040. "kcp",
  1041. []string{"tcp://foo", "tcp4://foo", "banana://foo", "banana4://foo", "banananas!"},
  1042. },
  1043. }
  1044. for _, tc := range cases {
  1045. res := filterURLSchemePrefix(tc.before, tc.prefix)
  1046. if !reflect.DeepEqual(res, tc.after) {
  1047. t.Errorf("filterURLSchemePrefix => %q, expected %q", res, tc.after)
  1048. }
  1049. }
  1050. }
  1051. func TestDeviceConfigObservedNotNil(t *testing.T) {
  1052. cfg := Configuration{
  1053. Devices: []DeviceConfiguration{
  1054. {},
  1055. },
  1056. }
  1057. cfg.prepare(device1)
  1058. for _, dev := range cfg.Devices {
  1059. if dev.IgnoredFolders == nil {
  1060. t.Errorf("Ignored folders nil")
  1061. }
  1062. }
  1063. }
  1064. func TestRemoveDeviceWithEmptyID(t *testing.T) {
  1065. cfg := Configuration{
  1066. Devices: []DeviceConfiguration{
  1067. {
  1068. Name: "foo",
  1069. },
  1070. },
  1071. Folders: []FolderConfiguration{
  1072. {
  1073. ID: "foo",
  1074. Path: "testdata",
  1075. Devices: []FolderDeviceConfiguration{{}},
  1076. },
  1077. },
  1078. }
  1079. cfg.prepare(device1)
  1080. if len(cfg.Devices) != 1 {
  1081. t.Error("Expected one device")
  1082. } else if cfg.Devices[0].DeviceID != device1 {
  1083. t.Error("Expected device with empty ID to be removed from config:", cfg.Devices)
  1084. }
  1085. if len(cfg.Folders[0].Devices) != 1 {
  1086. t.Error("Expected one device in folder")
  1087. } else if cfg.Folders[0].Devices[0].DeviceID != device1 {
  1088. t.Error("Expected device with empty ID to be removed from folder")
  1089. }
  1090. }
  1091. func TestMaxConcurrentFolders(t *testing.T) {
  1092. cases := []struct {
  1093. input int
  1094. output int
  1095. }{
  1096. {input: -42, output: 0},
  1097. {input: -1, output: 0},
  1098. {input: 0, output: runtime.GOMAXPROCS(-1)},
  1099. {input: 1, output: 1},
  1100. {input: 42, output: 42},
  1101. }
  1102. for _, tc := range cases {
  1103. opts := OptionsConfiguration{RawMaxFolderConcurrency: tc.input}
  1104. res := opts.MaxFolderConcurrency()
  1105. if res != tc.output {
  1106. t.Errorf("Wrong MaxFolderConcurrency, %d => %d, expected %d", tc.input, res, tc.output)
  1107. }
  1108. }
  1109. }
  1110. func adjustDeviceConfiguration(cfg *DeviceConfiguration, id protocol.DeviceID, name string) {
  1111. cfg.DeviceID = id
  1112. cfg.Name = name
  1113. }
  1114. func adjustFolderConfiguration(cfg *FolderConfiguration, id, label string, fsType fs.FilesystemType, path string) {
  1115. cfg.ID = id
  1116. cfg.Label = label
  1117. cfg.FilesystemType = fsType
  1118. cfg.Path = path
  1119. }
  1120. // defaultConfigAsMap returns a valid default config as a JSON-decoded
  1121. // map[string]interface{}. This is useful to override random elements and
  1122. // re-encode into JSON.
  1123. func defaultConfigAsMap() map[string]interface{} {
  1124. cfg := New(device1)
  1125. dev := cfg.Defaults.Device.Copy()
  1126. adjustDeviceConfiguration(&dev, device2, "name")
  1127. cfg.Devices = append(cfg.Devices, dev)
  1128. folder := cfg.Defaults.Folder.Copy()
  1129. adjustFolderConfiguration(&folder, "default", "default", fs.FilesystemTypeBasic, "/tmp")
  1130. cfg.Folders = append(cfg.Folders, folder)
  1131. bs, err := json.Marshal(cfg)
  1132. if err != nil {
  1133. // can't happen
  1134. panic(err)
  1135. }
  1136. var tmp map[string]interface{}
  1137. if err := json.Unmarshal(bs, &tmp); err != nil {
  1138. // can't happen
  1139. panic(err)
  1140. }
  1141. return tmp
  1142. }
  1143. func copyToTmp(path string) (string, error) {
  1144. orig, err := os.Open(path)
  1145. if err != nil {
  1146. return "", err
  1147. }
  1148. defer orig.Close()
  1149. temp, err := os.CreateTemp("", "syncthing-configTest-")
  1150. if err != nil {
  1151. return "", err
  1152. }
  1153. defer temp.Close()
  1154. if _, err := io.Copy(temp, orig); err != nil {
  1155. return "", err
  1156. }
  1157. return temp.Name(), nil
  1158. }
  1159. func copyAndLoad(path string, myID protocol.DeviceID) (*testWrapper, func(), error) {
  1160. temp, err := copyToTmp(path)
  1161. if err != nil {
  1162. return nil, func() {}, err
  1163. }
  1164. wrapper, err := load(temp, myID)
  1165. if err != nil {
  1166. return nil, func() {}, err
  1167. }
  1168. return wrapper, func() {
  1169. wrapper.stop()
  1170. os.Remove(temp)
  1171. }, nil
  1172. }
  1173. func load(path string, myID protocol.DeviceID) (*testWrapper, error) {
  1174. cfg, _, err := Load(path, myID, events.NoopLogger)
  1175. if err != nil {
  1176. return nil, err
  1177. }
  1178. return startWrapper(cfg), nil
  1179. }
  1180. func wrap(path string, cfg Configuration, myID protocol.DeviceID) *testWrapper {
  1181. wrapper := Wrap(path, cfg, myID, events.NoopLogger)
  1182. return startWrapper(wrapper)
  1183. }
  1184. type testWrapper struct {
  1185. Wrapper
  1186. cancel context.CancelFunc
  1187. done chan struct{}
  1188. }
  1189. func (w *testWrapper) stop() {
  1190. w.cancel()
  1191. <-w.done
  1192. }
  1193. func startWrapper(wrapper Wrapper) *testWrapper {
  1194. tw := &testWrapper{
  1195. Wrapper: wrapper,
  1196. done: make(chan struct{}),
  1197. }
  1198. ctx, cancel := context.WithCancel(context.Background())
  1199. tw.cancel = cancel
  1200. go func() {
  1201. wrapper.Serve(ctx)
  1202. close(tw.done)
  1203. }()
  1204. return tw
  1205. }
  1206. func TestInternalVersioningConfiguration(t *testing.T) {
  1207. // Verify that the versioning configuration XML seralizes to something
  1208. // reasonable.
  1209. cfg := New(device1)
  1210. folder := cfg.Defaults.Folder.Copy()
  1211. adjustFolderConfiguration(&folder, "default", "default", fs.FilesystemTypeBasic, "/tmp")
  1212. cfg.Folders = append(cfg.Folders, folder)
  1213. cfg.Folders[0].Versioning = VersioningConfiguration{
  1214. Type: "foo",
  1215. Params: map[string]string{"bar": "baz"},
  1216. CleanupIntervalS: 42,
  1217. }
  1218. // These things should all be present in the serialized version.
  1219. expected := []string{
  1220. `<versioning type="foo">`,
  1221. `<param key="bar" val="baz"`,
  1222. `<cleanupIntervalS>42<`,
  1223. `</versioning>`,
  1224. }
  1225. bs, err := xml.MarshalIndent(cfg, "", " ")
  1226. if err != nil {
  1227. t.Fatal(err)
  1228. }
  1229. for _, exp := range expected {
  1230. if !strings.Contains(string(bs), exp) {
  1231. t.Logf("%s", bs)
  1232. t.Fatal("bad serializion of versioning parameters")
  1233. }
  1234. }
  1235. }
  1236. func TestReceiveEncryptedFolderFixed(t *testing.T) {
  1237. cfg := Configuration{
  1238. Folders: []FolderConfiguration{
  1239. {
  1240. ID: "foo",
  1241. Path: "testdata",
  1242. Type: FolderTypeReceiveEncrypted,
  1243. DisableTempIndexes: false,
  1244. IgnorePerms: false,
  1245. },
  1246. },
  1247. }
  1248. cfg.prepare(device1)
  1249. if len(cfg.Folders) != 1 {
  1250. t.Fatal("Expected one folder")
  1251. }
  1252. f := cfg.Folders[0]
  1253. if !f.DisableTempIndexes {
  1254. t.Error("DisableTempIndexes should be true")
  1255. }
  1256. if !f.IgnorePerms {
  1257. t.Error("IgnorePerms should be true")
  1258. }
  1259. }