config.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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 http://mozilla.org/MPL/2.0/.
  6. // Package config implements reading and writing of the syncthing configuration file.
  7. package config
  8. import (
  9. "encoding/xml"
  10. "fmt"
  11. "io"
  12. "math/rand"
  13. "os"
  14. "path/filepath"
  15. "reflect"
  16. "runtime"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "github.com/syncthing/protocol"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "golang.org/x/crypto/bcrypt"
  23. )
  24. const (
  25. OldestHandledVersion = 5
  26. CurrentVersion = 12
  27. MaxRescanIntervalS = 365 * 24 * 60 * 60
  28. )
  29. type Configuration struct {
  30. Version int `xml:"version,attr" json:"version"`
  31. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  32. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  33. GUI GUIConfiguration `xml:"gui" json:"gui"`
  34. Options OptionsConfiguration `xml:"options" json:"options"`
  35. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  36. XMLName xml.Name `xml:"configuration" json:"-"`
  37. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  38. }
  39. func (cfg Configuration) Copy() Configuration {
  40. newCfg := cfg
  41. // Deep copy FolderConfigurations
  42. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  43. for i := range newCfg.Folders {
  44. newCfg.Folders[i] = cfg.Folders[i].Copy()
  45. }
  46. // Deep copy DeviceConfigurations
  47. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  48. for i := range newCfg.Devices {
  49. newCfg.Devices[i] = cfg.Devices[i].Copy()
  50. }
  51. newCfg.Options = cfg.Options.Copy()
  52. // DeviceIDs are values
  53. newCfg.IgnoredDevices = make([]protocol.DeviceID, len(cfg.IgnoredDevices))
  54. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  55. return newCfg
  56. }
  57. type FolderConfiguration struct {
  58. ID string `xml:"id,attr" json:"id"`
  59. RawPath string `xml:"path,attr" json:"path"`
  60. Devices []FolderDeviceConfiguration `xml:"device" json:"devices"`
  61. ReadOnly bool `xml:"ro,attr" json:"readOnly"`
  62. RescanIntervalS int `xml:"rescanIntervalS,attr" json:"rescanIntervalS"`
  63. IgnorePerms bool `xml:"ignorePerms,attr" json:"ignorePerms"`
  64. AutoNormalize bool `xml:"autoNormalize,attr" json:"autoNormalize"`
  65. MinDiskFreePct float64 `xml:"minDiskFreePct" json:"minDiskFreePct"`
  66. Versioning VersioningConfiguration `xml:"versioning" json:"versioning"`
  67. Copiers int `xml:"copiers" json:"copiers"` // This defines how many files are handled concurrently.
  68. Pullers int `xml:"pullers" json:"pullers"` // Defines how many blocks are fetched at the same time, possibly between separate copier routines.
  69. Hashers int `xml:"hashers" json:"hashers"` // Less than one sets the value to the number of cores. These are CPU bound due to hashing.
  70. Order PullOrder `xml:"order" json:"order"`
  71. IgnoreDelete bool `xml:"ignoreDelete" json:"ignoreDelete"`
  72. ScanProgressIntervalS int `xml:"scanProgressInterval" json:"scanProgressInterval"` // Set to a negative value to disable. Value of 0 will get replaced with value of 2 (default value)
  73. Invalid string `xml:"-" json:"invalid"` // Set at runtime when there is an error, not saved
  74. }
  75. func (f FolderConfiguration) Copy() FolderConfiguration {
  76. c := f
  77. c.Devices = make([]FolderDeviceConfiguration, len(f.Devices))
  78. copy(c.Devices, f.Devices)
  79. return c
  80. }
  81. func (f FolderConfiguration) Path() string {
  82. // This is intentionally not a pointer method, because things like
  83. // cfg.Folders["default"].Path() should be valid.
  84. // Attempt tilde expansion; leave unchanged in case of error
  85. if path, err := osutil.ExpandTilde(f.RawPath); err == nil {
  86. f.RawPath = path
  87. }
  88. // Attempt absolutification; leave unchanged in case of error
  89. if !filepath.IsAbs(f.RawPath) {
  90. // Abs() looks like a fairly expensive syscall on Windows, while
  91. // IsAbs() is a whole bunch of string mangling. I think IsAbs() may be
  92. // somewhat faster in the general case, hence the outer if...
  93. if path, err := filepath.Abs(f.RawPath); err == nil {
  94. f.RawPath = path
  95. }
  96. }
  97. // Attempt to enable long filename support on Windows. We may still not
  98. // have an absolute path here if the previous steps failed.
  99. if runtime.GOOS == "windows" && filepath.IsAbs(f.RawPath) && !strings.HasPrefix(f.RawPath, `\\`) {
  100. return `\\?\` + f.RawPath
  101. }
  102. return f.RawPath
  103. }
  104. func (f *FolderConfiguration) CreateMarker() error {
  105. if !f.HasMarker() {
  106. marker := filepath.Join(f.Path(), ".stfolder")
  107. fd, err := os.Create(marker)
  108. if err != nil {
  109. return err
  110. }
  111. fd.Close()
  112. osutil.HideFile(marker)
  113. }
  114. return nil
  115. }
  116. func (f *FolderConfiguration) HasMarker() bool {
  117. _, err := os.Stat(filepath.Join(f.Path(), ".stfolder"))
  118. if err != nil {
  119. return false
  120. }
  121. return true
  122. }
  123. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  124. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  125. for i, n := range f.Devices {
  126. deviceIDs[i] = n.DeviceID
  127. }
  128. return deviceIDs
  129. }
  130. type VersioningConfiguration struct {
  131. Type string `xml:"type,attr" json:"type"`
  132. Params map[string]string `json:"params"`
  133. }
  134. type InternalVersioningConfiguration struct {
  135. Type string `xml:"type,attr,omitempty"`
  136. Params []InternalParam `xml:"param"`
  137. }
  138. type InternalParam struct {
  139. Key string `xml:"key,attr"`
  140. Val string `xml:"val,attr"`
  141. }
  142. func (c *VersioningConfiguration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  143. var tmp InternalVersioningConfiguration
  144. tmp.Type = c.Type
  145. for k, v := range c.Params {
  146. tmp.Params = append(tmp.Params, InternalParam{k, v})
  147. }
  148. return e.EncodeElement(tmp, start)
  149. }
  150. func (c *VersioningConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  151. var tmp InternalVersioningConfiguration
  152. err := d.DecodeElement(&tmp, &start)
  153. if err != nil {
  154. return err
  155. }
  156. c.Type = tmp.Type
  157. c.Params = make(map[string]string, len(tmp.Params))
  158. for _, p := range tmp.Params {
  159. c.Params[p.Key] = p.Val
  160. }
  161. return nil
  162. }
  163. type DeviceConfiguration struct {
  164. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  165. Name string `xml:"name,attr,omitempty" json:"name"`
  166. Addresses []string `xml:"address,omitempty" json:"addresses"`
  167. Compression protocol.Compression `xml:"compression,attr" json:"compression"`
  168. CertName string `xml:"certName,attr,omitempty" json:"certName"`
  169. Introducer bool `xml:"introducer,attr" json:"introducer"`
  170. }
  171. func (orig DeviceConfiguration) Copy() DeviceConfiguration {
  172. c := orig
  173. c.Addresses = make([]string, len(orig.Addresses))
  174. copy(c.Addresses, orig.Addresses)
  175. return c
  176. }
  177. type FolderDeviceConfiguration struct {
  178. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  179. }
  180. type OptionsConfiguration struct {
  181. ListenAddress []string `xml:"listenAddress" json:"listenAddress" default:"tcp://0.0.0.0:22000"`
  182. GlobalAnnServers []string `xml:"globalAnnounceServer" json:"globalAnnounceServers" json:"globalAnnounceServer" default:"udp4://announce.syncthing.net:22027, udp6://announce-v6.syncthing.net:22027"`
  183. GlobalAnnEnabled bool `xml:"globalAnnounceEnabled" json:"globalAnnounceEnabled" default:"true"`
  184. LocalAnnEnabled bool `xml:"localAnnounceEnabled" json:"localAnnounceEnabled" default:"true"`
  185. LocalAnnPort int `xml:"localAnnouncePort" json:"localAnnouncePort" default:"21027"`
  186. LocalAnnMCAddr string `xml:"localAnnounceMCAddr" json:"localAnnounceMCAddr" default:"[ff12::8384]:21027"`
  187. RelayServers []string `xml:"relayServer" json:"relayServers" default:"dynamic+https://relays.syncthing.net"`
  188. MaxSendKbps int `xml:"maxSendKbps" json:"maxSendKbps"`
  189. MaxRecvKbps int `xml:"maxRecvKbps" json:"maxRecvKbps"`
  190. ReconnectIntervalS int `xml:"reconnectionIntervalS" json:"reconnectionIntervalS" default:"60"`
  191. RelaysEnabled bool `xml:"relaysEnabled" json:"relaysEnabled" default:"true"`
  192. RelayReconnectIntervalM int `xml:"relayReconnectIntervalM" json:"relayReconnectIntervalM" default:"10"`
  193. RelayWithoutGlobalAnn bool `xml:"relayWithoutGlobalAnn" json:"relayWithoutGlobalAnn" default:"false"`
  194. StartBrowser bool `xml:"startBrowser" json:"startBrowser" default:"true"`
  195. UPnPEnabled bool `xml:"upnpEnabled" json:"upnpEnabled" default:"true"`
  196. UPnPLeaseM int `xml:"upnpLeaseMinutes" json:"upnpLeaseMinutes" default:"60"`
  197. UPnPRenewalM int `xml:"upnpRenewalMinutes" json:"upnpRenewalMinutes" default:"30"`
  198. UPnPTimeoutS int `xml:"upnpTimeoutSeconds" json:"upnpTimeoutSeconds" default:"10"`
  199. URAccepted int `xml:"urAccepted" json:"urAccepted"` // Accepted usage reporting version; 0 for off (undecided), -1 for off (permanently)
  200. URUniqueID string `xml:"urUniqueID" json:"urUniqueId"` // Unique ID for reporting purposes, regenerated when UR is turned on.
  201. URURL string `xml:"urURL" json:"urURL" default:"https://data.syncthing.net/newdata"`
  202. URPostInsecurely bool `xml:"urPostInsecurely" json:"urPostInsecurely" default:"false"` // For testing
  203. URInitialDelayS int `xml:"urInitialDelayS" json:"urInitialDelayS" default:"1800"`
  204. RestartOnWakeup bool `xml:"restartOnWakeup" json:"restartOnWakeup" default:"true"`
  205. AutoUpgradeIntervalH int `xml:"autoUpgradeIntervalH" json:"autoUpgradeIntervalH" default:"12"` // 0 for off
  206. KeepTemporariesH int `xml:"keepTemporariesH" json:"keepTemporariesH" default:"24"` // 0 for off
  207. CacheIgnoredFiles bool `xml:"cacheIgnoredFiles" json:"cacheIgnoredFiles" default:"true"`
  208. ProgressUpdateIntervalS int `xml:"progressUpdateIntervalS" json:"progressUpdateIntervalS" default:"5"`
  209. SymlinksEnabled bool `xml:"symlinksEnabled" json:"symlinksEnabled" default:"true"`
  210. LimitBandwidthInLan bool `xml:"limitBandwidthInLan" json:"limitBandwidthInLan" default:"false"`
  211. DatabaseBlockCacheMiB int `xml:"databaseBlockCacheMiB" json:"databaseBlockCacheMiB" default:"0"`
  212. PingTimeoutS int `xml:"pingTimeoutS" json:"pingTimeoutS" default:"30"`
  213. PingIdleTimeS int `xml:"pingIdleTimeS" json:"pingIdleTimeS" default:"60"`
  214. MinHomeDiskFreePct float64 `xml:"minHomeDiskFreePct" json:"minHomeDiskFreePct" default:"1"`
  215. ReleasesURL string `xml:"releasesURL" json:"releasesURL" default:"https://api.github.com/repos/syncthing/syncthing/releases?per_page=30"`
  216. }
  217. func (orig OptionsConfiguration) Copy() OptionsConfiguration {
  218. c := orig
  219. c.ListenAddress = make([]string, len(orig.ListenAddress))
  220. copy(c.ListenAddress, orig.ListenAddress)
  221. c.GlobalAnnServers = make([]string, len(orig.GlobalAnnServers))
  222. copy(c.GlobalAnnServers, orig.GlobalAnnServers)
  223. return c
  224. }
  225. type GUIConfiguration struct {
  226. Enabled bool `xml:"enabled,attr" json:"enabled" default:"true"`
  227. Address string `xml:"address" json:"address" default:"127.0.0.1:8384"`
  228. User string `xml:"user,omitempty" json:"user"`
  229. Password string `xml:"password,omitempty" json:"password"`
  230. UseTLS bool `xml:"tls,attr" json:"useTLS"`
  231. APIKey string `xml:"apikey,omitempty" json:"apiKey"`
  232. }
  233. func New(myID protocol.DeviceID) Configuration {
  234. var cfg Configuration
  235. cfg.Version = CurrentVersion
  236. cfg.OriginalVersion = CurrentVersion
  237. setDefaults(&cfg)
  238. setDefaults(&cfg.Options)
  239. setDefaults(&cfg.GUI)
  240. cfg.prepare(myID)
  241. return cfg
  242. }
  243. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  244. var cfg Configuration
  245. setDefaults(&cfg)
  246. setDefaults(&cfg.Options)
  247. setDefaults(&cfg.GUI)
  248. err := xml.NewDecoder(r).Decode(&cfg)
  249. cfg.OriginalVersion = cfg.Version
  250. cfg.prepare(myID)
  251. return cfg, err
  252. }
  253. func (cfg *Configuration) WriteXML(w io.Writer) error {
  254. e := xml.NewEncoder(w)
  255. e.Indent("", " ")
  256. err := e.Encode(cfg)
  257. if err != nil {
  258. return err
  259. }
  260. _, err = w.Write([]byte("\n"))
  261. return err
  262. }
  263. func (cfg *Configuration) prepare(myID protocol.DeviceID) {
  264. fillNilSlices(&cfg.Options)
  265. // Initialize an empty slices
  266. if cfg.Folders == nil {
  267. cfg.Folders = []FolderConfiguration{}
  268. }
  269. if cfg.IgnoredDevices == nil {
  270. cfg.IgnoredDevices = []protocol.DeviceID{}
  271. }
  272. // Check for missing, bad or duplicate folder ID:s
  273. var seenFolders = map[string]*FolderConfiguration{}
  274. for i := range cfg.Folders {
  275. folder := &cfg.Folders[i]
  276. if len(folder.RawPath) == 0 {
  277. folder.Invalid = "no directory configured"
  278. continue
  279. }
  280. // The reason it's done like this:
  281. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  282. // C:\somedir -> C:\somedir\ -> C:\somedir
  283. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  284. // This way in the tests, we get away without OS specific separators
  285. // in the test configs.
  286. folder.RawPath = filepath.Dir(folder.RawPath + string(filepath.Separator))
  287. if folder.ID == "" {
  288. folder.ID = "default"
  289. }
  290. if folder.RescanIntervalS > MaxRescanIntervalS {
  291. folder.RescanIntervalS = MaxRescanIntervalS
  292. } else if folder.RescanIntervalS < 0 {
  293. folder.RescanIntervalS = 0
  294. }
  295. if seen, ok := seenFolders[folder.ID]; ok {
  296. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  297. seen.Invalid = "duplicate folder ID"
  298. folder.Invalid = "duplicate folder ID"
  299. } else {
  300. seenFolders[folder.ID] = folder
  301. }
  302. }
  303. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  304. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  305. if cfg.Version < OldestHandledVersion {
  306. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  307. }
  308. // Upgrade configuration versions as appropriate
  309. if cfg.Version <= 5 {
  310. convertV5V6(cfg)
  311. }
  312. if cfg.Version == 6 {
  313. convertV6V7(cfg)
  314. }
  315. if cfg.Version == 7 {
  316. convertV7V8(cfg)
  317. }
  318. if cfg.Version == 8 {
  319. convertV8V9(cfg)
  320. }
  321. if cfg.Version == 9 {
  322. convertV9V10(cfg)
  323. }
  324. if cfg.Version == 10 {
  325. convertV10V11(cfg)
  326. }
  327. if cfg.Version == 11 {
  328. convertV11V12(cfg)
  329. }
  330. // Hash old cleartext passwords
  331. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  332. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  333. if err != nil {
  334. l.Warnln("bcrypting password:", err)
  335. } else {
  336. cfg.GUI.Password = string(hash)
  337. }
  338. }
  339. // Build a list of available devices
  340. existingDevices := make(map[protocol.DeviceID]bool)
  341. for _, device := range cfg.Devices {
  342. existingDevices[device.DeviceID] = true
  343. }
  344. // Ensure this device is present in the config
  345. if !existingDevices[myID] {
  346. myName, _ := os.Hostname()
  347. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  348. DeviceID: myID,
  349. Name: myName,
  350. })
  351. existingDevices[myID] = true
  352. }
  353. sort.Sort(DeviceConfigurationList(cfg.Devices))
  354. // Ensure that any loose devices are not present in the wrong places
  355. // Ensure that there are no duplicate devices
  356. // Ensure that puller settings are sane
  357. for i := range cfg.Folders {
  358. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  359. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  360. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  361. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  362. }
  363. // An empty address list is equivalent to a single "dynamic" entry
  364. for i := range cfg.Devices {
  365. n := &cfg.Devices[i]
  366. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  367. n.Addresses = []string{"dynamic"}
  368. }
  369. }
  370. // Very short reconnection intervals are annoying
  371. if cfg.Options.ReconnectIntervalS < 5 {
  372. cfg.Options.ReconnectIntervalS = 5
  373. }
  374. if cfg.GUI.APIKey == "" {
  375. cfg.GUI.APIKey = randomString(32)
  376. }
  377. }
  378. // ChangeRequiresRestart returns true if updating the configuration requires a
  379. // complete restart.
  380. func ChangeRequiresRestart(from, to Configuration) bool {
  381. // Adding, removing or changing folders requires restart
  382. if !reflect.DeepEqual(from.Folders, to.Folders) {
  383. return true
  384. }
  385. // Removing a device requres restart
  386. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  387. for _, dev := range to.Devices {
  388. toDevs[dev.DeviceID] = true
  389. }
  390. for _, dev := range from.Devices {
  391. if _, ok := toDevs[dev.DeviceID]; !ok {
  392. return true
  393. }
  394. }
  395. // Changing usage reporting to on or off does not require a restart.
  396. to.Options.URAccepted = from.Options.URAccepted
  397. to.Options.URUniqueID = from.Options.URUniqueID
  398. // All of the generic options require restart
  399. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  400. return true
  401. }
  402. return false
  403. }
  404. func convertV10V11(cfg *Configuration) {
  405. // Set minimum disk free of existing folders to 1%
  406. for i := range cfg.Folders {
  407. cfg.Folders[i].MinDiskFreePct = 1
  408. }
  409. cfg.Version = 11
  410. }
  411. func convertV11V12(cfg *Configuration) {
  412. // Change listen address schema
  413. for i, addr := range cfg.Options.ListenAddress {
  414. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  415. cfg.Options.ListenAddress[i] = fmt.Sprintf("tcp://%s", addr)
  416. }
  417. }
  418. for i, device := range cfg.Devices {
  419. for j, addr := range device.Addresses {
  420. if addr != "dynamic" && addr != "" {
  421. cfg.Devices[i].Addresses[j] = fmt.Sprintf("tcp://%s", addr)
  422. }
  423. }
  424. }
  425. // Use new discovery server
  426. for i, addr := range cfg.Options.GlobalAnnServers {
  427. if addr == "udp4://announce.syncthing.net:22026" {
  428. cfg.Options.GlobalAnnServers[i] = "udp4://announce.syncthing.net:22027"
  429. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  430. cfg.Options.GlobalAnnServers[i] = "udp6://announce-v6.syncthing.net:22027"
  431. } else if addr == "udp4://194.126.249.5:22026" {
  432. cfg.Options.GlobalAnnServers[i] = "udp4://194.126.249.5:22027"
  433. } else if addr == "udp6://[2001:470:28:4d6::5]:22026" {
  434. cfg.Options.GlobalAnnServers[i] = "udp6://[2001:470:28:4d6::5]:22027"
  435. }
  436. }
  437. // Use new multicast group
  438. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  439. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  440. }
  441. // Use new local discovery port
  442. if cfg.Options.LocalAnnPort == 21025 {
  443. cfg.Options.LocalAnnPort = 21027
  444. }
  445. cfg.Version = 12
  446. }
  447. func convertV9V10(cfg *Configuration) {
  448. // Enable auto normalization on existing folders.
  449. for i := range cfg.Folders {
  450. cfg.Folders[i].AutoNormalize = true
  451. }
  452. cfg.Version = 10
  453. }
  454. func convertV8V9(cfg *Configuration) {
  455. // Compression is interpreted and serialized differently, but no enforced
  456. // changes. Still need a new version number since the compression stuff
  457. // isn't understandable by earlier versions.
  458. cfg.Version = 9
  459. }
  460. func convertV7V8(cfg *Configuration) {
  461. // Add IPv6 announce server
  462. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  463. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  464. }
  465. cfg.Version = 8
  466. }
  467. func convertV6V7(cfg *Configuration) {
  468. // Migrate announce server addresses to the new URL based format
  469. for i := range cfg.Options.GlobalAnnServers {
  470. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  471. }
  472. cfg.Version = 7
  473. }
  474. func convertV5V6(cfg *Configuration) {
  475. // Added ".stfolder" file at folder roots to identify mount issues
  476. // Doesn't affect the config itself, but uses config migrations to identify
  477. // the migration point.
  478. for _, folder := range Wrap("", *cfg).Folders() {
  479. // Best attempt, if it fails, it fails, the user will have to fix
  480. // it up manually, as the repo will not get started.
  481. folder.CreateMarker()
  482. }
  483. cfg.Version = 6
  484. }
  485. func setDefaults(data interface{}) error {
  486. s := reflect.ValueOf(data).Elem()
  487. t := s.Type()
  488. for i := 0; i < s.NumField(); i++ {
  489. f := s.Field(i)
  490. tag := t.Field(i).Tag
  491. v := tag.Get("default")
  492. if len(v) > 0 {
  493. switch f.Interface().(type) {
  494. case string:
  495. f.SetString(v)
  496. case int:
  497. i, err := strconv.ParseInt(v, 10, 64)
  498. if err != nil {
  499. return err
  500. }
  501. f.SetInt(i)
  502. case float64:
  503. i, err := strconv.ParseFloat(v, 64)
  504. if err != nil {
  505. return err
  506. }
  507. f.SetFloat(i)
  508. case bool:
  509. f.SetBool(v == "true")
  510. case []string:
  511. // We don't do anything with string slices here. Any default
  512. // we set will be appended to by the XML decoder, so we fill
  513. // those after decoding.
  514. default:
  515. panic(f.Type())
  516. }
  517. }
  518. }
  519. return nil
  520. }
  521. // fillNilSlices sets default value on slices that are still nil.
  522. func fillNilSlices(data interface{}) error {
  523. s := reflect.ValueOf(data).Elem()
  524. t := s.Type()
  525. for i := 0; i < s.NumField(); i++ {
  526. f := s.Field(i)
  527. tag := t.Field(i).Tag
  528. v := tag.Get("default")
  529. if len(v) > 0 {
  530. switch f.Interface().(type) {
  531. case []string:
  532. if f.IsNil() {
  533. // Treat the default as a comma separated slice
  534. vs := strings.Split(v, ",")
  535. for i := range vs {
  536. vs[i] = strings.TrimSpace(vs[i])
  537. }
  538. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  539. for i, v := range vs {
  540. rv.Index(i).SetString(v)
  541. }
  542. f.Set(rv)
  543. }
  544. }
  545. }
  546. }
  547. return nil
  548. }
  549. func uniqueStrings(ss []string) []string {
  550. var m = make(map[string]bool, len(ss))
  551. for _, s := range ss {
  552. m[strings.Trim(s, " ")] = true
  553. }
  554. var us = make([]string, 0, len(m))
  555. for k := range m {
  556. us = append(us, k)
  557. }
  558. sort.Strings(us)
  559. return us
  560. }
  561. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  562. for _, device := range devices {
  563. if device.DeviceID.Equals(myID) {
  564. return devices
  565. }
  566. }
  567. devices = append(devices, FolderDeviceConfiguration{
  568. DeviceID: myID,
  569. })
  570. return devices
  571. }
  572. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  573. count := len(devices)
  574. i := 0
  575. loop:
  576. for i < count {
  577. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  578. devices[i] = devices[count-1]
  579. count--
  580. continue loop
  581. }
  582. i++
  583. }
  584. return devices[0:count]
  585. }
  586. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  587. count := len(devices)
  588. i := 0
  589. seenDevices := make(map[protocol.DeviceID]bool)
  590. loop:
  591. for i < count {
  592. id := devices[i].DeviceID
  593. if _, ok := seenDevices[id]; ok {
  594. devices[i] = devices[count-1]
  595. count--
  596. continue loop
  597. }
  598. seenDevices[id] = true
  599. i++
  600. }
  601. return devices[0:count]
  602. }
  603. type DeviceConfigurationList []DeviceConfiguration
  604. func (l DeviceConfigurationList) Less(a, b int) bool {
  605. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  606. }
  607. func (l DeviceConfigurationList) Swap(a, b int) {
  608. l[a], l[b] = l[b], l[a]
  609. }
  610. func (l DeviceConfigurationList) Len() int {
  611. return len(l)
  612. }
  613. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  614. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  615. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  616. }
  617. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  618. l[a], l[b] = l[b], l[a]
  619. }
  620. func (l FolderDeviceConfigurationList) Len() int {
  621. return len(l)
  622. }
  623. // randomCharset contains the characters that can make up a randomString().
  624. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  625. // randomString returns a string of random characters (taken from
  626. // randomCharset) of the specified length.
  627. func randomString(l int) string {
  628. bs := make([]byte, l)
  629. for i := range bs {
  630. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  631. }
  632. return string(bs)
  633. }
  634. type PullOrder int
  635. const (
  636. OrderRandom PullOrder = iota // default is random
  637. OrderAlphabetic
  638. OrderSmallestFirst
  639. OrderLargestFirst
  640. OrderOldestFirst
  641. OrderNewestFirst
  642. )
  643. func (o PullOrder) String() string {
  644. switch o {
  645. case OrderRandom:
  646. return "random"
  647. case OrderAlphabetic:
  648. return "alphabetic"
  649. case OrderSmallestFirst:
  650. return "smallestFirst"
  651. case OrderLargestFirst:
  652. return "largestFirst"
  653. case OrderOldestFirst:
  654. return "oldestFirst"
  655. case OrderNewestFirst:
  656. return "newestFirst"
  657. default:
  658. return "unknown"
  659. }
  660. }
  661. func (o PullOrder) MarshalText() ([]byte, error) {
  662. return []byte(o.String()), nil
  663. }
  664. func (o *PullOrder) UnmarshalText(bs []byte) error {
  665. switch string(bs) {
  666. case "random":
  667. *o = OrderRandom
  668. case "alphabetic":
  669. *o = OrderAlphabetic
  670. case "smallestFirst":
  671. *o = OrderSmallestFirst
  672. case "largestFirst":
  673. *o = OrderLargestFirst
  674. case "oldestFirst":
  675. *o = OrderOldestFirst
  676. case "newestFirst":
  677. *o = OrderNewestFirst
  678. default:
  679. *o = OrderRandom
  680. }
  681. return nil
  682. }