config.go 21 KB

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