guiconfiguration.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "net/url"
  9. "os"
  10. "strings"
  11. )
  12. type GUIConfiguration struct {
  13. Enabled bool `xml:"enabled,attr" json:"enabled" default:"true"`
  14. RawAddress string `xml:"address" json:"address" default:"127.0.0.1:8384"`
  15. User string `xml:"user,omitempty" json:"user"`
  16. Password string `xml:"password,omitempty" json:"password"`
  17. RawUseTLS bool `xml:"tls,attr" json:"useTLS"`
  18. RawAPIKey string `xml:"apikey,omitempty" json:"apiKey"`
  19. InsecureAdminAccess bool `xml:"insecureAdminAccess,omitempty" json:"insecureAdminAccess"`
  20. }
  21. func (c GUIConfiguration) Address() string {
  22. if override := os.Getenv("STGUIADDRESS"); override != "" {
  23. // This value may be of the form "scheme://address:port" or just
  24. // "address:port". We need to chop off the scheme. We try to parse it as
  25. // an URL if it contains a slash. If that fails, return it as is and let
  26. // some other error handling handle it.
  27. if strings.Contains(override, "/") {
  28. url, err := url.Parse(override)
  29. if err != nil {
  30. return override
  31. }
  32. return url.Host
  33. }
  34. return override
  35. }
  36. return c.RawAddress
  37. }
  38. func (c GUIConfiguration) UseTLS() bool {
  39. if override := os.Getenv("STGUIADDRESS"); override != "" && strings.HasPrefix(override, "http") {
  40. return strings.HasPrefix(override, "https:")
  41. }
  42. return c.RawUseTLS
  43. }
  44. func (c GUIConfiguration) URL() string {
  45. u := url.URL{
  46. Scheme: "http",
  47. Host: c.Address(),
  48. Path: "/",
  49. }
  50. if c.UseTLS() {
  51. u.Scheme = "https"
  52. }
  53. if strings.HasPrefix(u.Host, ":") {
  54. // Empty host, i.e. ":port", use IPv4 localhost
  55. u.Host = "127.0.0.1" + u.Host
  56. } else if strings.HasPrefix(u.Host, "0.0.0.0:") {
  57. // IPv4 all zeroes host, convert to IPv4 localhost
  58. u.Host = "127.0.0.1" + u.Host[7:]
  59. } else if strings.HasPrefix(u.Host, "[::]:") {
  60. // IPv6 all zeroes host, convert to IPv6 localhost
  61. u.Host = "[::1]" + u.Host[4:]
  62. }
  63. return u.String()
  64. }
  65. func (c GUIConfiguration) APIKey() string {
  66. if override := os.Getenv("STGUIAPIKEY"); override != "" {
  67. return override
  68. }
  69. return c.RawAPIKey
  70. }