config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. }
  83. type OptionsConfiguration struct {
  84. ListenAddress []string `xml:"listenAddress" default:"0.0.0.0:22000"`
  85. GlobalAnnServer string `xml:"globalAnnounceServer" default:"announce.syncthing.net:22026"`
  86. GlobalAnnEnabled bool `xml:"globalAnnounceEnabled" default:"true"`
  87. LocalAnnEnabled bool `xml:"localAnnounceEnabled" default:"true"`
  88. LocalAnnPort int `xml:"localAnnouncePort" default:"21025"`
  89. ParallelRequests int `xml:"parallelRequests" default:"16"`
  90. MaxSendKbps int `xml:"maxSendKbps"`
  91. RescanIntervalS int `xml:"rescanIntervalS" default:"60"`
  92. ReconnectIntervalS int `xml:"reconnectionIntervalS" default:"60"`
  93. MaxChangeKbps int `xml:"maxChangeKbps" default:"10000"`
  94. StartBrowser bool `xml:"startBrowser" default:"true"`
  95. UPnPEnabled bool `xml:"upnpEnabled" default:"true"`
  96. URAccepted int `xml:"urAccepted"` // Accepted usage reporting version; 0 for off (undecided), -1 for off (permanently)
  97. Deprecated_UREnabled bool `xml:"urEnabled,omitempty" json:"-"`
  98. Deprecated_URDeclined bool `xml:"urDeclined,omitempty" json:"-"`
  99. Deprecated_ReadOnly bool `xml:"readOnly,omitempty" json:"-"`
  100. Deprecated_GUIEnabled bool `xml:"guiEnabled,omitempty" json:"-"`
  101. Deprecated_GUIAddress string `xml:"guiAddress,omitempty" json:"-"`
  102. }
  103. type GUIConfiguration struct {
  104. Enabled bool `xml:"enabled,attr" default:"true"`
  105. Address string `xml:"address" default:"127.0.0.1:8080"`
  106. User string `xml:"user,omitempty"`
  107. Password string `xml:"password,omitempty"`
  108. UseTLS bool `xml:"tls,attr"`
  109. APIKey string `xml:"apikey,omitempty"`
  110. }
  111. func (cfg *Configuration) NodeMap() map[protocol.NodeID]NodeConfiguration {
  112. m := make(map[protocol.NodeID]NodeConfiguration, len(cfg.Nodes))
  113. for _, n := range cfg.Nodes {
  114. m[n.NodeID] = n
  115. }
  116. return m
  117. }
  118. func (cfg *Configuration) RepoMap() map[string]RepositoryConfiguration {
  119. m := make(map[string]RepositoryConfiguration, len(cfg.Repositories))
  120. for _, r := range cfg.Repositories {
  121. m[r.ID] = r
  122. }
  123. return m
  124. }
  125. func setDefaults(data interface{}) error {
  126. s := reflect.ValueOf(data).Elem()
  127. t := s.Type()
  128. for i := 0; i < s.NumField(); i++ {
  129. f := s.Field(i)
  130. tag := t.Field(i).Tag
  131. v := tag.Get("default")
  132. if len(v) > 0 {
  133. switch f.Interface().(type) {
  134. case string:
  135. f.SetString(v)
  136. case int:
  137. i, err := strconv.ParseInt(v, 10, 64)
  138. if err != nil {
  139. return err
  140. }
  141. f.SetInt(i)
  142. case bool:
  143. f.SetBool(v == "true")
  144. case []string:
  145. // We don't do anything with string slices here. Any default
  146. // we set will be appended to by the XML decoder, so we fill
  147. // those after decoding.
  148. default:
  149. panic(f.Type())
  150. }
  151. }
  152. }
  153. return nil
  154. }
  155. // fillNilSlices sets default value on slices that are still nil.
  156. func fillNilSlices(data interface{}) error {
  157. s := reflect.ValueOf(data).Elem()
  158. t := s.Type()
  159. for i := 0; i < s.NumField(); i++ {
  160. f := s.Field(i)
  161. tag := t.Field(i).Tag
  162. v := tag.Get("default")
  163. if len(v) > 0 {
  164. switch f.Interface().(type) {
  165. case []string:
  166. if f.IsNil() {
  167. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1)
  168. rv.Index(0).SetString(v)
  169. f.Set(rv)
  170. }
  171. }
  172. }
  173. }
  174. return nil
  175. }
  176. func Save(wr io.Writer, cfg Configuration) error {
  177. e := xml.NewEncoder(wr)
  178. e.Indent("", " ")
  179. err := e.Encode(cfg)
  180. if err != nil {
  181. return err
  182. }
  183. _, err = wr.Write([]byte("\n"))
  184. return err
  185. }
  186. func uniqueStrings(ss []string) []string {
  187. var m = make(map[string]bool, len(ss))
  188. for _, s := range ss {
  189. m[s] = true
  190. }
  191. var us = make([]string, 0, len(m))
  192. for k := range m {
  193. us = append(us, k)
  194. }
  195. return us
  196. }
  197. func Load(rd io.Reader, myID protocol.NodeID) (Configuration, error) {
  198. var cfg Configuration
  199. setDefaults(&cfg)
  200. setDefaults(&cfg.Options)
  201. setDefaults(&cfg.GUI)
  202. var err error
  203. if rd != nil {
  204. err = xml.NewDecoder(rd).Decode(&cfg)
  205. }
  206. fillNilSlices(&cfg.Options)
  207. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  208. // Initialize an empty slice for repositories if the config has none
  209. if cfg.Repositories == nil {
  210. cfg.Repositories = []RepositoryConfiguration{}
  211. }
  212. // Check for missing, bad or duplicate repository ID:s
  213. var seenRepos = map[string]*RepositoryConfiguration{}
  214. var uniqueCounter int
  215. for i := range cfg.Repositories {
  216. repo := &cfg.Repositories[i]
  217. if len(repo.Directory) == 0 {
  218. repo.Invalid = "no directory configured"
  219. continue
  220. }
  221. if repo.ID == "" {
  222. repo.ID = "default"
  223. }
  224. if seen, ok := seenRepos[repo.ID]; ok {
  225. l.Warnf("Multiple repositories with ID %q; disabling", repo.ID)
  226. seen.Invalid = "duplicate repository ID"
  227. if seen.ID == repo.ID {
  228. uniqueCounter++
  229. seen.ID = fmt.Sprintf("%s~%d", repo.ID, uniqueCounter)
  230. }
  231. repo.Invalid = "duplicate repository ID"
  232. uniqueCounter++
  233. repo.ID = fmt.Sprintf("%s~%d", repo.ID, uniqueCounter)
  234. } else {
  235. seenRepos[repo.ID] = repo
  236. }
  237. }
  238. if cfg.Options.Deprecated_URDeclined {
  239. cfg.Options.URAccepted = -1
  240. }
  241. cfg.Options.Deprecated_URDeclined = false
  242. cfg.Options.Deprecated_UREnabled = false
  243. // Upgrade to v2 configuration if appropriate
  244. if cfg.Version == 1 {
  245. convertV1V2(&cfg)
  246. }
  247. // Hash old cleartext passwords
  248. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  249. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  250. if err != nil {
  251. l.Warnln(err)
  252. } else {
  253. cfg.GUI.Password = string(hash)
  254. }
  255. }
  256. // Ensure this node is present in all relevant places
  257. cfg.Nodes = ensureNodePresent(cfg.Nodes, myID)
  258. for i := range cfg.Repositories {
  259. cfg.Repositories[i].Nodes = ensureNodePresent(cfg.Repositories[i].Nodes, myID)
  260. }
  261. // An empty address list is equivalent to a single "dynamic" entry
  262. for i := range cfg.Nodes {
  263. n := &cfg.Nodes[i]
  264. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  265. n.Addresses = []string{"dynamic"}
  266. }
  267. }
  268. // The global discovery format and port number changed in v0.9. Having the
  269. // default announce server but old port number is guaranteed to be legacy.
  270. if cfg.Options.GlobalAnnServer == "announce.syncthing.net:22025" {
  271. cfg.Options.GlobalAnnServer = "announce.syncthing.net:22026"
  272. }
  273. return cfg, err
  274. }
  275. func convertV1V2(cfg *Configuration) {
  276. // Collect the list of nodes.
  277. // Replace node configs inside repositories with only a reference to the nide ID.
  278. // Set all repositories to read only if the global read only flag is set.
  279. var nodes = map[string]NodeConfiguration{}
  280. for i, repo := range cfg.Repositories {
  281. cfg.Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  282. for j, node := range repo.Nodes {
  283. id := node.NodeID.String()
  284. if _, ok := nodes[id]; !ok {
  285. nodes[id] = node
  286. }
  287. cfg.Repositories[i].Nodes[j] = NodeConfiguration{NodeID: node.NodeID}
  288. }
  289. }
  290. cfg.Options.Deprecated_ReadOnly = false
  291. // Set and sort the list of nodes.
  292. for _, node := range nodes {
  293. cfg.Nodes = append(cfg.Nodes, node)
  294. }
  295. sort.Sort(NodeConfigurationList(cfg.Nodes))
  296. // GUI
  297. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  298. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  299. cfg.Options.Deprecated_GUIEnabled = false
  300. cfg.Options.Deprecated_GUIAddress = ""
  301. cfg.Version = 2
  302. }
  303. type NodeConfigurationList []NodeConfiguration
  304. func (l NodeConfigurationList) Less(a, b int) bool {
  305. return l[a].NodeID.Compare(l[b].NodeID) == -1
  306. }
  307. func (l NodeConfigurationList) Swap(a, b int) {
  308. l[a], l[b] = l[b], l[a]
  309. }
  310. func (l NodeConfigurationList) Len() int {
  311. return len(l)
  312. }
  313. func ensureNodePresent(nodes []NodeConfiguration, myID protocol.NodeID) []NodeConfiguration {
  314. var myIDExists bool
  315. for _, node := range nodes {
  316. if node.NodeID.Equals(myID) {
  317. myIDExists = true
  318. break
  319. }
  320. }
  321. if !myIDExists {
  322. name, _ := os.Hostname()
  323. nodes = append(nodes, NodeConfiguration{
  324. NodeID: myID,
  325. Name: name,
  326. })
  327. }
  328. sort.Sort(NodeConfigurationList(nodes))
  329. return nodes
  330. }