config_test.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  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. XattrFilter: XattrFilter{
  103. Entries: []XattrFilterEntry{},
  104. MaxSingleEntrySize: 1024,
  105. MaxTotalSize: 4096,
  106. },
  107. },
  108. Device: DeviceConfiguration{
  109. Addresses: []string{"dynamic"},
  110. AllowedNetworks: []string{},
  111. Compression: protocol.CompressionMetadata,
  112. IgnoredFolders: []ObservedFolder{},
  113. },
  114. Ignores: Ignores{
  115. Lines: []string{},
  116. },
  117. },
  118. IgnoredDevices: []ObservedDevice{},
  119. }
  120. expected.Devices = []DeviceConfiguration{expected.Defaults.Device.Copy()}
  121. expected.Devices[0].DeviceID = device1
  122. expected.Devices[0].Name, _ = os.Hostname()
  123. cfg := New(device1)
  124. cfg.GUI = GUIConfiguration{}
  125. cfg.LDAP = LDAPConfiguration{}
  126. if diff, equal := messagediff.PrettyDiff(expected, cfg); !equal {
  127. t.Errorf("Default config differs. Diff:\n%s", diff)
  128. }
  129. }
  130. func TestDeviceConfig(t *testing.T) {
  131. for i := OldestHandledVersion; i <= CurrentVersion; i++ {
  132. cfgFile := fmt.Sprintf("testdata/v%d.xml", i)
  133. if _, err := os.Stat(cfgFile); os.IsNotExist(err) {
  134. continue
  135. }
  136. os.RemoveAll(filepath.Join("testdata", DefaultMarkerName))
  137. wr, wrCancel, err := copyAndLoad(cfgFile, device1)
  138. defer wrCancel()
  139. if err != nil {
  140. t.Fatal(err)
  141. }
  142. _, err = os.Stat(filepath.Join("testdata", DefaultMarkerName))
  143. if i < 6 && err != nil {
  144. t.Fatal(err)
  145. } else if i >= 6 && err == nil {
  146. t.Fatal("Unexpected file")
  147. }
  148. cfg := wr.Wrapper.(*wrapper).cfg
  149. expectedFolders := []FolderConfiguration{
  150. {
  151. ID: "test",
  152. FilesystemType: fs.FilesystemTypeBasic,
  153. Path: "testdata",
  154. Devices: []FolderDeviceConfiguration{{DeviceID: device1}, {DeviceID: device4}},
  155. Type: FolderTypeSendOnly,
  156. RescanIntervalS: 600,
  157. FSWatcherEnabled: false,
  158. FSWatcherDelayS: 10,
  159. Copiers: 0,
  160. Hashers: 0,
  161. AutoNormalize: true,
  162. MinDiskFree: Size{1, "%"},
  163. MaxConflicts: -1,
  164. Versioning: VersioningConfiguration{
  165. Params: map[string]string{},
  166. },
  167. WeakHashThresholdPct: 25,
  168. MarkerName: DefaultMarkerName,
  169. JunctionsAsDirs: true,
  170. MaxConcurrentWrites: maxConcurrentWritesDefault,
  171. XattrFilter: XattrFilter{
  172. Entries: []XattrFilterEntry{},
  173. },
  174. },
  175. }
  176. expectedDevices := []DeviceConfiguration{
  177. {
  178. DeviceID: device1,
  179. Name: "node one",
  180. Addresses: []string{"tcp://a"},
  181. Compression: protocol.CompressionMetadata,
  182. AllowedNetworks: []string{},
  183. IgnoredFolders: []ObservedFolder{},
  184. },
  185. {
  186. DeviceID: device4,
  187. Name: "node two",
  188. Addresses: []string{"tcp://b"},
  189. Compression: protocol.CompressionMetadata,
  190. AllowedNetworks: []string{},
  191. IgnoredFolders: []ObservedFolder{},
  192. },
  193. }
  194. expectedDeviceIDs := []protocol.DeviceID{device1, device4}
  195. if cfg.Version != CurrentVersion {
  196. t.Errorf("%d: Incorrect version %d != %d", i, cfg.Version, CurrentVersion)
  197. }
  198. if diff, equal := messagediff.PrettyDiff(expectedFolders, cfg.Folders); !equal {
  199. t.Errorf("%d: Incorrect Folders. Diff:\n%s", i, diff)
  200. }
  201. if diff, equal := messagediff.PrettyDiff(expectedDevices, cfg.Devices); !equal {
  202. t.Errorf("%d: Incorrect Devices. Diff:\n%s", i, diff)
  203. }
  204. if diff, equal := messagediff.PrettyDiff(expectedDeviceIDs, cfg.Folders[0].DeviceIDs()); !equal {
  205. t.Errorf("%d: Incorrect DeviceIDs. Diff:\n%s", i, diff)
  206. }
  207. }
  208. }
  209. func TestNoListenAddresses(t *testing.T) {
  210. cfg, cfgCancel, err := copyAndLoad("testdata/nolistenaddress.xml", device1)
  211. defer cfgCancel()
  212. if err != nil {
  213. t.Error(err)
  214. }
  215. expected := []string{""}
  216. actual := cfg.Options().RawListenAddresses
  217. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  218. t.Errorf("Unexpected RawListenAddresses. Diff:\n%s", diff)
  219. }
  220. }
  221. func TestOverriddenValues(t *testing.T) {
  222. expected := OptionsConfiguration{
  223. RawListenAddresses: []string{"tcp://:23000"},
  224. RawGlobalAnnServers: []string{"udp4://syncthing.nym.se:22026"},
  225. GlobalAnnEnabled: false,
  226. LocalAnnEnabled: false,
  227. LocalAnnPort: 42123,
  228. LocalAnnMCAddr: "quux:3232",
  229. MaxSendKbps: 1234,
  230. MaxRecvKbps: 2341,
  231. ReconnectIntervalS: 6000,
  232. RelaysEnabled: false,
  233. RelayReconnectIntervalM: 20,
  234. StartBrowser: false,
  235. NATEnabled: false,
  236. NATLeaseM: 90,
  237. NATRenewalM: 15,
  238. NATTimeoutS: 15,
  239. AutoUpgradeIntervalH: 24,
  240. KeepTemporariesH: 48,
  241. CacheIgnoredFiles: true,
  242. ProgressUpdateIntervalS: 10,
  243. LimitBandwidthInLan: true,
  244. MinHomeDiskFree: Size{5.2, "%"},
  245. URSeen: 8,
  246. URAccepted: 4,
  247. URURL: "https://localhost/newdata",
  248. URInitialDelayS: 800,
  249. URPostInsecurely: true,
  250. ReleasesURL: "https://localhost/releases",
  251. AlwaysLocalNets: []string{},
  252. OverwriteRemoteDevNames: true,
  253. TempIndexMinBlocks: 100,
  254. UnackedNotificationIDs: []string{"asdfasdf"},
  255. SetLowPriority: false,
  256. CRURL: "https://localhost/newcrash",
  257. CREnabled: false,
  258. StunKeepaliveStartS: 9000,
  259. StunKeepaliveMinS: 900,
  260. RawStunServers: []string{"foo"},
  261. FeatureFlags: []string{"feature"},
  262. }
  263. expectedPath := "/media/syncthing"
  264. os.Unsetenv("STNOUPGRADE")
  265. cfg, cfgCancel, err := copyAndLoad("testdata/overridenvalues.xml", device1)
  266. defer cfgCancel()
  267. if err != nil {
  268. t.Error(err)
  269. }
  270. if diff, equal := messagediff.PrettyDiff(expected, cfg.Options()); !equal {
  271. t.Errorf("Overridden config differs. Diff:\n%s", diff)
  272. }
  273. if path := cfg.DefaultFolder().Path; path != expectedPath {
  274. t.Errorf("Default folder path is %v, expected %v", path, expectedPath)
  275. }
  276. }
  277. func TestDeviceAddressesDynamic(t *testing.T) {
  278. name, _ := os.Hostname()
  279. expected := map[protocol.DeviceID]DeviceConfiguration{
  280. device1: {
  281. DeviceID: device1,
  282. Addresses: []string{"dynamic"},
  283. AllowedNetworks: []string{},
  284. IgnoredFolders: []ObservedFolder{},
  285. },
  286. device2: {
  287. DeviceID: device2,
  288. Addresses: []string{"dynamic"},
  289. AllowedNetworks: []string{},
  290. IgnoredFolders: []ObservedFolder{},
  291. },
  292. device3: {
  293. DeviceID: device3,
  294. Addresses: []string{"dynamic"},
  295. AllowedNetworks: []string{},
  296. IgnoredFolders: []ObservedFolder{},
  297. },
  298. device4: {
  299. DeviceID: device4,
  300. Name: name, // Set when auto created
  301. Addresses: []string{"dynamic"},
  302. Compression: protocol.CompressionMetadata,
  303. AllowedNetworks: []string{},
  304. IgnoredFolders: []ObservedFolder{},
  305. },
  306. }
  307. cfg, cfgCancel, err := copyAndLoad("testdata/deviceaddressesdynamic.xml", device4)
  308. defer cfgCancel()
  309. if err != nil {
  310. t.Error(err)
  311. }
  312. actual := cfg.Devices()
  313. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  314. t.Errorf("Devices differ. Diff:\n%s", diff)
  315. }
  316. }
  317. func TestDeviceCompression(t *testing.T) {
  318. name, _ := os.Hostname()
  319. expected := map[protocol.DeviceID]DeviceConfiguration{
  320. device1: {
  321. DeviceID: device1,
  322. Addresses: []string{"dynamic"},
  323. Compression: protocol.CompressionMetadata,
  324. AllowedNetworks: []string{},
  325. IgnoredFolders: []ObservedFolder{},
  326. },
  327. device2: {
  328. DeviceID: device2,
  329. Addresses: []string{"dynamic"},
  330. Compression: protocol.CompressionMetadata,
  331. AllowedNetworks: []string{},
  332. IgnoredFolders: []ObservedFolder{},
  333. },
  334. device3: {
  335. DeviceID: device3,
  336. Addresses: []string{"dynamic"},
  337. Compression: protocol.CompressionNever,
  338. AllowedNetworks: []string{},
  339. IgnoredFolders: []ObservedFolder{},
  340. },
  341. device4: {
  342. DeviceID: device4,
  343. Name: name, // Set when auto created
  344. Addresses: []string{"dynamic"},
  345. Compression: protocol.CompressionMetadata,
  346. AllowedNetworks: []string{},
  347. IgnoredFolders: []ObservedFolder{},
  348. },
  349. }
  350. cfg, cfgCancel, err := copyAndLoad("testdata/devicecompression.xml", device4)
  351. defer cfgCancel()
  352. if err != nil {
  353. t.Error(err)
  354. }
  355. actual := cfg.Devices()
  356. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  357. t.Errorf("Devices differ. Diff:\n%s", diff)
  358. }
  359. }
  360. func TestDeviceAddressesStatic(t *testing.T) {
  361. name, _ := os.Hostname()
  362. expected := map[protocol.DeviceID]DeviceConfiguration{
  363. device1: {
  364. DeviceID: device1,
  365. Addresses: []string{"tcp://192.0.2.1", "tcp://192.0.2.2"},
  366. AllowedNetworks: []string{},
  367. IgnoredFolders: []ObservedFolder{},
  368. },
  369. device2: {
  370. DeviceID: device2,
  371. Addresses: []string{"tcp://192.0.2.3:6070", "tcp://[2001:db8::42]:4242"},
  372. AllowedNetworks: []string{},
  373. IgnoredFolders: []ObservedFolder{},
  374. },
  375. device3: {
  376. DeviceID: device3,
  377. Addresses: []string{"tcp://[2001:db8::44]:4444", "tcp://192.0.2.4:6090"},
  378. AllowedNetworks: []string{},
  379. IgnoredFolders: []ObservedFolder{},
  380. },
  381. device4: {
  382. DeviceID: device4,
  383. Name: name, // Set when auto created
  384. Addresses: []string{"dynamic"},
  385. Compression: protocol.CompressionMetadata,
  386. AllowedNetworks: []string{},
  387. IgnoredFolders: []ObservedFolder{},
  388. },
  389. }
  390. cfg, cfgCancel, err := copyAndLoad("testdata/deviceaddressesstatic.xml", device4)
  391. defer cfgCancel()
  392. if err != nil {
  393. t.Error(err)
  394. }
  395. actual := cfg.Devices()
  396. if diff, equal := messagediff.PrettyDiff(expected, actual); !equal {
  397. t.Errorf("Devices differ. Diff:\n%s", diff)
  398. }
  399. }
  400. func TestVersioningConfig(t *testing.T) {
  401. cfg, cfgCancel, err := copyAndLoad("testdata/versioningconfig.xml", device4)
  402. defer cfgCancel()
  403. if err != nil {
  404. t.Error(err)
  405. }
  406. vc := cfg.Folders()["test"].Versioning
  407. if vc.Type != "simple" {
  408. t.Errorf(`vc.Type %q != "simple"`, vc.Type)
  409. }
  410. if l := len(vc.Params); l != 2 {
  411. t.Errorf("len(vc.Params) %d != 2", l)
  412. }
  413. expected := map[string]string{
  414. "foo": "bar",
  415. "baz": "quux",
  416. }
  417. if diff, equal := messagediff.PrettyDiff(expected, vc.Params); !equal {
  418. t.Errorf("vc.Params differ. Diff:\n%s", diff)
  419. }
  420. }
  421. func TestIssue1262(t *testing.T) {
  422. if !build.IsWindows {
  423. t.Skipf("path gets converted to absolute as part of the filesystem initialization on linux")
  424. }
  425. cfg, cfgCancel, err := copyAndLoad("testdata/issue-1262.xml", device4)
  426. defer cfgCancel()
  427. if err != nil {
  428. t.Fatal(err)
  429. }
  430. actual := cfg.Folders()["test"].Filesystem(nil).URI()
  431. expected := `e:\`
  432. if actual != expected {
  433. t.Errorf("%q != %q", actual, expected)
  434. }
  435. }
  436. func TestIssue1750(t *testing.T) {
  437. cfg, cfgCancel, err := copyAndLoad("testdata/issue-1750.xml", device4)
  438. defer cfgCancel()
  439. if err != nil {
  440. t.Fatal(err)
  441. }
  442. if cfg.Options().RawListenAddresses[0] != "tcp://:23000" {
  443. t.Errorf("%q != %q", cfg.Options().RawListenAddresses[0], "tcp://:23000")
  444. }
  445. if cfg.Options().RawListenAddresses[1] != "tcp://:23001" {
  446. t.Errorf("%q != %q", cfg.Options().RawListenAddresses[1], "tcp://:23001")
  447. }
  448. if cfg.Options().RawGlobalAnnServers[0] != "udp4://syncthing.nym.se:22026" {
  449. t.Errorf("%q != %q", cfg.Options().RawGlobalAnnServers[0], "udp4://syncthing.nym.se:22026")
  450. }
  451. if cfg.Options().RawGlobalAnnServers[1] != "udp4://syncthing.nym.se:22027" {
  452. t.Errorf("%q != %q", cfg.Options().RawGlobalAnnServers[1], "udp4://syncthing.nym.se:22027")
  453. }
  454. }
  455. func TestFolderPath(t *testing.T) {
  456. folder := FolderConfiguration{
  457. Path: "~/tmp",
  458. }
  459. realPath := folder.Filesystem(nil).URI()
  460. if !filepath.IsAbs(realPath) {
  461. t.Error(realPath, "should be absolute")
  462. }
  463. if strings.Contains(realPath, "~") {
  464. t.Error(realPath, "should not contain ~")
  465. }
  466. }
  467. func TestFolderCheckPath(t *testing.T) {
  468. n := t.TempDir()
  469. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, n)
  470. err := os.MkdirAll(filepath.Join(n, "dir", ".stfolder"), os.FileMode(0777))
  471. if err != nil {
  472. t.Fatal(err)
  473. }
  474. testcases := []struct {
  475. path string
  476. err error
  477. }{
  478. {
  479. path: "",
  480. err: ErrMarkerMissing,
  481. },
  482. {
  483. path: "does not exist",
  484. err: ErrPathMissing,
  485. },
  486. {
  487. path: "dir",
  488. err: nil,
  489. },
  490. }
  491. err = fs.DebugSymlinkForTestsOnly(testFs, testFs, "dir", "link")
  492. if err == nil {
  493. t.Log("running with symlink check")
  494. testcases = append(testcases, struct {
  495. path string
  496. err error
  497. }{
  498. path: "link",
  499. err: nil,
  500. })
  501. } else if !build.IsWindows {
  502. t.Log("running without symlink check")
  503. t.Fatal(err)
  504. }
  505. for _, testcase := range testcases {
  506. cfg := FolderConfiguration{
  507. Path: filepath.Join(n, testcase.path),
  508. MarkerName: DefaultMarkerName,
  509. }
  510. if err := cfg.CheckPath(); testcase.err != err {
  511. t.Errorf("unexpected error in case %s: %s != %v", testcase.path, err, testcase.err)
  512. }
  513. }
  514. }
  515. func TestNewSaveLoad(t *testing.T) {
  516. path := "testdata/temp.xml"
  517. os.Remove(path)
  518. defer os.Remove(path)
  519. exists := func(path string) bool {
  520. _, err := os.Stat(path)
  521. return err == nil
  522. }
  523. intCfg := New(device1)
  524. cfg := wrap(path, intCfg, device1)
  525. defer cfg.stop()
  526. if exists(path) {
  527. t.Error(path, "exists")
  528. }
  529. err := cfg.Save()
  530. if err != nil {
  531. t.Error(err)
  532. }
  533. if !exists(path) {
  534. t.Error(path, "does not exist")
  535. }
  536. cfg2, err := load(path, device1)
  537. defer cfg2.stop()
  538. if err != nil {
  539. t.Error(err)
  540. }
  541. if diff, equal := messagediff.PrettyDiff(cfg.RawCopy(), cfg2.RawCopy()); !equal {
  542. t.Errorf("Configs are not equal. Diff:\n%s", diff)
  543. }
  544. }
  545. func TestWindowsLineEndings(t *testing.T) {
  546. if !build.IsWindows {
  547. t.Skip("Windows specific")
  548. }
  549. dir := t.TempDir()
  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 serializes 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. }
  1260. func TestXattrFilter(t *testing.T) {
  1261. cases := []struct {
  1262. in []string
  1263. filter []XattrFilterEntry
  1264. out []string
  1265. }{
  1266. {in: nil, filter: nil, out: nil},
  1267. {in: []string{"foo", "bar", "baz"}, filter: nil, out: []string{"foo", "bar", "baz"}},
  1268. {
  1269. in: []string{"foo", "bar", "baz"},
  1270. filter: []XattrFilterEntry{{Match: "b*", Permit: true}},
  1271. out: []string{"bar", "baz"},
  1272. },
  1273. {
  1274. in: []string{"foo", "bar", "baz"},
  1275. filter: []XattrFilterEntry{{Match: "b*", Permit: false}, {Match: "*", Permit: true}},
  1276. out: []string{"foo"},
  1277. },
  1278. {
  1279. in: []string{"foo", "bar", "baz"},
  1280. filter: []XattrFilterEntry{{Match: "yoink", Permit: true}},
  1281. out: []string{},
  1282. },
  1283. }
  1284. for _, tc := range cases {
  1285. f := XattrFilter{Entries: tc.filter}
  1286. var out []string
  1287. for _, s := range tc.in {
  1288. if f.Permit(s) {
  1289. out = append(out, s)
  1290. }
  1291. }
  1292. if fmt.Sprint(out) != fmt.Sprint(tc.out) {
  1293. t.Errorf("Filter.Apply(%v, %v) == %v, expected %v", tc.in, tc.filter, out, tc.out)
  1294. }
  1295. }
  1296. }