1
0

config.go 24 KB

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