config.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. AlwaysLocalNets []string `xml:"alwaysLocalNet" json:"alwaysLocalNets"`
  217. }
  218. func (orig OptionsConfiguration) Copy() OptionsConfiguration {
  219. c := orig
  220. c.ListenAddress = make([]string, len(orig.ListenAddress))
  221. copy(c.ListenAddress, orig.ListenAddress)
  222. c.GlobalAnnServers = make([]string, len(orig.GlobalAnnServers))
  223. copy(c.GlobalAnnServers, orig.GlobalAnnServers)
  224. return c
  225. }
  226. type GUIConfiguration struct {
  227. Enabled bool `xml:"enabled,attr" json:"enabled" default:"true"`
  228. Address string `xml:"address" json:"address" default:"127.0.0.1:8384"`
  229. User string `xml:"user,omitempty" json:"user"`
  230. Password string `xml:"password,omitempty" json:"password"`
  231. UseTLS bool `xml:"tls,attr" json:"useTLS"`
  232. APIKey string `xml:"apikey,omitempty" json:"apiKey"`
  233. }
  234. func New(myID protocol.DeviceID) Configuration {
  235. var cfg Configuration
  236. cfg.Version = CurrentVersion
  237. cfg.OriginalVersion = CurrentVersion
  238. setDefaults(&cfg)
  239. setDefaults(&cfg.Options)
  240. setDefaults(&cfg.GUI)
  241. cfg.prepare(myID)
  242. return cfg
  243. }
  244. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  245. var cfg Configuration
  246. setDefaults(&cfg)
  247. setDefaults(&cfg.Options)
  248. setDefaults(&cfg.GUI)
  249. err := xml.NewDecoder(r).Decode(&cfg)
  250. cfg.OriginalVersion = cfg.Version
  251. cfg.prepare(myID)
  252. return cfg, err
  253. }
  254. func (cfg *Configuration) WriteXML(w io.Writer) error {
  255. e := xml.NewEncoder(w)
  256. e.Indent("", " ")
  257. err := e.Encode(cfg)
  258. if err != nil {
  259. return err
  260. }
  261. _, err = w.Write([]byte("\n"))
  262. return err
  263. }
  264. func (cfg *Configuration) prepare(myID protocol.DeviceID) {
  265. fillNilSlices(&cfg.Options)
  266. // Initialize an empty slices
  267. if cfg.Folders == nil {
  268. cfg.Folders = []FolderConfiguration{}
  269. }
  270. if cfg.IgnoredDevices == nil {
  271. cfg.IgnoredDevices = []protocol.DeviceID{}
  272. }
  273. // Check for missing, bad or duplicate folder ID:s
  274. var seenFolders = map[string]*FolderConfiguration{}
  275. for i := range cfg.Folders {
  276. folder := &cfg.Folders[i]
  277. if len(folder.RawPath) == 0 {
  278. folder.Invalid = "no directory configured"
  279. continue
  280. }
  281. // The reason it's done like this:
  282. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  283. // C:\somedir -> C:\somedir\ -> C:\somedir
  284. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  285. // This way in the tests, we get away without OS specific separators
  286. // in the test configs.
  287. folder.RawPath = filepath.Dir(folder.RawPath + string(filepath.Separator))
  288. if folder.ID == "" {
  289. folder.ID = "default"
  290. }
  291. if folder.RescanIntervalS > MaxRescanIntervalS {
  292. folder.RescanIntervalS = MaxRescanIntervalS
  293. } else if folder.RescanIntervalS < 0 {
  294. folder.RescanIntervalS = 0
  295. }
  296. if seen, ok := seenFolders[folder.ID]; ok {
  297. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  298. seen.Invalid = "duplicate folder ID"
  299. folder.Invalid = "duplicate folder ID"
  300. } else {
  301. seenFolders[folder.ID] = folder
  302. }
  303. }
  304. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  305. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  306. if cfg.Version < OldestHandledVersion {
  307. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  308. }
  309. // Upgrade configuration versions as appropriate
  310. if cfg.Version <= 5 {
  311. convertV5V6(cfg)
  312. }
  313. if cfg.Version == 6 {
  314. convertV6V7(cfg)
  315. }
  316. if cfg.Version == 7 {
  317. convertV7V8(cfg)
  318. }
  319. if cfg.Version == 8 {
  320. convertV8V9(cfg)
  321. }
  322. if cfg.Version == 9 {
  323. convertV9V10(cfg)
  324. }
  325. if cfg.Version == 10 {
  326. convertV10V11(cfg)
  327. }
  328. if cfg.Version == 11 {
  329. convertV11V12(cfg)
  330. }
  331. // Hash old cleartext passwords
  332. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  333. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  334. if err != nil {
  335. l.Warnln("bcrypting password:", err)
  336. } else {
  337. cfg.GUI.Password = string(hash)
  338. }
  339. }
  340. // Build a list of available devices
  341. existingDevices := make(map[protocol.DeviceID]bool)
  342. for _, device := range cfg.Devices {
  343. existingDevices[device.DeviceID] = true
  344. }
  345. // Ensure this device is present in the config
  346. if !existingDevices[myID] {
  347. myName, _ := os.Hostname()
  348. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  349. DeviceID: myID,
  350. Name: myName,
  351. })
  352. existingDevices[myID] = true
  353. }
  354. sort.Sort(DeviceConfigurationList(cfg.Devices))
  355. // Ensure that any loose devices are not present in the wrong places
  356. // Ensure that there are no duplicate devices
  357. // Ensure that puller settings are sane
  358. for i := range cfg.Folders {
  359. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  360. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  361. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  362. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  363. }
  364. // An empty address list is equivalent to a single "dynamic" entry
  365. for i := range cfg.Devices {
  366. n := &cfg.Devices[i]
  367. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  368. n.Addresses = []string{"dynamic"}
  369. }
  370. }
  371. // Very short reconnection intervals are annoying
  372. if cfg.Options.ReconnectIntervalS < 5 {
  373. cfg.Options.ReconnectIntervalS = 5
  374. }
  375. if cfg.GUI.APIKey == "" {
  376. cfg.GUI.APIKey = randomString(32)
  377. }
  378. }
  379. // ChangeRequiresRestart returns true if updating the configuration requires a
  380. // complete restart.
  381. func ChangeRequiresRestart(from, to Configuration) bool {
  382. // Adding, removing or changing folders requires restart
  383. if !reflect.DeepEqual(from.Folders, to.Folders) {
  384. return true
  385. }
  386. // Removing a device requres restart
  387. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  388. for _, dev := range to.Devices {
  389. toDevs[dev.DeviceID] = true
  390. }
  391. for _, dev := range from.Devices {
  392. if _, ok := toDevs[dev.DeviceID]; !ok {
  393. return true
  394. }
  395. }
  396. // Changing usage reporting to on or off does not require a restart.
  397. to.Options.URAccepted = from.Options.URAccepted
  398. to.Options.URUniqueID = from.Options.URUniqueID
  399. // All of the generic options require restart
  400. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  401. return true
  402. }
  403. return false
  404. }
  405. func convertV10V11(cfg *Configuration) {
  406. // Set minimum disk free of existing folders to 1%
  407. for i := range cfg.Folders {
  408. cfg.Folders[i].MinDiskFreePct = 1
  409. }
  410. cfg.Version = 11
  411. }
  412. func convertV11V12(cfg *Configuration) {
  413. // Change listen address schema
  414. for i, addr := range cfg.Options.ListenAddress {
  415. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  416. cfg.Options.ListenAddress[i] = fmt.Sprintf("tcp://%s", addr)
  417. }
  418. }
  419. for i, device := range cfg.Devices {
  420. for j, addr := range device.Addresses {
  421. if addr != "dynamic" && addr != "" {
  422. cfg.Devices[i].Addresses[j] = fmt.Sprintf("tcp://%s", addr)
  423. }
  424. }
  425. }
  426. // Use new discovery server
  427. for i, addr := range cfg.Options.GlobalAnnServers {
  428. if addr == "udp4://announce.syncthing.net:22026" {
  429. cfg.Options.GlobalAnnServers[i] = "udp4://announce.syncthing.net:22027"
  430. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  431. cfg.Options.GlobalAnnServers[i] = "udp6://announce-v6.syncthing.net:22027"
  432. } else if addr == "udp4://194.126.249.5:22026" {
  433. cfg.Options.GlobalAnnServers[i] = "udp4://194.126.249.5:22027"
  434. } else if addr == "udp6://[2001:470:28:4d6::5]:22026" {
  435. cfg.Options.GlobalAnnServers[i] = "udp6://[2001:470:28:4d6::5]:22027"
  436. }
  437. }
  438. // Use new multicast group
  439. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  440. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  441. }
  442. // Use new local discovery port
  443. if cfg.Options.LocalAnnPort == 21025 {
  444. cfg.Options.LocalAnnPort = 21027
  445. }
  446. cfg.Version = 12
  447. }
  448. func convertV9V10(cfg *Configuration) {
  449. // Enable auto normalization on existing folders.
  450. for i := range cfg.Folders {
  451. cfg.Folders[i].AutoNormalize = true
  452. }
  453. cfg.Version = 10
  454. }
  455. func convertV8V9(cfg *Configuration) {
  456. // Compression is interpreted and serialized differently, but no enforced
  457. // changes. Still need a new version number since the compression stuff
  458. // isn't understandable by earlier versions.
  459. cfg.Version = 9
  460. }
  461. func convertV7V8(cfg *Configuration) {
  462. // Add IPv6 announce server
  463. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  464. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  465. }
  466. cfg.Version = 8
  467. }
  468. func convertV6V7(cfg *Configuration) {
  469. // Migrate announce server addresses to the new URL based format
  470. for i := range cfg.Options.GlobalAnnServers {
  471. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  472. }
  473. cfg.Version = 7
  474. }
  475. func convertV5V6(cfg *Configuration) {
  476. // Added ".stfolder" file at folder roots to identify mount issues
  477. // Doesn't affect the config itself, but uses config migrations to identify
  478. // the migration point.
  479. for _, folder := range Wrap("", *cfg).Folders() {
  480. // Best attempt, if it fails, it fails, the user will have to fix
  481. // it up manually, as the repo will not get started.
  482. folder.CreateMarker()
  483. }
  484. cfg.Version = 6
  485. }
  486. func setDefaults(data interface{}) error {
  487. s := reflect.ValueOf(data).Elem()
  488. t := s.Type()
  489. for i := 0; i < s.NumField(); i++ {
  490. f := s.Field(i)
  491. tag := t.Field(i).Tag
  492. v := tag.Get("default")
  493. if len(v) > 0 {
  494. switch f.Interface().(type) {
  495. case string:
  496. f.SetString(v)
  497. case int:
  498. i, err := strconv.ParseInt(v, 10, 64)
  499. if err != nil {
  500. return err
  501. }
  502. f.SetInt(i)
  503. case float64:
  504. i, err := strconv.ParseFloat(v, 64)
  505. if err != nil {
  506. return err
  507. }
  508. f.SetFloat(i)
  509. case bool:
  510. f.SetBool(v == "true")
  511. case []string:
  512. // We don't do anything with string slices here. Any default
  513. // we set will be appended to by the XML decoder, so we fill
  514. // those after decoding.
  515. default:
  516. panic(f.Type())
  517. }
  518. }
  519. }
  520. return nil
  521. }
  522. // fillNilSlices sets default value on slices that are still nil.
  523. func fillNilSlices(data interface{}) error {
  524. s := reflect.ValueOf(data).Elem()
  525. t := s.Type()
  526. for i := 0; i < s.NumField(); i++ {
  527. f := s.Field(i)
  528. tag := t.Field(i).Tag
  529. v := tag.Get("default")
  530. if len(v) > 0 {
  531. switch f.Interface().(type) {
  532. case []string:
  533. if f.IsNil() {
  534. // Treat the default as a comma separated slice
  535. vs := strings.Split(v, ",")
  536. for i := range vs {
  537. vs[i] = strings.TrimSpace(vs[i])
  538. }
  539. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  540. for i, v := range vs {
  541. rv.Index(i).SetString(v)
  542. }
  543. f.Set(rv)
  544. }
  545. }
  546. }
  547. }
  548. return nil
  549. }
  550. func uniqueStrings(ss []string) []string {
  551. var m = make(map[string]bool, len(ss))
  552. for _, s := range ss {
  553. m[strings.Trim(s, " ")] = true
  554. }
  555. var us = make([]string, 0, len(m))
  556. for k := range m {
  557. us = append(us, k)
  558. }
  559. sort.Strings(us)
  560. return us
  561. }
  562. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  563. for _, device := range devices {
  564. if device.DeviceID.Equals(myID) {
  565. return devices
  566. }
  567. }
  568. devices = append(devices, FolderDeviceConfiguration{
  569. DeviceID: myID,
  570. })
  571. return devices
  572. }
  573. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  574. count := len(devices)
  575. i := 0
  576. loop:
  577. for i < count {
  578. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  579. devices[i] = devices[count-1]
  580. count--
  581. continue loop
  582. }
  583. i++
  584. }
  585. return devices[0:count]
  586. }
  587. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  588. count := len(devices)
  589. i := 0
  590. seenDevices := make(map[protocol.DeviceID]bool)
  591. loop:
  592. for i < count {
  593. id := devices[i].DeviceID
  594. if _, ok := seenDevices[id]; ok {
  595. devices[i] = devices[count-1]
  596. count--
  597. continue loop
  598. }
  599. seenDevices[id] = true
  600. i++
  601. }
  602. return devices[0:count]
  603. }
  604. type DeviceConfigurationList []DeviceConfiguration
  605. func (l DeviceConfigurationList) Less(a, b int) bool {
  606. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  607. }
  608. func (l DeviceConfigurationList) Swap(a, b int) {
  609. l[a], l[b] = l[b], l[a]
  610. }
  611. func (l DeviceConfigurationList) Len() int {
  612. return len(l)
  613. }
  614. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  615. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  616. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  617. }
  618. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  619. l[a], l[b] = l[b], l[a]
  620. }
  621. func (l FolderDeviceConfigurationList) Len() int {
  622. return len(l)
  623. }
  624. // randomCharset contains the characters that can make up a randomString().
  625. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  626. // randomString returns a string of random characters (taken from
  627. // randomCharset) of the specified length.
  628. func randomString(l int) string {
  629. bs := make([]byte, l)
  630. for i := range bs {
  631. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  632. }
  633. return string(bs)
  634. }
  635. type PullOrder int
  636. const (
  637. OrderRandom PullOrder = iota // default is random
  638. OrderAlphabetic
  639. OrderSmallestFirst
  640. OrderLargestFirst
  641. OrderOldestFirst
  642. OrderNewestFirst
  643. )
  644. func (o PullOrder) String() string {
  645. switch o {
  646. case OrderRandom:
  647. return "random"
  648. case OrderAlphabetic:
  649. return "alphabetic"
  650. case OrderSmallestFirst:
  651. return "smallestFirst"
  652. case OrderLargestFirst:
  653. return "largestFirst"
  654. case OrderOldestFirst:
  655. return "oldestFirst"
  656. case OrderNewestFirst:
  657. return "newestFirst"
  658. default:
  659. return "unknown"
  660. }
  661. }
  662. func (o PullOrder) MarshalText() ([]byte, error) {
  663. return []byte(o.String()), nil
  664. }
  665. func (o *PullOrder) UnmarshalText(bs []byte) error {
  666. switch string(bs) {
  667. case "random":
  668. *o = OrderRandom
  669. case "alphabetic":
  670. *o = OrderAlphabetic
  671. case "smallestFirst":
  672. *o = OrderSmallestFirst
  673. case "largestFirst":
  674. *o = OrderLargestFirst
  675. case "oldestFirst":
  676. *o = OrderOldestFirst
  677. case "newestFirst":
  678. *o = OrderNewestFirst
  679. default:
  680. *o = OrderRandom
  681. }
  682. return nil
  683. }