config.go 21 KB

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