config.go 19 KB

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