config.go 21 KB

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