config.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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 implements reading and writing of the syncthing configuration file.
  7. package config
  8. import (
  9. "encoding/json"
  10. "encoding/xml"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "net"
  15. "net/url"
  16. "os"
  17. "reflect"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "github.com/syncthing/syncthing/lib/build"
  22. "github.com/syncthing/syncthing/lib/fs"
  23. "github.com/syncthing/syncthing/lib/netutil"
  24. "github.com/syncthing/syncthing/lib/protocol"
  25. "github.com/syncthing/syncthing/lib/sliceutil"
  26. "github.com/syncthing/syncthing/lib/structutil"
  27. )
  28. const (
  29. OldestHandledVersion = 10
  30. CurrentVersion = 37
  31. MaxRescanIntervalS = 365 * 24 * 60 * 60
  32. )
  33. var (
  34. // DefaultTCPPort defines default TCP port used if the URI does not specify one, for example tcp://0.0.0.0
  35. DefaultTCPPort = 22000
  36. // DefaultQUICPort defines default QUIC port used if the URI does not specify one, for example quic://0.0.0.0
  37. DefaultQUICPort = 22000
  38. // DefaultListenAddresses should be substituted when the configuration
  39. // contains <listenAddress>default</listenAddress>. This is done by the
  40. // "consumer" of the configuration as we don't want these saved to the
  41. // config.
  42. DefaultListenAddresses = []string{
  43. netutil.AddressURL("tcp", net.JoinHostPort("0.0.0.0", strconv.Itoa(DefaultTCPPort))),
  44. "dynamic+https://relays.syncthing.net/endpoint",
  45. netutil.AddressURL("quic", net.JoinHostPort("0.0.0.0", strconv.Itoa(DefaultQUICPort))),
  46. }
  47. DefaultGUIPort = 8384
  48. // DefaultDiscoveryServersV4 should be substituted when the configuration
  49. // contains <globalAnnounceServer>default-v4</globalAnnounceServer>.
  50. DefaultDiscoveryServersV4 = []string{
  51. "https://discovery.syncthing.net/v2/?noannounce&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  52. "https://discovery-v4.syncthing.net/v2/?nolookup&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  53. }
  54. // DefaultDiscoveryServersV6 should be substituted when the configuration
  55. // contains <globalAnnounceServer>default-v6</globalAnnounceServer>.
  56. DefaultDiscoveryServersV6 = []string{
  57. "https://discovery.syncthing.net/v2/?noannounce&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  58. "https://discovery-v6.syncthing.net/v2/?nolookup&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  59. }
  60. // DefaultDiscoveryServers should be substituted when the configuration
  61. // contains <globalAnnounceServer>default</globalAnnounceServer>.
  62. DefaultDiscoveryServers = append(DefaultDiscoveryServersV4, DefaultDiscoveryServersV6...)
  63. // DefaultTheme is the default and fallback theme for the web UI.
  64. DefaultTheme = "default"
  65. // Default stun servers should be substituted when the configuration
  66. // contains <stunServer>default</stunServer>.
  67. // DefaultPrimaryStunServers are servers provided by us (to avoid causing the public servers burden)
  68. DefaultPrimaryStunServers = []string{
  69. "stun.syncthing.net:3478",
  70. }
  71. DefaultSecondaryStunServers = []string{
  72. "stun.callwithus.com:3478",
  73. "stun.counterpath.com:3478",
  74. "stun.counterpath.net:3478",
  75. "stun.ekiga.net:3478",
  76. "stun.ideasip.com:3478",
  77. "stun.internetcalls.com:3478",
  78. "stun.schlund.de:3478",
  79. "stun.sipgate.net:10000",
  80. "stun.sipgate.net:3478",
  81. "stun.voip.aebc.com:3478",
  82. "stun.voiparound.com:3478",
  83. "stun.voipbuster.com:3478",
  84. "stun.voipstunt.com:3478",
  85. "stun.xten.com:3478",
  86. }
  87. )
  88. var (
  89. errFolderIDEmpty = errors.New("folder has empty ID")
  90. errFolderIDDuplicate = errors.New("folder has duplicate ID")
  91. errFolderPathEmpty = errors.New("folder has empty path")
  92. )
  93. func New(myID protocol.DeviceID) Configuration {
  94. var cfg Configuration
  95. cfg.Version = CurrentVersion
  96. cfg.Options.UnackedNotificationIDs = []string{"authenticationUserAndPassword"}
  97. structutil.SetDefaults(&cfg)
  98. // Can't happen.
  99. if err := cfg.prepare(myID); err != nil {
  100. l.Warnln("bug: error in preparing new folder:", err)
  101. panic("error in preparing new folder")
  102. }
  103. return cfg
  104. }
  105. func (cfg *Configuration) ProbeFreePorts() error {
  106. port, err := getFreePort("127.0.0.1", DefaultGUIPort)
  107. if err != nil {
  108. return fmt.Errorf("get free port (GUI): %w", err)
  109. }
  110. cfg.GUI.RawAddress = fmt.Sprintf("127.0.0.1:%d", port)
  111. port, err = getFreePort("0.0.0.0", DefaultTCPPort)
  112. if err != nil {
  113. return fmt.Errorf("get free port (BEP): %w", err)
  114. }
  115. if port == DefaultTCPPort {
  116. cfg.Options.RawListenAddresses = []string{"default"}
  117. } else {
  118. cfg.Options.RawListenAddresses = []string{
  119. netutil.AddressURL("tcp", net.JoinHostPort("0.0.0.0", strconv.Itoa(port))),
  120. "dynamic+https://relays.syncthing.net/endpoint",
  121. netutil.AddressURL("quic", net.JoinHostPort("0.0.0.0", strconv.Itoa(port))),
  122. }
  123. }
  124. return nil
  125. }
  126. type xmlConfiguration struct {
  127. Configuration
  128. XMLName xml.Name `xml:"configuration"`
  129. }
  130. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, int, error) {
  131. var cfg xmlConfiguration
  132. structutil.SetDefaults(&cfg)
  133. if err := xml.NewDecoder(r).Decode(&cfg); err != nil {
  134. return Configuration{}, 0, err
  135. }
  136. originalVersion := cfg.Version
  137. if err := cfg.prepare(myID); err != nil {
  138. return Configuration{}, originalVersion, err
  139. }
  140. return cfg.Configuration, originalVersion, nil
  141. }
  142. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  143. bs, err := io.ReadAll(r)
  144. if err != nil {
  145. return Configuration{}, err
  146. }
  147. var cfg Configuration
  148. structutil.SetDefaults(&cfg)
  149. if err := json.Unmarshal(bs, &cfg); err != nil {
  150. return Configuration{}, err
  151. }
  152. // Unmarshal list of devices and folders separately to set defaults
  153. var rawFoldersDevices struct {
  154. Folders []json.RawMessage
  155. Devices []json.RawMessage
  156. }
  157. if err := json.Unmarshal(bs, &rawFoldersDevices); err != nil {
  158. return Configuration{}, err
  159. }
  160. cfg.Folders = make([]FolderConfiguration, len(rawFoldersDevices.Folders))
  161. for i, bs := range rawFoldersDevices.Folders {
  162. cfg.Folders[i] = cfg.Defaults.Folder.Copy()
  163. if err := json.Unmarshal(bs, &cfg.Folders[i]); err != nil {
  164. return Configuration{}, err
  165. }
  166. }
  167. cfg.Devices = make([]DeviceConfiguration, len(rawFoldersDevices.Devices))
  168. for i, bs := range rawFoldersDevices.Devices {
  169. cfg.Devices[i] = cfg.Defaults.Device.Copy()
  170. if err := json.Unmarshal(bs, &cfg.Devices[i]); err != nil {
  171. return Configuration{}, err
  172. }
  173. }
  174. if err := cfg.prepare(myID); err != nil {
  175. return Configuration{}, err
  176. }
  177. return cfg, nil
  178. }
  179. func (cfg Configuration) Copy() Configuration {
  180. newCfg := cfg
  181. // Deep copy FolderConfigurations
  182. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  183. for i := range newCfg.Folders {
  184. newCfg.Folders[i] = cfg.Folders[i].Copy()
  185. }
  186. // Deep copy DeviceConfigurations
  187. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  188. for i := range newCfg.Devices {
  189. newCfg.Devices[i] = cfg.Devices[i].Copy()
  190. }
  191. newCfg.Options = cfg.Options.Copy()
  192. newCfg.GUI = cfg.GUI.Copy()
  193. // DeviceIDs are values
  194. newCfg.IgnoredDevices = make([]ObservedDevice, len(cfg.IgnoredDevices))
  195. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  196. return newCfg
  197. }
  198. func (cfg *Configuration) WriteXML(w io.Writer) error {
  199. e := xml.NewEncoder(w)
  200. e.Indent("", " ")
  201. xmlCfg := xmlConfiguration{Configuration: *cfg}
  202. err := e.Encode(xmlCfg)
  203. if err != nil {
  204. return err
  205. }
  206. _, err = w.Write([]byte("\n"))
  207. return err
  208. }
  209. func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
  210. cfg.ensureMyDevice(myID)
  211. existingDevices, err := cfg.prepareFoldersAndDevices(myID)
  212. if err != nil {
  213. return err
  214. }
  215. cfg.GUI.prepare()
  216. guiPWIsSet := cfg.GUI.User != "" && cfg.GUI.Password != ""
  217. cfg.Options.prepare(guiPWIsSet)
  218. cfg.prepareIgnoredDevices(existingDevices)
  219. cfg.Defaults.prepare(myID, existingDevices)
  220. cfg.removeDeprecatedProtocols()
  221. structutil.FillNilExceptDeprecated(cfg)
  222. // TestIssue1750 relies on migrations happening after preparing options.
  223. cfg.applyMigrations()
  224. return nil
  225. }
  226. func (cfg *Configuration) ensureMyDevice(myID protocol.DeviceID) {
  227. if myID == protocol.EmptyDeviceID {
  228. return
  229. }
  230. for _, device := range cfg.Devices {
  231. if device.DeviceID == myID {
  232. return
  233. }
  234. }
  235. myName, _ := os.Hostname()
  236. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  237. DeviceID: myID,
  238. Name: myName,
  239. })
  240. }
  241. func (cfg *Configuration) prepareFoldersAndDevices(myID protocol.DeviceID) (map[protocol.DeviceID]*DeviceConfiguration, error) {
  242. existingDevices := cfg.prepareDeviceList()
  243. sharedFolders, err := cfg.prepareFolders(myID, existingDevices)
  244. if err != nil {
  245. return nil, err
  246. }
  247. cfg.prepareDevices(sharedFolders)
  248. return existingDevices, nil
  249. }
  250. func (cfg *Configuration) prepareDeviceList() map[protocol.DeviceID]*DeviceConfiguration {
  251. // Ensure that the device list is
  252. // - free from duplicates
  253. // - no devices with empty ID
  254. // - sorted by ID
  255. // Happen before preparting folders as that needs a correct device list.
  256. cfg.Devices = ensureNoDuplicateOrEmptyIDDevices(cfg.Devices)
  257. sort.Slice(cfg.Devices, func(a, b int) bool {
  258. return cfg.Devices[a].DeviceID.Compare(cfg.Devices[b].DeviceID) == -1
  259. })
  260. // Build a list of available devices
  261. existingDevices := make(map[protocol.DeviceID]*DeviceConfiguration, len(cfg.Devices))
  262. for i, device := range cfg.Devices {
  263. existingDevices[device.DeviceID] = &cfg.Devices[i]
  264. }
  265. return existingDevices
  266. }
  267. func (cfg *Configuration) prepareFolders(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]*DeviceConfiguration) (map[protocol.DeviceID][]string, error) {
  268. // Prepare folders and check for duplicates. Duplicates are bad and
  269. // dangerous, can't currently be resolved in the GUI, and shouldn't
  270. // happen when configured by the GUI. We return with an error in that
  271. // situation.
  272. sharedFolders := make(map[protocol.DeviceID][]string, len(cfg.Devices))
  273. existingFolders := make(map[string]*FolderConfiguration, len(cfg.Folders))
  274. for i := range cfg.Folders {
  275. folder := &cfg.Folders[i]
  276. if folder.ID == "" {
  277. return nil, errFolderIDEmpty
  278. }
  279. if folder.Path == "" {
  280. return nil, fmt.Errorf("folder %q: %w", folder.ID, errFolderPathEmpty)
  281. }
  282. if _, ok := existingFolders[folder.ID]; ok {
  283. return nil, fmt.Errorf("folder %q: %w", folder.ID, errFolderIDDuplicate)
  284. }
  285. folder.prepare(myID, existingDevices)
  286. existingFolders[folder.ID] = folder
  287. for _, dev := range folder.Devices {
  288. sharedFolders[dev.DeviceID] = append(sharedFolders[dev.DeviceID], folder.ID)
  289. }
  290. }
  291. // Ensure that the folder list is sorted by ID
  292. sort.Slice(cfg.Folders, func(a, b int) bool {
  293. return cfg.Folders[a].ID < cfg.Folders[b].ID
  294. })
  295. return sharedFolders, nil
  296. }
  297. func (cfg *Configuration) prepareDevices(sharedFolders map[protocol.DeviceID][]string) {
  298. for i := range cfg.Devices {
  299. cfg.Devices[i].prepare(sharedFolders[cfg.Devices[i].DeviceID])
  300. }
  301. }
  302. func (cfg *Configuration) prepareIgnoredDevices(existingDevices map[protocol.DeviceID]*DeviceConfiguration) map[protocol.DeviceID]bool {
  303. // The list of ignored devices should not contain any devices that have
  304. // been manually added to the config.
  305. newIgnoredDevices := cfg.IgnoredDevices[:0]
  306. ignoredDevices := make(map[protocol.DeviceID]bool, len(cfg.IgnoredDevices))
  307. for _, dev := range cfg.IgnoredDevices {
  308. if _, ok := existingDevices[dev.ID]; !ok {
  309. ignoredDevices[dev.ID] = true
  310. newIgnoredDevices = append(newIgnoredDevices, dev)
  311. }
  312. }
  313. cfg.IgnoredDevices = newIgnoredDevices
  314. return ignoredDevices
  315. }
  316. func (cfg *Configuration) removeDeprecatedProtocols() {
  317. // Deprecated protocols are removed from the list of listeners and
  318. // device addresses. So far just kcp*.
  319. for _, prefix := range []string{"kcp"} {
  320. cfg.Options.RawListenAddresses = filterURLSchemePrefix(cfg.Options.RawListenAddresses, prefix)
  321. for i := range cfg.Devices {
  322. dev := &cfg.Devices[i]
  323. dev.Addresses = filterURLSchemePrefix(dev.Addresses, prefix)
  324. }
  325. }
  326. }
  327. func (cfg *Configuration) applyMigrations() {
  328. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  329. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  330. }
  331. // Upgrade configuration versions as appropriate
  332. migrationsMut.Lock()
  333. migrations.apply(cfg)
  334. migrationsMut.Unlock()
  335. }
  336. func (cfg *Configuration) Device(id protocol.DeviceID) (DeviceConfiguration, int, bool) {
  337. for i, device := range cfg.Devices {
  338. if device.DeviceID == id {
  339. return device, i, true
  340. }
  341. }
  342. return DeviceConfiguration{}, 0, false
  343. }
  344. // DeviceMap returns a map of device ID to device configuration for the given configuration.
  345. func (cfg *Configuration) DeviceMap() map[protocol.DeviceID]DeviceConfiguration {
  346. m := make(map[protocol.DeviceID]DeviceConfiguration, len(cfg.Devices))
  347. for _, dev := range cfg.Devices {
  348. m[dev.DeviceID] = dev
  349. }
  350. return m
  351. }
  352. func (cfg *Configuration) SetDevice(device DeviceConfiguration) {
  353. cfg.SetDevices([]DeviceConfiguration{device})
  354. }
  355. func (cfg *Configuration) SetDevices(devices []DeviceConfiguration) {
  356. inds := make(map[protocol.DeviceID]int, len(cfg.Devices))
  357. for i, device := range cfg.Devices {
  358. inds[device.DeviceID] = i
  359. }
  360. filtered := devices[:0]
  361. for _, device := range devices {
  362. if i, ok := inds[device.DeviceID]; ok {
  363. cfg.Devices[i] = device
  364. } else {
  365. filtered = append(filtered, device)
  366. }
  367. }
  368. cfg.Devices = append(cfg.Devices, filtered...)
  369. }
  370. func (cfg *Configuration) Folder(id string) (FolderConfiguration, int, bool) {
  371. for i, folder := range cfg.Folders {
  372. if folder.ID == id {
  373. return folder, i, true
  374. }
  375. }
  376. return FolderConfiguration{}, 0, false
  377. }
  378. // FolderMap returns a map of folder ID to folder configuration for the given configuration.
  379. func (cfg *Configuration) FolderMap() map[string]FolderConfiguration {
  380. m := make(map[string]FolderConfiguration, len(cfg.Folders))
  381. for _, folder := range cfg.Folders {
  382. m[folder.ID] = folder
  383. }
  384. return m
  385. }
  386. // FolderPasswords returns the folder passwords set for this device, for
  387. // folders that have an encryption password set.
  388. func (cfg Configuration) FolderPasswords(device protocol.DeviceID) map[string]string {
  389. res := make(map[string]string, len(cfg.Folders))
  390. for _, folder := range cfg.Folders {
  391. if dev, ok := folder.Device(device); ok && dev.EncryptionPassword != "" {
  392. res[folder.ID] = dev.EncryptionPassword
  393. }
  394. }
  395. return res
  396. }
  397. func (cfg *Configuration) SetFolder(folder FolderConfiguration) {
  398. cfg.SetFolders([]FolderConfiguration{folder})
  399. }
  400. func (cfg *Configuration) SetFolders(folders []FolderConfiguration) {
  401. inds := make(map[string]int, len(cfg.Folders))
  402. for i, folder := range cfg.Folders {
  403. inds[folder.ID] = i
  404. }
  405. filtered := folders[:0]
  406. for _, folder := range folders {
  407. if i, ok := inds[folder.ID]; ok {
  408. cfg.Folders[i] = folder
  409. } else {
  410. filtered = append(filtered, folder)
  411. }
  412. }
  413. cfg.Folders = append(cfg.Folders, filtered...)
  414. }
  415. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  416. if myID == protocol.EmptyDeviceID {
  417. return devices
  418. }
  419. for _, device := range devices {
  420. if device.DeviceID.Equals(myID) {
  421. return devices
  422. }
  423. }
  424. devices = append(devices, FolderDeviceConfiguration{
  425. DeviceID: myID,
  426. })
  427. return devices
  428. }
  429. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]*DeviceConfiguration) []FolderDeviceConfiguration {
  430. count := len(devices)
  431. i := 0
  432. loop:
  433. for i < count {
  434. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  435. devices[i] = devices[count-1]
  436. count--
  437. continue loop
  438. }
  439. i++
  440. }
  441. return devices[0:count]
  442. }
  443. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  444. count := len(devices)
  445. i := 0
  446. seenDevices := make(map[protocol.DeviceID]bool)
  447. loop:
  448. for i < count {
  449. id := devices[i].DeviceID
  450. if _, ok := seenDevices[id]; ok {
  451. devices[i] = devices[count-1]
  452. count--
  453. continue loop
  454. }
  455. seenDevices[id] = true
  456. i++
  457. }
  458. return devices[0:count]
  459. }
  460. func ensureNoDuplicateOrEmptyIDDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  461. count := len(devices)
  462. i := 0
  463. seenDevices := make(map[protocol.DeviceID]bool)
  464. loop:
  465. for i < count {
  466. id := devices[i].DeviceID
  467. if _, ok := seenDevices[id]; ok || id == protocol.EmptyDeviceID {
  468. devices[i] = devices[count-1]
  469. count--
  470. continue loop
  471. }
  472. seenDevices[id] = true
  473. i++
  474. }
  475. return devices[0:count]
  476. }
  477. func ensureNoUntrustedTrustingSharing(f *FolderConfiguration, devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]*DeviceConfiguration) []FolderDeviceConfiguration {
  478. for i := 0; i < len(devices); i++ {
  479. dev := devices[i]
  480. if dev.EncryptionPassword != "" || f.Type == FolderTypeReceiveEncrypted {
  481. // There's a password set or the folder is received encrypted, no check required
  482. continue
  483. }
  484. if devCfg := existingDevices[dev.DeviceID]; devCfg.Untrusted {
  485. l.Warnf("Folder %s (%s) is shared in trusted mode with untrusted device %s (%s); unsharing.", f.ID, f.Label, dev.DeviceID.Short(), devCfg.Name)
  486. devices = sliceutil.RemoveAndZero(devices, i)
  487. i--
  488. }
  489. }
  490. return devices
  491. }
  492. func cleanSymlinks(filesystem fs.Filesystem, dir string) {
  493. if build.IsWindows {
  494. // We don't do symlinks on Windows. Additionally, there may
  495. // be things that look like symlinks that are not, which we
  496. // should leave alone. Deduplicated files, for example.
  497. return
  498. }
  499. filesystem.Walk(dir, func(path string, info fs.FileInfo, err error) error {
  500. if err != nil {
  501. return err
  502. }
  503. if info.IsSymlink() {
  504. l.Infoln("Removing incorrectly versioned symlink", path)
  505. filesystem.Remove(path)
  506. return fs.SkipDir
  507. }
  508. return nil
  509. })
  510. }
  511. // filterURLSchemePrefix returns the list of addresses after removing all
  512. // entries whose URL scheme matches the given prefix.
  513. func filterURLSchemePrefix(addrs []string, prefix string) []string {
  514. for i := 0; i < len(addrs); i++ {
  515. uri, err := url.Parse(addrs[i])
  516. if err != nil {
  517. continue
  518. }
  519. if strings.HasPrefix(uri.Scheme, prefix) {
  520. addrs = sliceutil.RemoveAndZero(addrs, i)
  521. i--
  522. }
  523. }
  524. return addrs
  525. }
  526. // tried in succession and the first to succeed is returned. If none succeed,
  527. // a random high port is returned.
  528. func getFreePort(host string, ports ...int) (int, error) {
  529. for _, port := range ports {
  530. c, err := net.Listen("tcp", net.JoinHostPort(host, strconv.Itoa(port)))
  531. if err == nil {
  532. c.Close()
  533. return port, nil
  534. }
  535. }
  536. c, err := net.Listen("tcp", host+":0")
  537. if err != nil {
  538. return 0, err
  539. }
  540. addr := c.Addr().(*net.TCPAddr)
  541. c.Close()
  542. return addr.Port, nil
  543. }
  544. func (defaults *Defaults) prepare(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]*DeviceConfiguration) {
  545. ensureZeroForNodefault(&FolderConfiguration{}, &defaults.Folder)
  546. ensureZeroForNodefault(&DeviceConfiguration{}, &defaults.Device)
  547. defaults.Folder.prepare(myID, existingDevices)
  548. defaults.Device.prepare(nil)
  549. }
  550. func ensureZeroForNodefault(empty interface{}, target interface{}) {
  551. copyMatchingTag(empty, target, "nodefault", func(v string) bool {
  552. if len(v) > 0 && v != "true" {
  553. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "true"`, v))
  554. }
  555. return len(v) > 0
  556. })
  557. }
  558. // copyMatchingTag copies fields tagged tag:"value" from "from" struct onto "to" struct.
  559. func copyMatchingTag(from interface{}, to interface{}, tag string, shouldCopy func(value string) bool) {
  560. fromStruct := reflect.ValueOf(from).Elem()
  561. fromType := fromStruct.Type()
  562. toStruct := reflect.ValueOf(to).Elem()
  563. toType := toStruct.Type()
  564. if fromType != toType {
  565. panic(fmt.Sprintf("non equal types: %s != %s", fromType, toType))
  566. }
  567. for i := 0; i < toStruct.NumField(); i++ {
  568. fromField := fromStruct.Field(i)
  569. toField := toStruct.Field(i)
  570. if !toField.CanSet() {
  571. // Unexported fields
  572. continue
  573. }
  574. structTag := toType.Field(i).Tag
  575. v := structTag.Get(tag)
  576. if shouldCopy(v) {
  577. toField.Set(fromField)
  578. }
  579. }
  580. }
  581. func (i Ignores) Copy() Ignores {
  582. out := Ignores{Lines: make([]string, len(i.Lines))}
  583. copy(out.Lines, i.Lines)
  584. return out
  585. }