config.go 20 KB

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