config.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // Package config implements reading and writing of the syncthing configuration file.
  2. package config
  3. import (
  4. "encoding/xml"
  5. "fmt"
  6. "io"
  7. "os"
  8. "reflect"
  9. "sort"
  10. "strconv"
  11. "code.google.com/p/go.crypto/bcrypt"
  12. "github.com/calmh/syncthing/logger"
  13. )
  14. var l = logger.DefaultLogger
  15. type Configuration struct {
  16. Version int `xml:"version,attr" default:"2"`
  17. Repositories []RepositoryConfiguration `xml:"repository"`
  18. Nodes []NodeConfiguration `xml:"node"`
  19. GUI GUIConfiguration `xml:"gui"`
  20. Options OptionsConfiguration `xml:"options"`
  21. XMLName xml.Name `xml:"configuration" json:"-"`
  22. }
  23. type RepositoryConfiguration struct {
  24. ID string `xml:"id,attr"`
  25. Directory string `xml:"directory,attr"`
  26. Nodes []NodeConfiguration `xml:"node"`
  27. ReadOnly bool `xml:"ro,attr"`
  28. Invalid string `xml:"-"` // Set at runtime when there is an error, not saved
  29. nodeIDs []string
  30. }
  31. func (r *RepositoryConfiguration) NodeIDs() []string {
  32. if r.nodeIDs == nil {
  33. for _, n := range r.Nodes {
  34. r.nodeIDs = append(r.nodeIDs, n.NodeID)
  35. }
  36. }
  37. return r.nodeIDs
  38. }
  39. type NodeConfiguration struct {
  40. NodeID string `xml:"id,attr"`
  41. Name string `xml:"name,attr,omitempty"`
  42. Addresses []string `xml:"address,omitempty"`
  43. }
  44. type OptionsConfiguration struct {
  45. ListenAddress []string `xml:"listenAddress" default:"0.0.0.0:22000"`
  46. GlobalAnnServer string `xml:"globalAnnounceServer" default:"announce.syncthing.net:22025"`
  47. GlobalAnnEnabled bool `xml:"globalAnnounceEnabled" default:"true"`
  48. LocalAnnEnabled bool `xml:"localAnnounceEnabled" default:"true"`
  49. ParallelRequests int `xml:"parallelRequests" default:"16"`
  50. MaxSendKbps int `xml:"maxSendKbps"`
  51. RescanIntervalS int `xml:"rescanIntervalS" default:"60"`
  52. ReconnectIntervalS int `xml:"reconnectionIntervalS" default:"60"`
  53. MaxChangeKbps int `xml:"maxChangeKbps" default:"10000"`
  54. StartBrowser bool `xml:"startBrowser" default:"true"`
  55. UPnPEnabled bool `xml:"upnpEnabled" default:"true"`
  56. Deprecated_ReadOnly bool `xml:"readOnly,omitempty" json:"-"`
  57. Deprecated_GUIEnabled bool `xml:"guiEnabled,omitempty" json:"-"`
  58. Deprecated_GUIAddress string `xml:"guiAddress,omitempty" json:"-"`
  59. }
  60. type GUIConfiguration struct {
  61. Enabled bool `xml:"enabled,attr" default:"true"`
  62. Address string `xml:"address" default:"127.0.0.1:8080"`
  63. User string `xml:"user,omitempty"`
  64. Password string `xml:"password,omitempty"`
  65. }
  66. func setDefaults(data interface{}) error {
  67. s := reflect.ValueOf(data).Elem()
  68. t := s.Type()
  69. for i := 0; i < s.NumField(); i++ {
  70. f := s.Field(i)
  71. tag := t.Field(i).Tag
  72. v := tag.Get("default")
  73. if len(v) > 0 {
  74. switch f.Interface().(type) {
  75. case string:
  76. f.SetString(v)
  77. case int:
  78. i, err := strconv.ParseInt(v, 10, 64)
  79. if err != nil {
  80. return err
  81. }
  82. f.SetInt(i)
  83. case bool:
  84. f.SetBool(v == "true")
  85. case []string:
  86. // We don't do anything with string slices here. Any default
  87. // we set will be appended to by the XML decoder, so we fill
  88. // those after decoding.
  89. default:
  90. panic(f.Type())
  91. }
  92. }
  93. }
  94. return nil
  95. }
  96. // fillNilSlices sets default value on slices that are still nil.
  97. func fillNilSlices(data interface{}) error {
  98. s := reflect.ValueOf(data).Elem()
  99. t := s.Type()
  100. for i := 0; i < s.NumField(); i++ {
  101. f := s.Field(i)
  102. tag := t.Field(i).Tag
  103. v := tag.Get("default")
  104. if len(v) > 0 {
  105. switch f.Interface().(type) {
  106. case []string:
  107. if f.IsNil() {
  108. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1)
  109. rv.Index(0).SetString(v)
  110. f.Set(rv)
  111. }
  112. }
  113. }
  114. }
  115. return nil
  116. }
  117. func Save(wr io.Writer, cfg Configuration) error {
  118. e := xml.NewEncoder(wr)
  119. e.Indent("", " ")
  120. err := e.Encode(cfg)
  121. if err != nil {
  122. return err
  123. }
  124. _, err = wr.Write([]byte("\n"))
  125. return err
  126. }
  127. func uniqueStrings(ss []string) []string {
  128. var m = make(map[string]bool, len(ss))
  129. for _, s := range ss {
  130. m[s] = true
  131. }
  132. var us = make([]string, 0, len(m))
  133. for k := range m {
  134. us = append(us, k)
  135. }
  136. return us
  137. }
  138. func Load(rd io.Reader, myID string) (Configuration, error) {
  139. var cfg Configuration
  140. setDefaults(&cfg)
  141. setDefaults(&cfg.Options)
  142. setDefaults(&cfg.GUI)
  143. var err error
  144. if rd != nil {
  145. err = xml.NewDecoder(rd).Decode(&cfg)
  146. }
  147. fillNilSlices(&cfg.Options)
  148. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  149. // Initialize an empty slice for repositories if the config has none
  150. if cfg.Repositories == nil {
  151. cfg.Repositories = []RepositoryConfiguration{}
  152. }
  153. // Check for missing, bad or duplicate repository ID:s
  154. var seenRepos = map[string]*RepositoryConfiguration{}
  155. var uniqueCounter int
  156. for i := range cfg.Repositories {
  157. repo := &cfg.Repositories[i]
  158. if len(repo.Directory) == 0 {
  159. repo.Invalid = "empty directory"
  160. continue
  161. }
  162. if repo.ID == "" {
  163. repo.ID = "default"
  164. }
  165. if seen, ok := seenRepos[repo.ID]; ok {
  166. l.Warnf("Multiple repositories with ID %q; disabling", repo.ID)
  167. seen.Invalid = "duplicate repository ID"
  168. if seen.ID == repo.ID {
  169. uniqueCounter++
  170. seen.ID = fmt.Sprintf("%s~%d", repo.ID, uniqueCounter)
  171. }
  172. repo.Invalid = "duplicate repository ID"
  173. uniqueCounter++
  174. repo.ID = fmt.Sprintf("%s~%d", repo.ID, uniqueCounter)
  175. } else {
  176. seenRepos[repo.ID] = repo
  177. }
  178. }
  179. // Upgrade to v2 configuration if appropriate
  180. if cfg.Version == 1 {
  181. convertV1V2(&cfg)
  182. }
  183. // Hash old cleartext passwords
  184. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  185. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  186. if err != nil {
  187. l.Warnln(err)
  188. } else {
  189. cfg.GUI.Password = string(hash)
  190. }
  191. }
  192. // Ensure this node is present in all relevant places
  193. cfg.Nodes = ensureNodePresent(cfg.Nodes, myID)
  194. for i := range cfg.Repositories {
  195. cfg.Repositories[i].Nodes = ensureNodePresent(cfg.Repositories[i].Nodes, myID)
  196. }
  197. // An empty address list is equivalent to a single "dynamic" entry
  198. for i := range cfg.Nodes {
  199. n := &cfg.Nodes[i]
  200. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  201. n.Addresses = []string{"dynamic"}
  202. }
  203. }
  204. return cfg, err
  205. }
  206. func convertV1V2(cfg *Configuration) {
  207. // Collect the list of nodes.
  208. // Replace node configs inside repositories with only a reference to the nide ID.
  209. // Set all repositories to read only if the global read only flag is set.
  210. var nodes = map[string]NodeConfiguration{}
  211. for i, repo := range cfg.Repositories {
  212. cfg.Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  213. for j, node := range repo.Nodes {
  214. if _, ok := nodes[node.NodeID]; !ok {
  215. nodes[node.NodeID] = node
  216. }
  217. cfg.Repositories[i].Nodes[j] = NodeConfiguration{NodeID: node.NodeID}
  218. }
  219. }
  220. cfg.Options.Deprecated_ReadOnly = false
  221. // Set and sort the list of nodes.
  222. for _, node := range nodes {
  223. cfg.Nodes = append(cfg.Nodes, node)
  224. }
  225. sort.Sort(NodeConfigurationList(cfg.Nodes))
  226. // GUI
  227. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  228. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  229. cfg.Options.Deprecated_GUIEnabled = false
  230. cfg.Options.Deprecated_GUIAddress = ""
  231. cfg.Version = 2
  232. }
  233. type NodeConfigurationList []NodeConfiguration
  234. func (l NodeConfigurationList) Less(a, b int) bool {
  235. return l[a].NodeID < l[b].NodeID
  236. }
  237. func (l NodeConfigurationList) Swap(a, b int) {
  238. l[a], l[b] = l[b], l[a]
  239. }
  240. func (l NodeConfigurationList) Len() int {
  241. return len(l)
  242. }
  243. func ensureNodePresent(nodes []NodeConfiguration, myID string) []NodeConfiguration {
  244. var myIDExists bool
  245. for _, node := range nodes {
  246. if node.NodeID == myID {
  247. myIDExists = true
  248. break
  249. }
  250. }
  251. if !myIDExists {
  252. name, _ := os.Hostname()
  253. nodes = append(nodes, NodeConfiguration{
  254. NodeID: myID,
  255. Name: name,
  256. })
  257. }
  258. sort.Sort(NodeConfigurationList(nodes))
  259. return nodes
  260. }