config_test.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  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. PullerDelayS: 1,
  105. AutoNormalize: true,
  106. MinDiskFree: size,
  107. Versioning: VersioningConfiguration{
  108. FSType: FilesystemTypeBasic,
  109. CleanupIntervalS: 3600,
  110. Params: map[string]string{},
  111. },
  112. MaxConflicts: 10,
  113. MarkerName: ".stfolder",
  114. MaxConcurrentWrites: maxConcurrentWritesDefault,
  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. PullerDelayS: 1,
  175. AutoNormalize: true,
  176. MinDiskFree: Size{1, "%"},
  177. MaxConflicts: -1,
  178. Versioning: VersioningConfiguration{
  179. CleanupIntervalS: 3600,
  180. FSType: FilesystemTypeBasic,
  181. Params: map[string]string{},
  182. },
  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().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().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. IgnorePerms: false,
  1283. },
  1284. },
  1285. }
  1286. cfg.prepare(device1)
  1287. if len(cfg.Folders) != 1 {
  1288. t.Fatal("Expected one folder")
  1289. }
  1290. f := cfg.Folders[0]
  1291. if !f.IgnorePerms {
  1292. t.Error("IgnorePerms should be true")
  1293. }
  1294. }
  1295. func TestXattrFilter(t *testing.T) {
  1296. cases := []struct {
  1297. in []string
  1298. filter []XattrFilterEntry
  1299. out []string
  1300. }{
  1301. {in: nil, filter: nil, out: nil},
  1302. {in: []string{"foo", "bar", "baz"}, filter: nil, out: []string{"foo", "bar", "baz"}},
  1303. {
  1304. in: []string{"foo", "bar", "baz"},
  1305. filter: []XattrFilterEntry{{Match: "b*", Permit: true}},
  1306. out: []string{"bar", "baz"},
  1307. },
  1308. {
  1309. in: []string{"foo", "bar", "baz"},
  1310. filter: []XattrFilterEntry{{Match: "b*", Permit: false}, {Match: "*", Permit: true}},
  1311. out: []string{"foo"},
  1312. },
  1313. {
  1314. in: []string{"foo", "bar", "baz"},
  1315. filter: []XattrFilterEntry{{Match: "yoink", Permit: true}},
  1316. out: []string{},
  1317. },
  1318. }
  1319. for _, tc := range cases {
  1320. f := XattrFilter{Entries: tc.filter}
  1321. var out []string
  1322. for _, s := range tc.in {
  1323. if f.Permit(s) {
  1324. out = append(out, s)
  1325. }
  1326. }
  1327. if fmt.Sprint(out) != fmt.Sprint(tc.out) {
  1328. t.Errorf("Filter.Apply(%v, %v) == %v, expected %v", tc.in, tc.filter, out, tc.out)
  1329. }
  1330. }
  1331. }
  1332. func TestUntrustedIntroducer(t *testing.T) {
  1333. fd, err := os.Open("testdata/untrustedintroducer.xml")
  1334. if err != nil {
  1335. t.Fatal(err)
  1336. }
  1337. cfg, _, err := ReadXML(fd, device1)
  1338. if err != nil {
  1339. t.Fatal(err)
  1340. }
  1341. if len(cfg.Devices) != 2 {
  1342. // ourselves and the remote in the config
  1343. t.Fatal("Expected two devices")
  1344. }
  1345. // Check that the introducer and auto-accept flags were negated
  1346. var foundUntrusted protocol.DeviceID
  1347. for _, d := range cfg.Devices {
  1348. if d.Name == "untrusted" {
  1349. foundUntrusted = d.DeviceID
  1350. if !d.Untrusted {
  1351. t.Error("untrusted device should be untrusted")
  1352. }
  1353. if d.Introducer {
  1354. t.Error("untrusted device should not be an introducer")
  1355. }
  1356. if d.AutoAcceptFolders {
  1357. t.Error("untrusted device should not auto-accept folders")
  1358. }
  1359. }
  1360. }
  1361. if foundUntrusted.Equals(protocol.EmptyDeviceID) {
  1362. t.Error("untrusted device not found")
  1363. }
  1364. // Folder A has the device added without a password, which is not permitted
  1365. folderA := cfg.FolderMap()["a"]
  1366. for _, dev := range folderA.Devices {
  1367. if dev.DeviceID == foundUntrusted {
  1368. t.Error("untrusted device should not be in folder A")
  1369. }
  1370. }
  1371. // Folder B has the device added with a password, this is just a sanity check
  1372. folderB := cfg.FolderMap()["b"]
  1373. found := false
  1374. for _, dev := range folderB.Devices {
  1375. if dev.DeviceID == foundUntrusted {
  1376. found = true
  1377. if dev.EncryptionPassword == "" {
  1378. t.Error("untrusted device should have a password in folder B")
  1379. }
  1380. }
  1381. }
  1382. if !found {
  1383. t.Error("untrusted device not found in folder B")
  1384. }
  1385. }
  1386. // Verify that opening a config with myID == protocol.EmptyDeviceID doesn't add that ID to the config.
  1387. // Done in various places where config is needed, but the device ID isn't known.
  1388. func TestLoadEmptyDeviceID(t *testing.T) {
  1389. temp, err := copyToTmp(testFs, "example.xml")
  1390. if err != nil {
  1391. t.Fatal(err)
  1392. }
  1393. fd, err := testFs.Open(temp)
  1394. if err != nil {
  1395. t.Fatal(err)
  1396. }
  1397. defer fd.Close()
  1398. cfg, _, err := ReadXML(fd, protocol.EmptyDeviceID)
  1399. if err != nil {
  1400. t.Fatal(err)
  1401. }
  1402. for _, devCfg := range cfg.Devices {
  1403. if devCfg.DeviceID == protocol.EmptyDeviceID {
  1404. t.Fatal("Device with empty ID")
  1405. }
  1406. }
  1407. for _, folderCfg := range cfg.Folders {
  1408. for _, devCfg := range folderCfg.Devices {
  1409. if devCfg.DeviceID == protocol.EmptyDeviceID {
  1410. t.Fatalf("Device with empty ID in folder %v", folderCfg.Description())
  1411. }
  1412. }
  1413. }
  1414. }
  1415. func loadTestFiles() {
  1416. entries, err := os.ReadDir("testdata")
  1417. if err != nil {
  1418. return
  1419. }
  1420. for _, e := range entries {
  1421. handleFile(e.Name())
  1422. }
  1423. }
  1424. func handleFile(name string) {
  1425. fd, err := testFs.Create(name)
  1426. if err != nil {
  1427. return
  1428. }
  1429. origin, _ := os.ReadFile(filepath.Join("testdata", name))
  1430. fd.Write(origin)
  1431. fd.Close()
  1432. }
  1433. func TestCopyMatching(t *testing.T) {
  1434. type Nested struct {
  1435. A int
  1436. }
  1437. type Test struct {
  1438. CopyA int
  1439. CopyB []string
  1440. CopyC Nested
  1441. CopyD *Nested
  1442. NoCopy int `restart:"true"`
  1443. }
  1444. from := Test{
  1445. CopyA: 1,
  1446. CopyB: []string{"friend", "foe"},
  1447. CopyC: Nested{
  1448. A: 2,
  1449. },
  1450. CopyD: &Nested{
  1451. A: 3,
  1452. },
  1453. NoCopy: 4,
  1454. }
  1455. to := Test{
  1456. CopyA: 11,
  1457. CopyB: []string{"foot", "toe"},
  1458. CopyC: Nested{
  1459. A: 22,
  1460. },
  1461. CopyD: &Nested{
  1462. A: 33,
  1463. },
  1464. NoCopy: 44,
  1465. }
  1466. // Copy empty fields
  1467. copyMatchingTag(&from, &to, "restart", func(v string) bool {
  1468. return v != "true"
  1469. })
  1470. if to.CopyA != 1 {
  1471. t.Error("CopyA")
  1472. }
  1473. if len(to.CopyB) != 2 || to.CopyB[0] != "friend" || to.CopyB[1] != "foe" {
  1474. t.Error("CopyB")
  1475. }
  1476. if to.CopyC.A != 2 {
  1477. t.Error("CopyC")
  1478. }
  1479. if to.CopyD.A != 3 {
  1480. t.Error("CopyC")
  1481. }
  1482. if to.NoCopy != 44 {
  1483. t.Error("NoCopy")
  1484. }
  1485. }