config_test.go 37 KB

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