config.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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. "slices"
  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 = 51
  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 Defaults
  206. newCfg.Defaults.Folder = cfg.Defaults.Folder.Copy()
  207. newCfg.Defaults.Device = cfg.Defaults.Device.Copy()
  208. // Deep copy FolderConfigurations
  209. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  210. for i := range newCfg.Folders {
  211. newCfg.Folders[i] = cfg.Folders[i].Copy()
  212. }
  213. // Deep copy DeviceConfigurations
  214. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  215. for i := range newCfg.Devices {
  216. newCfg.Devices[i] = cfg.Devices[i].Copy()
  217. }
  218. newCfg.Options = cfg.Options.Copy()
  219. newCfg.GUI = cfg.GUI.Copy()
  220. // DeviceIDs are values
  221. newCfg.IgnoredDevices = make([]ObservedDevice, len(cfg.IgnoredDevices))
  222. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  223. return newCfg
  224. }
  225. func (cfg *Configuration) WriteXML(w io.Writer) error {
  226. e := xml.NewEncoder(w)
  227. e.Indent("", " ")
  228. xmlCfg := xmlConfiguration{Configuration: *cfg}
  229. err := e.Encode(xmlCfg)
  230. if err != nil {
  231. return err
  232. }
  233. _, err = w.Write([]byte("\n"))
  234. return err
  235. }
  236. func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
  237. cfg.ensureMyDevice(myID)
  238. existingDevices, err := cfg.prepareFoldersAndDevices(myID)
  239. if err != nil {
  240. return err
  241. }
  242. cfg.GUI.prepare()
  243. guiPWIsSet := cfg.GUI.User != "" && cfg.GUI.Password != ""
  244. cfg.Options.prepare(guiPWIsSet)
  245. cfg.prepareIgnoredDevices(existingDevices)
  246. cfg.Defaults.prepare(myID, existingDevices)
  247. cfg.removeDeprecatedProtocols()
  248. structutil.FillNilExceptDeprecated(cfg)
  249. // TestIssue1750 relies on migrations happening after preparing options.
  250. cfg.applyMigrations()
  251. return nil
  252. }
  253. func (cfg *Configuration) ensureMyDevice(myID protocol.DeviceID) {
  254. if myID == protocol.EmptyDeviceID {
  255. return
  256. }
  257. for _, device := range cfg.Devices {
  258. if device.DeviceID == myID {
  259. return
  260. }
  261. }
  262. myName, _ := os.Hostname()
  263. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  264. DeviceID: myID,
  265. Name: myName,
  266. })
  267. }
  268. func (cfg *Configuration) prepareFoldersAndDevices(myID protocol.DeviceID) (map[protocol.DeviceID]*DeviceConfiguration, error) {
  269. existingDevices := cfg.prepareDeviceList()
  270. sharedFolders, err := cfg.prepareFolders(myID, existingDevices)
  271. if err != nil {
  272. return nil, err
  273. }
  274. cfg.prepareDevices(sharedFolders)
  275. return existingDevices, nil
  276. }
  277. func (cfg *Configuration) prepareDeviceList() map[protocol.DeviceID]*DeviceConfiguration {
  278. // Ensure that the device list is
  279. // - free from duplicates
  280. // - no devices with empty ID
  281. // - sorted by ID
  282. // Happen before preparting folders as that needs a correct device list.
  283. cfg.Devices = ensureNoDuplicateOrEmptyIDDevices(cfg.Devices)
  284. slices.SortFunc(cfg.Devices, func(a, b DeviceConfiguration) int {
  285. return a.DeviceID.Compare(b.DeviceID)
  286. })
  287. // Build a list of available devices
  288. existingDevices := make(map[protocol.DeviceID]*DeviceConfiguration, len(cfg.Devices))
  289. for i, device := range cfg.Devices {
  290. existingDevices[device.DeviceID] = &cfg.Devices[i]
  291. }
  292. return existingDevices
  293. }
  294. func (cfg *Configuration) prepareFolders(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]*DeviceConfiguration) (map[protocol.DeviceID][]string, error) {
  295. // Prepare folders and check for duplicates. Duplicates are bad and
  296. // dangerous, can't currently be resolved in the GUI, and shouldn't
  297. // happen when configured by the GUI. We return with an error in that
  298. // situation.
  299. sharedFolders := make(map[protocol.DeviceID][]string, len(cfg.Devices))
  300. existingFolders := make(map[string]*FolderConfiguration, len(cfg.Folders))
  301. for i := range cfg.Folders {
  302. folder := &cfg.Folders[i]
  303. if folder.ID == "" {
  304. return nil, errFolderIDEmpty
  305. }
  306. if folder.Path == "" {
  307. return nil, fmt.Errorf("folder %q: %w", folder.ID, errFolderPathEmpty)
  308. }
  309. if _, ok := existingFolders[folder.ID]; ok {
  310. return nil, fmt.Errorf("folder %q: %w", folder.ID, errFolderIDDuplicate)
  311. }
  312. folder.prepare(myID, existingDevices)
  313. existingFolders[folder.ID] = folder
  314. for _, dev := range folder.Devices {
  315. sharedFolders[dev.DeviceID] = append(sharedFolders[dev.DeviceID], folder.ID)
  316. }
  317. }
  318. // Ensure that the folder list is sorted by ID
  319. slices.SortFunc(cfg.Folders, func(a, b FolderConfiguration) int {
  320. return strings.Compare(a.ID, b.ID)
  321. })
  322. return sharedFolders, nil
  323. }
  324. func (cfg *Configuration) prepareDevices(sharedFolders map[protocol.DeviceID][]string) {
  325. for i := range cfg.Devices {
  326. cfg.Devices[i].prepare(sharedFolders[cfg.Devices[i].DeviceID])
  327. }
  328. }
  329. func (cfg *Configuration) prepareIgnoredDevices(existingDevices map[protocol.DeviceID]*DeviceConfiguration) map[protocol.DeviceID]bool {
  330. // The list of ignored devices should not contain any devices that have
  331. // been manually added to the config.
  332. newIgnoredDevices := cfg.IgnoredDevices[:0]
  333. ignoredDevices := make(map[protocol.DeviceID]bool, len(cfg.IgnoredDevices))
  334. for _, dev := range cfg.IgnoredDevices {
  335. if _, ok := existingDevices[dev.ID]; !ok {
  336. ignoredDevices[dev.ID] = true
  337. newIgnoredDevices = append(newIgnoredDevices, dev)
  338. }
  339. }
  340. cfg.IgnoredDevices = newIgnoredDevices
  341. return ignoredDevices
  342. }
  343. func (cfg *Configuration) removeDeprecatedProtocols() {
  344. // Deprecated protocols are removed from the list of listeners and
  345. // device addresses. So far just kcp*.
  346. for _, prefix := range []string{"kcp"} {
  347. cfg.Options.RawListenAddresses = filterURLSchemePrefix(cfg.Options.RawListenAddresses, prefix)
  348. for i := range cfg.Devices {
  349. dev := &cfg.Devices[i]
  350. dev.Addresses = filterURLSchemePrefix(dev.Addresses, prefix)
  351. }
  352. }
  353. }
  354. func (cfg *Configuration) applyMigrations() {
  355. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  356. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  357. }
  358. // Upgrade configuration versions as appropriate
  359. migrationsMut.Lock()
  360. migrations.apply(cfg)
  361. migrationsMut.Unlock()
  362. }
  363. func (cfg *Configuration) Device(id protocol.DeviceID) (DeviceConfiguration, int, bool) {
  364. for i, device := range cfg.Devices {
  365. if device.DeviceID == id {
  366. return device, i, true
  367. }
  368. }
  369. return DeviceConfiguration{}, 0, false
  370. }
  371. // DeviceMap returns a map of device ID to device configuration for the given configuration.
  372. func (cfg *Configuration) DeviceMap() map[protocol.DeviceID]DeviceConfiguration {
  373. m := make(map[protocol.DeviceID]DeviceConfiguration, len(cfg.Devices))
  374. for _, dev := range cfg.Devices {
  375. m[dev.DeviceID] = dev
  376. }
  377. return m
  378. }
  379. func (cfg *Configuration) SetDevice(device DeviceConfiguration) {
  380. cfg.SetDevices([]DeviceConfiguration{device})
  381. }
  382. func (cfg *Configuration) SetDevices(devices []DeviceConfiguration) {
  383. inds := make(map[protocol.DeviceID]int, len(cfg.Devices))
  384. for i, device := range cfg.Devices {
  385. inds[device.DeviceID] = i
  386. }
  387. filtered := devices[:0]
  388. for _, device := range devices {
  389. if i, ok := inds[device.DeviceID]; ok {
  390. cfg.Devices[i] = device
  391. } else {
  392. filtered = append(filtered, device)
  393. }
  394. }
  395. cfg.Devices = append(cfg.Devices, filtered...)
  396. }
  397. func (cfg *Configuration) Folder(id string) (FolderConfiguration, int, bool) {
  398. for i, folder := range cfg.Folders {
  399. if folder.ID == id {
  400. return folder, i, true
  401. }
  402. }
  403. return FolderConfiguration{}, 0, false
  404. }
  405. // FolderMap returns a map of folder ID to folder configuration for the given configuration.
  406. func (cfg *Configuration) FolderMap() map[string]FolderConfiguration {
  407. m := make(map[string]FolderConfiguration, len(cfg.Folders))
  408. for _, folder := range cfg.Folders {
  409. m[folder.ID] = folder
  410. }
  411. return m
  412. }
  413. // FolderPasswords returns the folder passwords set for this device, for
  414. // folders that have an encryption password set.
  415. func (cfg Configuration) FolderPasswords(device protocol.DeviceID) map[string]string {
  416. res := make(map[string]string, len(cfg.Folders))
  417. for _, folder := range cfg.Folders {
  418. if dev, ok := folder.Device(device); ok && dev.EncryptionPassword != "" {
  419. res[folder.ID] = dev.EncryptionPassword
  420. }
  421. }
  422. return res
  423. }
  424. func (cfg *Configuration) SetFolder(folder FolderConfiguration) {
  425. cfg.SetFolders([]FolderConfiguration{folder})
  426. }
  427. func (cfg *Configuration) SetFolders(folders []FolderConfiguration) {
  428. inds := make(map[string]int, len(cfg.Folders))
  429. for i, folder := range cfg.Folders {
  430. inds[folder.ID] = i
  431. }
  432. filtered := folders[:0]
  433. for _, folder := range folders {
  434. if i, ok := inds[folder.ID]; ok {
  435. cfg.Folders[i] = folder
  436. } else {
  437. filtered = append(filtered, folder)
  438. }
  439. }
  440. cfg.Folders = append(cfg.Folders, filtered...)
  441. }
  442. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  443. if myID == protocol.EmptyDeviceID {
  444. return devices
  445. }
  446. for _, device := range devices {
  447. if device.DeviceID.Equals(myID) {
  448. return devices
  449. }
  450. }
  451. devices = append(devices, FolderDeviceConfiguration{
  452. DeviceID: myID,
  453. })
  454. return devices
  455. }
  456. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]*DeviceConfiguration) []FolderDeviceConfiguration {
  457. count := len(devices)
  458. i := 0
  459. loop:
  460. for i < count {
  461. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  462. devices[i] = devices[count-1]
  463. count--
  464. continue loop
  465. }
  466. i++
  467. }
  468. return devices[0:count]
  469. }
  470. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  471. count := len(devices)
  472. i := 0
  473. seenDevices := make(map[protocol.DeviceID]bool)
  474. loop:
  475. for i < count {
  476. id := devices[i].DeviceID
  477. if _, ok := seenDevices[id]; ok {
  478. devices[i] = devices[count-1]
  479. count--
  480. continue loop
  481. }
  482. seenDevices[id] = true
  483. i++
  484. }
  485. return devices[0:count]
  486. }
  487. func ensureNoDuplicateOrEmptyIDDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  488. count := len(devices)
  489. i := 0
  490. seenDevices := make(map[protocol.DeviceID]bool)
  491. loop:
  492. for i < count {
  493. id := devices[i].DeviceID
  494. if _, ok := seenDevices[id]; ok || id == protocol.EmptyDeviceID {
  495. devices[i] = devices[count-1]
  496. count--
  497. continue loop
  498. }
  499. seenDevices[id] = true
  500. i++
  501. }
  502. return devices[0:count]
  503. }
  504. func ensureNoUntrustedTrustingSharing(f *FolderConfiguration, devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]*DeviceConfiguration) []FolderDeviceConfiguration {
  505. for i := 0; i < len(devices); i++ {
  506. dev := devices[i]
  507. if dev.EncryptionPassword != "" || f.Type == FolderTypeReceiveEncrypted {
  508. // There's a password set or the folder is received encrypted, no check required
  509. continue
  510. }
  511. if devCfg := existingDevices[dev.DeviceID]; devCfg.Untrusted {
  512. 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)
  513. devices = sliceutil.RemoveAndZero(devices, i)
  514. i--
  515. }
  516. }
  517. return devices
  518. }
  519. func cleanSymlinks(filesystem fs.Filesystem, dir string) {
  520. if build.IsWindows {
  521. // We don't do symlinks on Windows. Additionally, there may
  522. // be things that look like symlinks that are not, which we
  523. // should leave alone. Deduplicated files, for example.
  524. return
  525. }
  526. filesystem.Walk(dir, func(path string, info fs.FileInfo, err error) error {
  527. if err != nil {
  528. return err
  529. }
  530. if info.IsSymlink() {
  531. l.Infoln("Removing incorrectly versioned symlink", path)
  532. filesystem.Remove(path)
  533. return fs.SkipDir
  534. }
  535. return nil
  536. })
  537. }
  538. // filterURLSchemePrefix returns the list of addresses after removing all
  539. // entries whose URL scheme matches the given prefix.
  540. func filterURLSchemePrefix(addrs []string, prefix string) []string {
  541. for i := 0; i < len(addrs); i++ {
  542. uri, err := url.Parse(addrs[i])
  543. if err != nil {
  544. continue
  545. }
  546. if strings.HasPrefix(uri.Scheme, prefix) {
  547. addrs = sliceutil.RemoveAndZero(addrs, i)
  548. i--
  549. }
  550. }
  551. return addrs
  552. }
  553. // tried in succession and the first to succeed is returned. If none succeed,
  554. // a random high port is returned.
  555. func getFreePort(host string, ports ...int) (int, error) {
  556. for _, port := range ports {
  557. c, err := net.Listen("tcp", net.JoinHostPort(host, strconv.Itoa(port)))
  558. if err == nil {
  559. c.Close()
  560. return port, nil
  561. }
  562. }
  563. c, err := net.Listen("tcp", host+":0")
  564. if err != nil {
  565. return 0, err
  566. }
  567. addr := c.Addr().(*net.TCPAddr)
  568. c.Close()
  569. return addr.Port, nil
  570. }
  571. func (defaults *Defaults) prepare(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]*DeviceConfiguration) {
  572. ensureZeroForNodefault(&FolderConfiguration{}, &defaults.Folder)
  573. ensureZeroForNodefault(&DeviceConfiguration{}, &defaults.Device)
  574. defaults.Folder.prepare(myID, existingDevices)
  575. defaults.Device.prepare(nil)
  576. }
  577. func ensureZeroForNodefault(empty interface{}, target interface{}) {
  578. copyMatchingTag(empty, target, "nodefault", func(v string) bool {
  579. if len(v) > 0 && v != "true" {
  580. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "true"`, v))
  581. }
  582. return len(v) > 0
  583. })
  584. }
  585. // copyMatchingTag copies fields tagged tag:"value" from "from" struct onto "to" struct.
  586. func copyMatchingTag(from interface{}, to interface{}, tag string, shouldCopy func(value string) bool) {
  587. fromStruct := reflect.ValueOf(from).Elem()
  588. fromType := fromStruct.Type()
  589. toStruct := reflect.ValueOf(to).Elem()
  590. toType := toStruct.Type()
  591. if fromType != toType {
  592. panic(fmt.Sprintf("non equal types: %s != %s", fromType, toType))
  593. }
  594. for i := 0; i < toStruct.NumField(); i++ {
  595. fromField := fromStruct.Field(i)
  596. toField := toStruct.Field(i)
  597. if !toField.CanSet() {
  598. // Unexported fields
  599. continue
  600. }
  601. structTag := toType.Field(i).Tag
  602. v := structTag.Get(tag)
  603. if shouldCopy(v) {
  604. toField.Set(fromField)
  605. }
  606. }
  607. }
  608. func (i Ignores) Copy() Ignores {
  609. out := Ignores{Lines: make([]string, len(i.Lines))}
  610. copy(out.Lines, i.Lines)
  611. return out
  612. }