config.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright (C) 2014 Jakob Borg and other contributors. All rights reserved.
  2. // Use of this source code is governed by an MIT-style license that can be
  3. // 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. "strings"
  15. "code.google.com/p/go.crypto/bcrypt"
  16. "github.com/calmh/syncthing/logger"
  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 []string
  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() []string {
  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 string `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:22025"`
  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. Deprecated_ReadOnly bool `xml:"readOnly,omitempty" json:"-"`
  97. Deprecated_GUIEnabled bool `xml:"guiEnabled,omitempty" json:"-"`
  98. Deprecated_GUIAddress string `xml:"guiAddress,omitempty" json:"-"`
  99. }
  100. type GUIConfiguration struct {
  101. Enabled bool `xml:"enabled,attr" default:"true"`
  102. Address string `xml:"address" default:"127.0.0.1:8080"`
  103. User string `xml:"user,omitempty"`
  104. Password string `xml:"password,omitempty"`
  105. UseTLS bool `xml:"tls,attr"`
  106. APIKey string `xml:"apikey,omitempty"`
  107. }
  108. func setDefaults(data interface{}) error {
  109. s := reflect.ValueOf(data).Elem()
  110. t := s.Type()
  111. for i := 0; i < s.NumField(); i++ {
  112. f := s.Field(i)
  113. tag := t.Field(i).Tag
  114. v := tag.Get("default")
  115. if len(v) > 0 {
  116. switch f.Interface().(type) {
  117. case string:
  118. f.SetString(v)
  119. case int:
  120. i, err := strconv.ParseInt(v, 10, 64)
  121. if err != nil {
  122. return err
  123. }
  124. f.SetInt(i)
  125. case bool:
  126. f.SetBool(v == "true")
  127. case []string:
  128. // We don't do anything with string slices here. Any default
  129. // we set will be appended to by the XML decoder, so we fill
  130. // those after decoding.
  131. default:
  132. panic(f.Type())
  133. }
  134. }
  135. }
  136. return nil
  137. }
  138. // fillNilSlices sets default value on slices that are still nil.
  139. func fillNilSlices(data interface{}) error {
  140. s := reflect.ValueOf(data).Elem()
  141. t := s.Type()
  142. for i := 0; i < s.NumField(); i++ {
  143. f := s.Field(i)
  144. tag := t.Field(i).Tag
  145. v := tag.Get("default")
  146. if len(v) > 0 {
  147. switch f.Interface().(type) {
  148. case []string:
  149. if f.IsNil() {
  150. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1)
  151. rv.Index(0).SetString(v)
  152. f.Set(rv)
  153. }
  154. }
  155. }
  156. }
  157. return nil
  158. }
  159. func Save(wr io.Writer, cfg Configuration) error {
  160. e := xml.NewEncoder(wr)
  161. e.Indent("", " ")
  162. err := e.Encode(cfg)
  163. if err != nil {
  164. return err
  165. }
  166. _, err = wr.Write([]byte("\n"))
  167. return err
  168. }
  169. func uniqueStrings(ss []string) []string {
  170. var m = make(map[string]bool, len(ss))
  171. for _, s := range ss {
  172. m[s] = true
  173. }
  174. var us = make([]string, 0, len(m))
  175. for k := range m {
  176. us = append(us, k)
  177. }
  178. return us
  179. }
  180. func Load(rd io.Reader, myID string) (Configuration, error) {
  181. var cfg Configuration
  182. setDefaults(&cfg)
  183. setDefaults(&cfg.Options)
  184. setDefaults(&cfg.GUI)
  185. var err error
  186. if rd != nil {
  187. err = xml.NewDecoder(rd).Decode(&cfg)
  188. }
  189. fillNilSlices(&cfg.Options)
  190. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  191. // Initialize an empty slice for repositories if the config has none
  192. if cfg.Repositories == nil {
  193. cfg.Repositories = []RepositoryConfiguration{}
  194. }
  195. // Sanitize node IDs
  196. for i := range cfg.Nodes {
  197. node := &cfg.Nodes[i]
  198. // Strip spaces and dashes
  199. node.NodeID = strings.Replace(node.NodeID, "-", "", -1)
  200. node.NodeID = strings.Replace(node.NodeID, " ", "", -1)
  201. node.NodeID = strings.ToUpper(node.NodeID)
  202. }
  203. // Check for missing, bad or duplicate repository ID:s
  204. var seenRepos = map[string]*RepositoryConfiguration{}
  205. var uniqueCounter int
  206. for i := range cfg.Repositories {
  207. repo := &cfg.Repositories[i]
  208. if len(repo.Directory) == 0 {
  209. repo.Invalid = "no directory configured"
  210. continue
  211. }
  212. if repo.ID == "" {
  213. repo.ID = "default"
  214. }
  215. for i := range repo.Nodes {
  216. node := &repo.Nodes[i]
  217. // Strip spaces and dashes
  218. node.NodeID = strings.Replace(node.NodeID, "-", "", -1)
  219. node.NodeID = strings.Replace(node.NodeID, " ", "", -1)
  220. }
  221. if seen, ok := seenRepos[repo.ID]; ok {
  222. l.Warnf("Multiple repositories with ID %q; disabling", repo.ID)
  223. seen.Invalid = "duplicate repository ID"
  224. if seen.ID == repo.ID {
  225. uniqueCounter++
  226. seen.ID = fmt.Sprintf("%s~%d", repo.ID, uniqueCounter)
  227. }
  228. repo.Invalid = "duplicate repository ID"
  229. uniqueCounter++
  230. repo.ID = fmt.Sprintf("%s~%d", repo.ID, uniqueCounter)
  231. } else {
  232. seenRepos[repo.ID] = repo
  233. }
  234. }
  235. // Upgrade to v2 configuration if appropriate
  236. if cfg.Version == 1 {
  237. convertV1V2(&cfg)
  238. }
  239. // Hash old cleartext passwords
  240. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  241. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  242. if err != nil {
  243. l.Warnln(err)
  244. } else {
  245. cfg.GUI.Password = string(hash)
  246. }
  247. }
  248. // Ensure this node is present in all relevant places
  249. cfg.Nodes = ensureNodePresent(cfg.Nodes, myID)
  250. for i := range cfg.Repositories {
  251. cfg.Repositories[i].Nodes = ensureNodePresent(cfg.Repositories[i].Nodes, myID)
  252. }
  253. // An empty address list is equivalent to a single "dynamic" entry
  254. for i := range cfg.Nodes {
  255. n := &cfg.Nodes[i]
  256. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  257. n.Addresses = []string{"dynamic"}
  258. }
  259. }
  260. return cfg, err
  261. }
  262. func convertV1V2(cfg *Configuration) {
  263. // Collect the list of nodes.
  264. // Replace node configs inside repositories with only a reference to the nide ID.
  265. // Set all repositories to read only if the global read only flag is set.
  266. var nodes = map[string]NodeConfiguration{}
  267. for i, repo := range cfg.Repositories {
  268. cfg.Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  269. for j, node := range repo.Nodes {
  270. if _, ok := nodes[node.NodeID]; !ok {
  271. nodes[node.NodeID] = node
  272. }
  273. cfg.Repositories[i].Nodes[j] = NodeConfiguration{NodeID: node.NodeID}
  274. }
  275. }
  276. cfg.Options.Deprecated_ReadOnly = false
  277. // Set and sort the list of nodes.
  278. for _, node := range nodes {
  279. cfg.Nodes = append(cfg.Nodes, node)
  280. }
  281. sort.Sort(NodeConfigurationList(cfg.Nodes))
  282. // GUI
  283. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  284. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  285. cfg.Options.Deprecated_GUIEnabled = false
  286. cfg.Options.Deprecated_GUIAddress = ""
  287. cfg.Version = 2
  288. }
  289. type NodeConfigurationList []NodeConfiguration
  290. func (l NodeConfigurationList) Less(a, b int) bool {
  291. return l[a].NodeID < l[b].NodeID
  292. }
  293. func (l NodeConfigurationList) Swap(a, b int) {
  294. l[a], l[b] = l[b], l[a]
  295. }
  296. func (l NodeConfigurationList) Len() int {
  297. return len(l)
  298. }
  299. func ensureNodePresent(nodes []NodeConfiguration, myID string) []NodeConfiguration {
  300. var myIDExists bool
  301. for _, node := range nodes {
  302. if node.NodeID == myID {
  303. myIDExists = true
  304. break
  305. }
  306. }
  307. if !myIDExists {
  308. name, _ := os.Hostname()
  309. nodes = append(nodes, NodeConfiguration{
  310. NodeID: myID,
  311. Name: name,
  312. })
  313. }
  314. sort.Sort(NodeConfigurationList(nodes))
  315. return nodes
  316. }