config.go 12 KB

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