config_test.go 43 KB

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