config.go 23 KB

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