config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. // Package config implements reading and writing of the syncthing configuration file.
  5. package config
  6. import (
  7. "encoding/xml"
  8. "fmt"
  9. "io"
  10. "os"
  11. "reflect"
  12. "sort"
  13. "strconv"
  14. "code.google.com/p/go.crypto/bcrypt"
  15. "github.com/calmh/syncthing/logger"
  16. "github.com/calmh/syncthing/protocol"
  17. )
  18. var l = logger.DefaultLogger
  19. type Configuration struct {
  20. Version int `xml:"version,attr" default:"2"`
  21. Repositories []RepositoryConfiguration `xml:"repository"`
  22. Nodes []NodeConfiguration `xml:"node"`
  23. GUI GUIConfiguration `xml:"gui"`
  24. Options OptionsConfiguration `xml:"options"`
  25. XMLName xml.Name `xml:"configuration" json:"-"`
  26. }
  27. type RepositoryConfiguration struct {
  28. ID string `xml:"id,attr"`
  29. Directory string `xml:"directory,attr"`
  30. Nodes []NodeConfiguration `xml:"node"`
  31. ReadOnly bool `xml:"ro,attr"`
  32. IgnorePerms bool `xml:"ignorePerms,attr"`
  33. Invalid string `xml:"-"` // Set at runtime when there is an error, not saved
  34. Versioning VersioningConfiguration `xml:"versioning"`
  35. nodeIDs []protocol.NodeID
  36. }
  37. type VersioningConfiguration struct {
  38. Type string `xml:"type,attr"`
  39. Params map[string]string
  40. }
  41. type InternalVersioningConfiguration struct {
  42. Type string `xml:"type,attr,omitempty"`
  43. Params []InternalParam `xml:"param"`
  44. }
  45. type InternalParam struct {
  46. Key string `xml:"key,attr"`
  47. Val string `xml:"val,attr"`
  48. }
  49. func (c *VersioningConfiguration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  50. var tmp InternalVersioningConfiguration
  51. tmp.Type = c.Type
  52. for k, v := range c.Params {
  53. tmp.Params = append(tmp.Params, InternalParam{k, v})
  54. }
  55. return e.EncodeElement(tmp, start)
  56. }
  57. func (c *VersioningConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  58. var tmp InternalVersioningConfiguration
  59. err := d.DecodeElement(&tmp, &start)
  60. if err != nil {
  61. return err
  62. }
  63. c.Type = tmp.Type
  64. c.Params = make(map[string]string, len(tmp.Params))
  65. for _, p := range tmp.Params {
  66. c.Params[p.Key] = p.Val
  67. }
  68. return nil
  69. }
  70. func (r *RepositoryConfiguration) NodeIDs() []protocol.NodeID {
  71. if r.nodeIDs == nil {
  72. for _, n := range r.Nodes {
  73. r.nodeIDs = append(r.nodeIDs, n.NodeID)
  74. }
  75. }
  76. return r.nodeIDs
  77. }
  78. type NodeConfiguration struct {
  79. NodeID protocol.NodeID `xml:"id,attr"`
  80. Name string `xml:"name,attr,omitempty"`
  81. Addresses []string `xml:"address,omitempty"`
  82. Compression bool `xml:"compression,attr"`
  83. }
  84. type OptionsConfiguration struct {
  85. ListenAddress []string `xml:"listenAddress" default:"0.0.0.0:22000"`
  86. GlobalAnnServer string `xml:"globalAnnounceServer" default:"announce.syncthing.net:22026"`
  87. GlobalAnnEnabled bool `xml:"globalAnnounceEnabled" default:"true"`
  88. LocalAnnEnabled bool `xml:"localAnnounceEnabled" default:"true"`
  89. LocalAnnPort int `xml:"localAnnouncePort" default:"21025"`
  90. ParallelRequests int `xml:"parallelRequests" default:"16"`
  91. MaxSendKbps int `xml:"maxSendKbps"`
  92. RescanIntervalS int `xml:"rescanIntervalS" default:"60"`
  93. ReconnectIntervalS int `xml:"reconnectionIntervalS" default:"60"`
  94. MaxChangeKbps int `xml:"maxChangeKbps" default:"10000"`
  95. StartBrowser bool `xml:"startBrowser" default:"true"`
  96. UPnPEnabled bool `xml:"upnpEnabled" default:"true"`
  97. URAccepted int `xml:"urAccepted"` // Accepted usage reporting version; 0 for off (undecided), -1 for off (permanently)
  98. Deprecated_UREnabled bool `xml:"urEnabled,omitempty" json:"-"`
  99. Deprecated_URDeclined bool `xml:"urDeclined,omitempty" json:"-"`
  100. Deprecated_ReadOnly bool `xml:"readOnly,omitempty" json:"-"`
  101. Deprecated_GUIEnabled bool `xml:"guiEnabled,omitempty" json:"-"`
  102. Deprecated_GUIAddress string `xml:"guiAddress,omitempty" json:"-"`
  103. }
  104. type GUIConfiguration struct {
  105. Enabled bool `xml:"enabled,attr" default:"true"`
  106. Address string `xml:"address" default:"127.0.0.1:8080"`
  107. User string `xml:"user,omitempty"`
  108. Password string `xml:"password,omitempty"`
  109. UseTLS bool `xml:"tls,attr"`
  110. APIKey string `xml:"apikey,omitempty"`
  111. }
  112. func (cfg *Configuration) NodeMap() map[protocol.NodeID]NodeConfiguration {
  113. m := make(map[protocol.NodeID]NodeConfiguration, len(cfg.Nodes))
  114. for _, n := range cfg.Nodes {
  115. m[n.NodeID] = n
  116. }
  117. return m
  118. }
  119. func (cfg *Configuration) RepoMap() map[string]RepositoryConfiguration {
  120. m := make(map[string]RepositoryConfiguration, len(cfg.Repositories))
  121. for _, r := range cfg.Repositories {
  122. m[r.ID] = r
  123. }
  124. return m
  125. }
  126. func setDefaults(data interface{}) error {
  127. s := reflect.ValueOf(data).Elem()
  128. t := s.Type()
  129. for i := 0; i < s.NumField(); i++ {
  130. f := s.Field(i)
  131. tag := t.Field(i).Tag
  132. v := tag.Get("default")
  133. if len(v) > 0 {
  134. switch f.Interface().(type) {
  135. case string:
  136. f.SetString(v)
  137. case int:
  138. i, err := strconv.ParseInt(v, 10, 64)
  139. if err != nil {
  140. return err
  141. }
  142. f.SetInt(i)
  143. case bool:
  144. f.SetBool(v == "true")
  145. case []string:
  146. // We don't do anything with string slices here. Any default
  147. // we set will be appended to by the XML decoder, so we fill
  148. // those after decoding.
  149. default:
  150. panic(f.Type())
  151. }
  152. }
  153. }
  154. return nil
  155. }
  156. // fillNilSlices sets default value on slices that are still nil.
  157. func fillNilSlices(data interface{}) error {
  158. s := reflect.ValueOf(data).Elem()
  159. t := s.Type()
  160. for i := 0; i < s.NumField(); i++ {
  161. f := s.Field(i)
  162. tag := t.Field(i).Tag
  163. v := tag.Get("default")
  164. if len(v) > 0 {
  165. switch f.Interface().(type) {
  166. case []string:
  167. if f.IsNil() {
  168. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1)
  169. rv.Index(0).SetString(v)
  170. f.Set(rv)
  171. }
  172. }
  173. }
  174. }
  175. return nil
  176. }
  177. func Save(wr io.Writer, cfg Configuration) error {
  178. e := xml.NewEncoder(wr)
  179. e.Indent("", " ")
  180. err := e.Encode(cfg)
  181. if err != nil {
  182. return err
  183. }
  184. _, err = wr.Write([]byte("\n"))
  185. return err
  186. }
  187. func uniqueStrings(ss []string) []string {
  188. var m = make(map[string]bool, len(ss))
  189. for _, s := range ss {
  190. m[s] = true
  191. }
  192. var us = make([]string, 0, len(m))
  193. for k := range m {
  194. us = append(us, k)
  195. }
  196. return us
  197. }
  198. func Load(rd io.Reader, myID protocol.NodeID) (Configuration, error) {
  199. var cfg Configuration
  200. setDefaults(&cfg)
  201. setDefaults(&cfg.Options)
  202. setDefaults(&cfg.GUI)
  203. var err error
  204. if rd != nil {
  205. err = xml.NewDecoder(rd).Decode(&cfg)
  206. }
  207. fillNilSlices(&cfg.Options)
  208. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  209. // Initialize an empty slice for repositories if the config has none
  210. if cfg.Repositories == nil {
  211. cfg.Repositories = []RepositoryConfiguration{}
  212. }
  213. // Check for missing, bad or duplicate repository ID:s
  214. var seenRepos = map[string]*RepositoryConfiguration{}
  215. var uniqueCounter int
  216. for i := range cfg.Repositories {
  217. repo := &cfg.Repositories[i]
  218. if len(repo.Directory) == 0 {
  219. repo.Invalid = "no directory configured"
  220. continue
  221. }
  222. if repo.ID == "" {
  223. repo.ID = "default"
  224. }
  225. if seen, ok := seenRepos[repo.ID]; ok {
  226. l.Warnf("Multiple repositories with ID %q; disabling", repo.ID)
  227. seen.Invalid = "duplicate repository ID"
  228. if seen.ID == repo.ID {
  229. uniqueCounter++
  230. seen.ID = fmt.Sprintf("%s~%d", repo.ID, uniqueCounter)
  231. }
  232. repo.Invalid = "duplicate repository ID"
  233. uniqueCounter++
  234. repo.ID = fmt.Sprintf("%s~%d", repo.ID, uniqueCounter)
  235. } else {
  236. seenRepos[repo.ID] = repo
  237. }
  238. }
  239. if cfg.Options.Deprecated_URDeclined {
  240. cfg.Options.URAccepted = -1
  241. }
  242. cfg.Options.Deprecated_URDeclined = false
  243. cfg.Options.Deprecated_UREnabled = false
  244. // Upgrade to v2 configuration if appropriate
  245. if cfg.Version == 1 {
  246. convertV1V2(&cfg)
  247. }
  248. // Hash old cleartext passwords
  249. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  250. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  251. if err != nil {
  252. l.Warnln(err)
  253. } else {
  254. cfg.GUI.Password = string(hash)
  255. }
  256. }
  257. // Build a list of available nodes
  258. existingNodes := make(map[protocol.NodeID]bool)
  259. existingNodes[myID] = true
  260. for _, node := range cfg.Nodes {
  261. existingNodes[node.NodeID] = true
  262. }
  263. // Ensure this node is present in all relevant places
  264. // Ensure that any loose nodes are not present in the wrong places
  265. // Ensure that there are no duplicate nodes
  266. cfg.Nodes = ensureNodePresent(cfg.Nodes, myID)
  267. sort.Sort(NodeConfigurationList(cfg.Nodes))
  268. for i := range cfg.Repositories {
  269. cfg.Repositories[i].Nodes = ensureNodePresent(cfg.Repositories[i].Nodes, myID)
  270. cfg.Repositories[i].Nodes = ensureExistingNodes(cfg.Repositories[i].Nodes, existingNodes)
  271. cfg.Repositories[i].Nodes = ensureNoDuplicates(cfg.Repositories[i].Nodes)
  272. sort.Sort(NodeConfigurationList(cfg.Repositories[i].Nodes))
  273. }
  274. // An empty address list is equivalent to a single "dynamic" entry
  275. for i := range cfg.Nodes {
  276. n := &cfg.Nodes[i]
  277. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  278. n.Addresses = []string{"dynamic"}
  279. }
  280. }
  281. // The global discovery format and port number changed in v0.9. Having the
  282. // default announce server but old port number is guaranteed to be legacy.
  283. if cfg.Options.GlobalAnnServer == "announce.syncthing.net:22025" {
  284. cfg.Options.GlobalAnnServer = "announce.syncthing.net:22026"
  285. }
  286. return cfg, err
  287. }
  288. func convertV1V2(cfg *Configuration) {
  289. // Collect the list of nodes.
  290. // Replace node configs inside repositories with only a reference to the nide ID.
  291. // Set all repositories to read only if the global read only flag is set.
  292. var nodes = map[string]NodeConfiguration{}
  293. for i, repo := range cfg.Repositories {
  294. cfg.Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  295. for j, node := range repo.Nodes {
  296. id := node.NodeID.String()
  297. if _, ok := nodes[id]; !ok {
  298. nodes[id] = node
  299. }
  300. cfg.Repositories[i].Nodes[j] = NodeConfiguration{NodeID: node.NodeID}
  301. }
  302. }
  303. cfg.Options.Deprecated_ReadOnly = false
  304. // Set and sort the list of nodes.
  305. for _, node := range nodes {
  306. cfg.Nodes = append(cfg.Nodes, node)
  307. }
  308. sort.Sort(NodeConfigurationList(cfg.Nodes))
  309. // GUI
  310. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  311. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  312. cfg.Options.Deprecated_GUIEnabled = false
  313. cfg.Options.Deprecated_GUIAddress = ""
  314. cfg.Version = 2
  315. }
  316. type NodeConfigurationList []NodeConfiguration
  317. func (l NodeConfigurationList) Less(a, b int) bool {
  318. return l[a].NodeID.Compare(l[b].NodeID) == -1
  319. }
  320. func (l NodeConfigurationList) Swap(a, b int) {
  321. l[a], l[b] = l[b], l[a]
  322. }
  323. func (l NodeConfigurationList) Len() int {
  324. return len(l)
  325. }
  326. func ensureNodePresent(nodes []NodeConfiguration, myID protocol.NodeID) []NodeConfiguration {
  327. for _, node := range nodes {
  328. if node.NodeID.Equals(myID) {
  329. return nodes
  330. }
  331. }
  332. name, _ := os.Hostname()
  333. nodes = append(nodes, NodeConfiguration{
  334. NodeID: myID,
  335. Name: name,
  336. })
  337. return nodes
  338. }
  339. func ensureExistingNodes(nodes []NodeConfiguration, existingNodes map[protocol.NodeID]bool) []NodeConfiguration {
  340. count := len(nodes)
  341. i := 0
  342. loop:
  343. for i < count {
  344. if _, ok := existingNodes[nodes[i].NodeID]; !ok {
  345. nodes[i] = nodes[count-1]
  346. count--
  347. continue loop
  348. }
  349. i++
  350. }
  351. return nodes[0:count]
  352. }
  353. func ensureNoDuplicates(nodes []NodeConfiguration) []NodeConfiguration {
  354. count := len(nodes)
  355. i := 0
  356. seenNodes := make(map[protocol.NodeID]bool)
  357. loop:
  358. for i < count {
  359. id := nodes[i].NodeID
  360. if _, ok := seenNodes[id]; ok {
  361. nodes[i] = nodes[count-1]
  362. count--
  363. continue loop
  364. }
  365. seenNodes[id] = true
  366. i++
  367. }
  368. return nodes[0:count]
  369. }