config_test.go 43 KB

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