optionsconfiguration.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 https://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "fmt"
  9. "net"
  10. "runtime"
  11. "slices"
  12. "strings"
  13. "github.com/syncthing/syncthing/lib/protocol"
  14. "github.com/syncthing/syncthing/lib/rand"
  15. "github.com/syncthing/syncthing/lib/stringutil"
  16. "github.com/syncthing/syncthing/lib/structutil"
  17. )
  18. type OptionsConfiguration struct {
  19. RawListenAddresses []string `json:"listenAddresses" xml:"listenAddress" default:"default"`
  20. RawGlobalAnnServers []string `json:"globalAnnounceServers" xml:"globalAnnounceServer" default:"default"`
  21. GlobalAnnEnabled bool `json:"globalAnnounceEnabled" xml:"globalAnnounceEnabled" default:"true"`
  22. LocalAnnEnabled bool `json:"localAnnounceEnabled" xml:"localAnnounceEnabled" default:"true"`
  23. LocalAnnPort int `json:"localAnnouncePort" xml:"localAnnouncePort" default:"21027"`
  24. LocalAnnMCAddr string `json:"localAnnounceMCAddr" xml:"localAnnounceMCAddr" default:"[ff12::8384]:21027"`
  25. MaxSendKbps int `json:"maxSendKbps" xml:"maxSendKbps"`
  26. MaxRecvKbps int `json:"maxRecvKbps" xml:"maxRecvKbps"`
  27. ReconnectIntervalS int `json:"reconnectionIntervalS" xml:"reconnectionIntervalS" default:"60"`
  28. RelaysEnabled bool `json:"relaysEnabled" xml:"relaysEnabled" default:"true"`
  29. RelayReconnectIntervalM int `json:"relayReconnectIntervalM" xml:"relayReconnectIntervalM" default:"10"`
  30. StartBrowser bool `json:"startBrowser" xml:"startBrowser" default:"true"`
  31. NATEnabled bool `json:"natEnabled" xml:"natEnabled" default:"true"`
  32. NATLeaseM int `json:"natLeaseMinutes" xml:"natLeaseMinutes" default:"60"`
  33. NATRenewalM int `json:"natRenewalMinutes" xml:"natRenewalMinutes" default:"30"`
  34. NATTimeoutS int `json:"natTimeoutSeconds" xml:"natTimeoutSeconds" default:"10"`
  35. URAccepted int `json:"urAccepted" xml:"urAccepted"`
  36. URSeen int `json:"urSeen" xml:"urSeen"`
  37. URUniqueID string `json:"urUniqueId" xml:"urUniqueID"`
  38. URURL string `json:"urURL" xml:"urURL" default:"https://data.syncthing.net/newdata"`
  39. URPostInsecurely bool `json:"urPostInsecurely" xml:"urPostInsecurely" default:"false"`
  40. URInitialDelayS int `json:"urInitialDelayS" xml:"urInitialDelayS" default:"1800"`
  41. AutoUpgradeIntervalH int `json:"autoUpgradeIntervalH" xml:"autoUpgradeIntervalH" default:"12"`
  42. UpgradeToPreReleases bool `json:"upgradeToPreReleases" xml:"upgradeToPreReleases"`
  43. KeepTemporariesH int `json:"keepTemporariesH" xml:"keepTemporariesH" default:"24"`
  44. CacheIgnoredFiles bool `json:"cacheIgnoredFiles" xml:"cacheIgnoredFiles" default:"false"`
  45. ProgressUpdateIntervalS int `json:"progressUpdateIntervalS" xml:"progressUpdateIntervalS" default:"5"`
  46. LimitBandwidthInLan bool `json:"limitBandwidthInLan" xml:"limitBandwidthInLan" default:"false"`
  47. MinHomeDiskFree Size `json:"minHomeDiskFree" xml:"minHomeDiskFree" default:"1 %"`
  48. ReleasesURL string `json:"releasesURL" xml:"releasesURL" default:"https://upgrades.syncthing.net/meta.json"`
  49. AlwaysLocalNets []string `json:"alwaysLocalNets" xml:"alwaysLocalNet"`
  50. OverwriteRemoteDevNames bool `json:"overwriteRemoteDeviceNamesOnConnect" xml:"overwriteRemoteDeviceNamesOnConnect" default:"false"`
  51. TempIndexMinBlocks int `json:"tempIndexMinBlocks" xml:"tempIndexMinBlocks" default:"10"`
  52. UnackedNotificationIDs []string `json:"unackedNotificationIDs" xml:"unackedNotificationID"`
  53. TrafficClass int `json:"trafficClass" xml:"trafficClass"`
  54. DeprecatedDefaultFolderPath string `json:"-" xml:"defaultFolderPath,omitempty"` // Deprecated: Do not use.
  55. SetLowPriority bool `json:"setLowPriority" xml:"setLowPriority" default:"true"`
  56. RawMaxFolderConcurrency int `json:"maxFolderConcurrency" xml:"maxFolderConcurrency"`
  57. CRURL string `json:"crURL" xml:"crashReportingURL" default:"https://crash.syncthing.net/newcrash"`
  58. CREnabled bool `json:"crashReportingEnabled" xml:"crashReportingEnabled" default:"true"`
  59. StunKeepaliveStartS int `json:"stunKeepaliveStartS" xml:"stunKeepaliveStartS" default:"180"`
  60. StunKeepaliveMinS int `json:"stunKeepaliveMinS" xml:"stunKeepaliveMinS" default:"20"`
  61. RawStunServers []string `json:"stunServers" xml:"stunServer" default:"default"`
  62. RawMaxCIRequestKiB int `json:"maxConcurrentIncomingRequestKiB" xml:"maxConcurrentIncomingRequestKiB"`
  63. AnnounceLANAddresses bool `json:"announceLANAddresses" xml:"announceLANAddresses" default:"true"`
  64. SendFullIndexOnUpgrade bool `json:"sendFullIndexOnUpgrade" xml:"sendFullIndexOnUpgrade"`
  65. FeatureFlags []string `json:"featureFlags" xml:"featureFlag"`
  66. AuditEnabled bool `json:"auditEnabled" xml:"auditEnabled" default:"false" restart:"true"`
  67. AuditFile string `json:"auditFile" xml:"auditFile" restart:"true"`
  68. // The number of connections at which we stop trying to connect to more
  69. // devices, zero meaning no limit. Does not affect incoming connections.
  70. ConnectionLimitEnough int `json:"connectionLimitEnough" xml:"connectionLimitEnough"`
  71. // The maximum number of connections which we will allow in total, zero
  72. // meaning no limit. Affects incoming connections and prevents
  73. // attempting outgoing connections.
  74. ConnectionLimitMax int `json:"connectionLimitMax" xml:"connectionLimitMax"`
  75. ConnectionPriorityTCPLAN int `json:"connectionPriorityTcpLan" xml:"connectionPriorityTcpLan" default:"10"`
  76. ConnectionPriorityQUICLAN int `json:"connectionPriorityQuicLan" xml:"connectionPriorityQuicLan" default:"20"`
  77. ConnectionPriorityTCPWAN int `json:"connectionPriorityTcpWan" xml:"connectionPriorityTcpWan" default:"30"`
  78. ConnectionPriorityQUICWAN int `json:"connectionPriorityQuicWan" xml:"connectionPriorityQuicWan" default:"40"`
  79. ConnectionPriorityRelay int `json:"connectionPriorityRelay" xml:"connectionPriorityRelay" default:"50"`
  80. ConnectionPriorityUpgradeThreshold int `json:"connectionPriorityUpgradeThreshold" xml:"connectionPriorityUpgradeThreshold" default:"0"`
  81. // Legacy deprecated
  82. DeprecatedUPnPEnabled bool `json:"-" xml:"upnpEnabled,omitempty"` // Deprecated: Do not use.
  83. DeprecatedUPnPLeaseM int `json:"-" xml:"upnpLeaseMinutes,omitempty"` // Deprecated: Do not use.
  84. DeprecatedUPnPRenewalM int `json:"-" xml:"upnpRenewalMinutes,omitempty"` // Deprecated: Do not use.
  85. DeprecatedUPnPTimeoutS int `json:"-" xml:"upnpTimeoutSeconds,omitempty"` // Deprecated: Do not use.
  86. DeprecatedRelayServers []string `json:"-" xml:"relayServer,omitempty"` // Deprecated: Do not use.
  87. DeprecatedMinHomeDiskFreePct float64 `json:"-" xml:"minHomeDiskFreePct,omitempty"` // Deprecated: Do not use.
  88. DeprecatedMaxConcurrentScans int `json:"-" xml:"maxConcurrentScans,omitempty"` // Deprecated: Do not use.
  89. }
  90. func (opts OptionsConfiguration) Copy() OptionsConfiguration {
  91. optsCopy := opts
  92. optsCopy.RawListenAddresses = make([]string, len(opts.RawListenAddresses))
  93. copy(optsCopy.RawListenAddresses, opts.RawListenAddresses)
  94. optsCopy.RawGlobalAnnServers = make([]string, len(opts.RawGlobalAnnServers))
  95. copy(optsCopy.RawGlobalAnnServers, opts.RawGlobalAnnServers)
  96. optsCopy.AlwaysLocalNets = make([]string, len(opts.AlwaysLocalNets))
  97. copy(optsCopy.AlwaysLocalNets, opts.AlwaysLocalNets)
  98. optsCopy.UnackedNotificationIDs = make([]string, len(opts.UnackedNotificationIDs))
  99. copy(optsCopy.UnackedNotificationIDs, opts.UnackedNotificationIDs)
  100. return optsCopy
  101. }
  102. func (opts *OptionsConfiguration) prepare(guiPWIsSet bool) {
  103. structutil.FillNilSlices(opts)
  104. opts.RawListenAddresses = stringutil.UniqueTrimmedStrings(opts.RawListenAddresses)
  105. opts.RawGlobalAnnServers = stringutil.UniqueTrimmedStrings(opts.RawGlobalAnnServers)
  106. // Very short reconnection intervals are annoying
  107. if opts.ReconnectIntervalS < 5 {
  108. opts.ReconnectIntervalS = 5
  109. }
  110. if guiPWIsSet && len(opts.UnackedNotificationIDs) > 0 {
  111. for i, key := range opts.UnackedNotificationIDs {
  112. if key == "authenticationUserAndPassword" {
  113. opts.UnackedNotificationIDs = append(opts.UnackedNotificationIDs[:i], opts.UnackedNotificationIDs[i+1:]...)
  114. break
  115. }
  116. }
  117. }
  118. // Negative limits are meaningless, zero means unlimited.
  119. if opts.ConnectionLimitEnough < 0 {
  120. opts.ConnectionLimitEnough = 0
  121. }
  122. if opts.ConnectionLimitMax < 0 {
  123. opts.ConnectionLimitMax = 0
  124. }
  125. if opts.ConnectionPriorityQUICWAN <= opts.ConnectionPriorityQUICLAN {
  126. opts.ConnectionPriorityQUICWAN = opts.ConnectionPriorityQUICLAN + 1
  127. }
  128. if opts.ConnectionPriorityTCPWAN <= opts.ConnectionPriorityTCPLAN {
  129. opts.ConnectionPriorityTCPWAN = opts.ConnectionPriorityTCPLAN + 1
  130. }
  131. // If usage reporting is enabled we must have a unique ID.
  132. if opts.URAccepted > 0 && opts.URUniqueID == "" {
  133. opts.URUniqueID = rand.String(8)
  134. }
  135. }
  136. // RequiresRestartOnly returns a copy with only the attributes that require
  137. // restart on change.
  138. func (opts OptionsConfiguration) RequiresRestartOnly() OptionsConfiguration {
  139. optsCopy := opts
  140. blank := OptionsConfiguration{}
  141. copyMatchingTag(&blank, &optsCopy, "restart", func(v string) bool {
  142. if len(v) > 0 && v != "true" {
  143. panic(fmt.Sprintf(`unexpected tag value: %s. Expected untagged or "true"`, v))
  144. }
  145. return v != "true"
  146. })
  147. return optsCopy
  148. }
  149. func (opts OptionsConfiguration) IsStunDisabled() bool {
  150. return opts.StunKeepaliveMinS < 1 || opts.StunKeepaliveStartS < 1 || !opts.NATEnabled
  151. }
  152. func (opts OptionsConfiguration) ListenAddresses() []string {
  153. var addresses []string
  154. for _, addr := range opts.RawListenAddresses {
  155. switch addr {
  156. case "default":
  157. addresses = append(addresses, DefaultListenAddresses...)
  158. default:
  159. addresses = append(addresses, addr)
  160. }
  161. }
  162. return stringutil.UniqueTrimmedStrings(addresses)
  163. }
  164. func (opts OptionsConfiguration) StunServers() []string {
  165. var addresses []string
  166. for _, addr := range opts.RawStunServers {
  167. switch addr {
  168. case "default":
  169. _, records, err := net.LookupSRV("stun", "udp", "syncthing.net")
  170. if err != nil {
  171. l.Debugln("Unable to resolve primary STUN servers via DNS:", err)
  172. }
  173. for _, record := range records {
  174. priority := record.Priority
  175. target := strings.TrimSuffix(record.Target, ".")
  176. address := fmt.Sprintf("%s:%d", target, record.Port)
  177. l.Debugf("Resolved primary STUN server %s with priority %d", address, priority)
  178. addresses = append(addresses, address)
  179. }
  180. fallbackAddresses := slices.Clone(DefaultFallbackStunServers)
  181. rand.Shuffle(fallbackAddresses)
  182. addresses = append(addresses, fallbackAddresses...)
  183. default:
  184. addresses = append(addresses, addr)
  185. }
  186. }
  187. addresses = stringutil.UniqueTrimmedStrings(addresses)
  188. return addresses
  189. }
  190. func (opts OptionsConfiguration) GlobalDiscoveryServers() []string {
  191. var servers []string
  192. for _, srv := range opts.RawGlobalAnnServers {
  193. switch srv {
  194. case "default":
  195. servers = append(servers, DefaultDiscoveryServers...)
  196. case "default-v4":
  197. servers = append(servers, DefaultDiscoveryServersV4...)
  198. case "default-v6":
  199. servers = append(servers, DefaultDiscoveryServersV6...)
  200. default:
  201. servers = append(servers, srv)
  202. }
  203. }
  204. return stringutil.UniqueTrimmedStrings(servers)
  205. }
  206. func (opts OptionsConfiguration) MaxFolderConcurrency() int {
  207. // If a value is set, trust that.
  208. if opts.RawMaxFolderConcurrency > 0 {
  209. return opts.RawMaxFolderConcurrency
  210. }
  211. if opts.RawMaxFolderConcurrency < 0 {
  212. // -1 etc means unlimited, which in the implementation means zero
  213. return 0
  214. }
  215. // Otherwise default to the number of CPU cores in the system as a rough
  216. // approximation of system powerfulness.
  217. if n := runtime.GOMAXPROCS(-1); n > 0 {
  218. return n
  219. }
  220. // We should never get here to begin with, but since we're here let's
  221. // use some sort of reasonable compromise between the old "no limit" and
  222. // getting nothing done... (Median number of folders out there at time
  223. // of writing is two, 95-percentile at 12 folders.)
  224. return 4 // https://xkcd.com/221/
  225. }
  226. func (opts OptionsConfiguration) MaxConcurrentIncomingRequestKiB() int {
  227. // Negative is disabled, which in limiter land is spelled zero
  228. if opts.RawMaxCIRequestKiB < 0 {
  229. return 0
  230. }
  231. if opts.RawMaxCIRequestKiB == 0 {
  232. // The default is 256 MiB
  233. return 256 * 1024 // KiB
  234. }
  235. // We can't really do less than a couple of concurrent blocks or we'll
  236. // pretty much stall completely. Check that an explicit value is large
  237. // enough.
  238. const minAllowed = 2 * protocol.MaxBlockSize / 1024
  239. if opts.RawMaxCIRequestKiB < minAllowed {
  240. return minAllowed
  241. }
  242. // Roll with it.
  243. return opts.RawMaxCIRequestKiB
  244. }
  245. func (opts OptionsConfiguration) AutoUpgradeEnabled() bool {
  246. return opts.AutoUpgradeIntervalH > 0
  247. }
  248. func (opts OptionsConfiguration) FeatureFlag(name string) bool {
  249. return slices.Contains(opts.FeatureFlags, name)
  250. }
  251. // LowestConnectionLimit is the lower of ConnectionLimitEnough or
  252. // ConnectionLimitMax, or whichever of them is actually set if only one of
  253. // them is set. It's the point where we should stop dialing.
  254. func (opts OptionsConfiguration) LowestConnectionLimit() int {
  255. limit := opts.ConnectionLimitEnough
  256. if limit == 0 || (opts.ConnectionLimitMax != 0 && opts.ConnectionLimitMax < limit) {
  257. // It doesn't really make sense to set Max lower than Enough but
  258. // someone might do it while experimenting and it's easy for us to
  259. // do the right thing.
  260. limit = opts.ConnectionLimitMax
  261. }
  262. return limit
  263. }