config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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/json"
  10. "encoding/xml"
  11. "io"
  12. "math/rand"
  13. "net/url"
  14. "os"
  15. "reflect"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. )
  21. const (
  22. OldestHandledVersion = 10
  23. CurrentVersion = 12
  24. MaxRescanIntervalS = 365 * 24 * 60 * 60
  25. )
  26. var (
  27. // DefaultDiscoveryServersV4 should be substituted when the configuration
  28. // contains <globalAnnounceServer>default-v4</globalAnnounceServer>. This is
  29. // done by the "consumer" of the configuration, as we don't want these
  30. // saved to the config.
  31. DefaultDiscoveryServersV4 = []string{
  32. "https://discovery-v4-1.syncthing.net/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 194.126.249.5, Sweden
  33. "https://discovery-v4-2.syncthing.net/?id=DVU36WY-H3LVZHW-E6LLFRE-YAFN5EL-HILWRYP-OC2M47J-Z4PE62Y-ADIBDQC", // 45.55.230.38, USA
  34. "https://discovery-v4-3.syncthing.net/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ", // 128.199.95.124, Singapore
  35. }
  36. // DefaultDiscoveryServersV6 should be substituted when the configuration
  37. // contains <globalAnnounceServer>default-v6</globalAnnounceServer>.
  38. DefaultDiscoveryServersV6 = []string{
  39. "https://discovery-v6-1.syncthing.net/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 2001:470:28:4d6::5, Sweden
  40. "https://discovery-v6-2.syncthing.net/?id=DVU36WY-H3LVZHW-E6LLFRE-YAFN5EL-HILWRYP-OC2M47J-Z4PE62Y-ADIBDQC", // 2604:a880:800:10::182:a001, USA
  41. "https://discovery-v6-3.syncthing.net/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ", // 2400:6180:0:d0::d9:d001, Singapore
  42. }
  43. // DefaultDiscoveryServers should be substituted when the configuration
  44. // contains <globalAnnounceServer>default</globalAnnounceServer>.
  45. DefaultDiscoveryServers = append(DefaultDiscoveryServersV4, DefaultDiscoveryServersV6...)
  46. // DefaultDiscoveryServersIP is used by the usage reporting.
  47. // XXX: Detect Android, and use this is we still don't have working DNS?
  48. DefaultDiscoveryServersIP = []string{
  49. "https://194.126.249.5/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA",
  50. "https://45.55.230.38/?id=AQEHEO2-XOS7QRA-X2COH5K-PO6OPVA-EWOSEGO-KZFMD32-XJ4ZV46-CUUVKAS",
  51. "https://128.199.95.124/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ",
  52. "https://[2001:470:28:4d6::5]/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA",
  53. "https://[2604:a880:800:10::182:a001]/?id=AQEHEO2-XOS7QRA-X2COH5K-PO6OPVA-EWOSEGO-KZFMD32-XJ4ZV46-CUUVKAS",
  54. "https://[2400:6180:0:d0::d9:d001]/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ",
  55. }
  56. )
  57. func New(myID protocol.DeviceID) Configuration {
  58. var cfg Configuration
  59. cfg.Version = CurrentVersion
  60. cfg.OriginalVersion = CurrentVersion
  61. setDefaults(&cfg)
  62. setDefaults(&cfg.Options)
  63. setDefaults(&cfg.GUI)
  64. cfg.prepare(myID)
  65. return cfg
  66. }
  67. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  68. var cfg Configuration
  69. setDefaults(&cfg)
  70. setDefaults(&cfg.Options)
  71. setDefaults(&cfg.GUI)
  72. err := xml.NewDecoder(r).Decode(&cfg)
  73. cfg.OriginalVersion = cfg.Version
  74. cfg.prepare(myID)
  75. return cfg, err
  76. }
  77. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  78. var cfg Configuration
  79. setDefaults(&cfg)
  80. setDefaults(&cfg.Options)
  81. setDefaults(&cfg.GUI)
  82. err := json.NewDecoder(r).Decode(&cfg)
  83. cfg.OriginalVersion = cfg.Version
  84. cfg.prepare(myID)
  85. return cfg, err
  86. }
  87. type Configuration struct {
  88. Version int `xml:"version,attr" json:"version"`
  89. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  90. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  91. GUI GUIConfiguration `xml:"gui" json:"gui"`
  92. Options OptionsConfiguration `xml:"options" json:"options"`
  93. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  94. XMLName xml.Name `xml:"configuration" json:"-"`
  95. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  96. }
  97. func (cfg Configuration) Copy() Configuration {
  98. newCfg := cfg
  99. // Deep copy FolderConfigurations
  100. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  101. for i := range newCfg.Folders {
  102. newCfg.Folders[i] = cfg.Folders[i].Copy()
  103. }
  104. // Deep copy DeviceConfigurations
  105. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  106. for i := range newCfg.Devices {
  107. newCfg.Devices[i] = cfg.Devices[i].Copy()
  108. }
  109. newCfg.Options = cfg.Options.Copy()
  110. // DeviceIDs are values
  111. newCfg.IgnoredDevices = make([]protocol.DeviceID, len(cfg.IgnoredDevices))
  112. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  113. return newCfg
  114. }
  115. func (cfg *Configuration) WriteXML(w io.Writer) error {
  116. e := xml.NewEncoder(w)
  117. e.Indent("", " ")
  118. err := e.Encode(cfg)
  119. if err != nil {
  120. return err
  121. }
  122. _, err = w.Write([]byte("\n"))
  123. return err
  124. }
  125. func (cfg *Configuration) prepare(myID protocol.DeviceID) {
  126. fillNilSlices(&cfg.Options)
  127. // Initialize any empty slices
  128. if cfg.Folders == nil {
  129. cfg.Folders = []FolderConfiguration{}
  130. }
  131. if cfg.IgnoredDevices == nil {
  132. cfg.IgnoredDevices = []protocol.DeviceID{}
  133. }
  134. if cfg.Options.AlwaysLocalNets == nil {
  135. cfg.Options.AlwaysLocalNets = []string{}
  136. }
  137. // Check for missing, bad or duplicate folder ID:s
  138. var seenFolders = map[string]*FolderConfiguration{}
  139. for i := range cfg.Folders {
  140. folder := &cfg.Folders[i]
  141. folder.prepare()
  142. if seen, ok := seenFolders[folder.ID]; ok {
  143. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  144. seen.Invalid = "duplicate folder ID"
  145. folder.Invalid = "duplicate folder ID"
  146. } else {
  147. seenFolders[folder.ID] = folder
  148. }
  149. }
  150. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  151. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  152. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  153. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  154. }
  155. // Upgrade configuration versions as appropriate
  156. if cfg.Version <= 10 {
  157. convertV10V11(cfg)
  158. }
  159. if cfg.Version == 11 {
  160. convertV11V12(cfg)
  161. }
  162. // Build a list of available devices
  163. existingDevices := make(map[protocol.DeviceID]bool)
  164. for _, device := range cfg.Devices {
  165. existingDevices[device.DeviceID] = true
  166. }
  167. // Ensure this device is present in the config
  168. if !existingDevices[myID] {
  169. myName, _ := os.Hostname()
  170. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  171. DeviceID: myID,
  172. Name: myName,
  173. })
  174. existingDevices[myID] = true
  175. }
  176. sort.Sort(DeviceConfigurationList(cfg.Devices))
  177. // Ensure that any loose devices are not present in the wrong places
  178. // Ensure that there are no duplicate devices
  179. // Ensure that puller settings are sane
  180. for i := range cfg.Folders {
  181. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  182. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  183. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  184. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  185. }
  186. // An empty address list is equivalent to a single "dynamic" entry
  187. for i := range cfg.Devices {
  188. n := &cfg.Devices[i]
  189. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  190. n.Addresses = []string{"dynamic"}
  191. }
  192. }
  193. // Very short reconnection intervals are annoying
  194. if cfg.Options.ReconnectIntervalS < 5 {
  195. cfg.Options.ReconnectIntervalS = 5
  196. }
  197. if cfg.GUI.RawAPIKey == "" {
  198. cfg.GUI.RawAPIKey = randomString(32)
  199. }
  200. }
  201. func convertV11V12(cfg *Configuration) {
  202. // Change listen address schema
  203. for i, addr := range cfg.Options.ListenAddress {
  204. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  205. cfg.Options.ListenAddress[i] = tcpAddr(addr)
  206. }
  207. }
  208. for i, device := range cfg.Devices {
  209. for j, addr := range device.Addresses {
  210. if addr != "dynamic" && addr != "" {
  211. cfg.Devices[i].Addresses[j] = tcpAddr(addr)
  212. }
  213. }
  214. }
  215. // Use new discovery server
  216. var newDiscoServers []string
  217. var useDefault bool
  218. for _, addr := range cfg.Options.GlobalAnnServers {
  219. if addr == "udp4://announce.syncthing.net:22026" {
  220. useDefault = true
  221. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  222. useDefault = true
  223. } else {
  224. newDiscoServers = append(newDiscoServers, addr)
  225. }
  226. }
  227. if useDefault {
  228. newDiscoServers = append(newDiscoServers, "default")
  229. }
  230. cfg.Options.GlobalAnnServers = newDiscoServers
  231. // Use new multicast group
  232. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  233. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  234. }
  235. // Use new local discovery port
  236. if cfg.Options.LocalAnnPort == 21025 {
  237. cfg.Options.LocalAnnPort = 21027
  238. }
  239. // Set MaxConflicts to unlimited
  240. for i := range cfg.Folders {
  241. cfg.Folders[i].MaxConflicts = -1
  242. }
  243. cfg.Version = 12
  244. }
  245. func convertV10V11(cfg *Configuration) {
  246. // Set minimum disk free of existing folders to 1%
  247. for i := range cfg.Folders {
  248. cfg.Folders[i].MinDiskFreePct = 1
  249. }
  250. cfg.Version = 11
  251. }
  252. func setDefaults(data interface{}) error {
  253. s := reflect.ValueOf(data).Elem()
  254. t := s.Type()
  255. for i := 0; i < s.NumField(); i++ {
  256. f := s.Field(i)
  257. tag := t.Field(i).Tag
  258. v := tag.Get("default")
  259. if len(v) > 0 {
  260. switch f.Interface().(type) {
  261. case string:
  262. f.SetString(v)
  263. case int:
  264. i, err := strconv.ParseInt(v, 10, 64)
  265. if err != nil {
  266. return err
  267. }
  268. f.SetInt(i)
  269. case float64:
  270. i, err := strconv.ParseFloat(v, 64)
  271. if err != nil {
  272. return err
  273. }
  274. f.SetFloat(i)
  275. case bool:
  276. f.SetBool(v == "true")
  277. case []string:
  278. // We don't do anything with string slices here. Any default
  279. // we set will be appended to by the XML decoder, so we fill
  280. // those after decoding.
  281. default:
  282. panic(f.Type())
  283. }
  284. }
  285. }
  286. return nil
  287. }
  288. // fillNilSlices sets default value on slices that are still nil.
  289. func fillNilSlices(data interface{}) error {
  290. s := reflect.ValueOf(data).Elem()
  291. t := s.Type()
  292. for i := 0; i < s.NumField(); i++ {
  293. f := s.Field(i)
  294. tag := t.Field(i).Tag
  295. v := tag.Get("default")
  296. if len(v) > 0 {
  297. switch f.Interface().(type) {
  298. case []string:
  299. if f.IsNil() {
  300. // Treat the default as a comma separated slice
  301. vs := strings.Split(v, ",")
  302. for i := range vs {
  303. vs[i] = strings.TrimSpace(vs[i])
  304. }
  305. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  306. for i, v := range vs {
  307. rv.Index(i).SetString(v)
  308. }
  309. f.Set(rv)
  310. }
  311. }
  312. }
  313. }
  314. return nil
  315. }
  316. func uniqueStrings(ss []string) []string {
  317. var m = make(map[string]bool, len(ss))
  318. for _, s := range ss {
  319. m[strings.Trim(s, " ")] = true
  320. }
  321. var us = make([]string, 0, len(m))
  322. for k := range m {
  323. us = append(us, k)
  324. }
  325. sort.Strings(us)
  326. return us
  327. }
  328. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  329. for _, device := range devices {
  330. if device.DeviceID.Equals(myID) {
  331. return devices
  332. }
  333. }
  334. devices = append(devices, FolderDeviceConfiguration{
  335. DeviceID: myID,
  336. })
  337. return devices
  338. }
  339. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  340. count := len(devices)
  341. i := 0
  342. loop:
  343. for i < count {
  344. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  345. devices[i] = devices[count-1]
  346. count--
  347. continue loop
  348. }
  349. i++
  350. }
  351. return devices[0:count]
  352. }
  353. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  354. count := len(devices)
  355. i := 0
  356. seenDevices := make(map[protocol.DeviceID]bool)
  357. loop:
  358. for i < count {
  359. id := devices[i].DeviceID
  360. if _, ok := seenDevices[id]; ok {
  361. devices[i] = devices[count-1]
  362. count--
  363. continue loop
  364. }
  365. seenDevices[id] = true
  366. i++
  367. }
  368. return devices[0:count]
  369. }
  370. // randomCharset contains the characters that can make up a randomString().
  371. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  372. // randomString returns a string of random characters (taken from
  373. // randomCharset) of the specified length.
  374. func randomString(l int) string {
  375. bs := make([]byte, l)
  376. for i := range bs {
  377. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  378. }
  379. return string(bs)
  380. }
  381. func tcpAddr(host string) string {
  382. u := url.URL{
  383. Scheme: "tcp",
  384. Host: host,
  385. }
  386. return u.String()
  387. }