optionsconfiguration.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. DatabaseTuning Tuning `json:"databaseTuning" xml:"databaseTuning" restart:"true"`
  63. RawMaxCIRequestKiB int `json:"maxConcurrentIncomingRequestKiB" xml:"maxConcurrentIncomingRequestKiB"`
  64. AnnounceLANAddresses bool `json:"announceLANAddresses" xml:"announceLANAddresses" default:"true"`
  65. SendFullIndexOnUpgrade bool `json:"sendFullIndexOnUpgrade" xml:"sendFullIndexOnUpgrade"`
  66. FeatureFlags []string `json:"featureFlags" xml:"featureFlag"`
  67. // The number of connections at which we stop trying to connect to more
  68. // devices, zero meaning no limit. Does not affect incoming connections.
  69. ConnectionLimitEnough int `json:"connectionLimitEnough" xml:"connectionLimitEnough"`
  70. // The maximum number of connections which we will allow in total, zero
  71. // meaning no limit. Affects incoming connections and prevents
  72. // attempting outgoing connections.
  73. ConnectionLimitMax int `json:"connectionLimitMax" xml:"connectionLimitMax"`
  74. // When set, this allows TLS 1.2 on sync connections, where we otherwise
  75. // default to TLS 1.3+ only.
  76. InsecureAllowOldTLSVersions bool `json:"insecureAllowOldTLSVersions" xml:"insecureAllowOldTLSVersions"`
  77. ConnectionPriorityTCPLAN int `json:"connectionPriorityTcpLan" xml:"connectionPriorityTcpLan" default:"10"`
  78. ConnectionPriorityQUICLAN int `json:"connectionPriorityQuicLan" xml:"connectionPriorityQuicLan" default:"20"`
  79. ConnectionPriorityTCPWAN int `json:"connectionPriorityTcpWan" xml:"connectionPriorityTcpWan" default:"30"`
  80. ConnectionPriorityQUICWAN int `json:"connectionPriorityQuicWan" xml:"connectionPriorityQuicWan" default:"40"`
  81. ConnectionPriorityRelay int `json:"connectionPriorityRelay" xml:"connectionPriorityRelay" default:"50"`
  82. ConnectionPriorityUpgradeThreshold int `json:"connectionPriorityUpgradeThreshold" xml:"connectionPriorityUpgradeThreshold" default:"0"`
  83. // Legacy deprecated
  84. DeprecatedUPnPEnabled bool `json:"-" xml:"upnpEnabled,omitempty"` // Deprecated: Do not use.
  85. DeprecatedUPnPLeaseM int `json:"-" xml:"upnpLeaseMinutes,omitempty"` // Deprecated: Do not use.
  86. DeprecatedUPnPRenewalM int `json:"-" xml:"upnpRenewalMinutes,omitempty"` // Deprecated: Do not use.
  87. DeprecatedUPnPTimeoutS int `json:"-" xml:"upnpTimeoutSeconds,omitempty"` // Deprecated: Do not use.
  88. DeprecatedRelayServers []string `json:"-" xml:"relayServer,omitempty"` // Deprecated: Do not use.
  89. DeprecatedMinHomeDiskFreePct float64 `json:"-" xml:"minHomeDiskFreePct,omitempty"` // Deprecated: Do not use.
  90. DeprecatedMaxConcurrentScans int `json:"-" xml:"maxConcurrentScans,omitempty"` // Deprecated: Do not use.
  91. }
  92. func (opts OptionsConfiguration) Copy() OptionsConfiguration {
  93. optsCopy := opts
  94. optsCopy.RawListenAddresses = make([]string, len(opts.RawListenAddresses))
  95. copy(optsCopy.RawListenAddresses, opts.RawListenAddresses)
  96. optsCopy.RawGlobalAnnServers = make([]string, len(opts.RawGlobalAnnServers))
  97. copy(optsCopy.RawGlobalAnnServers, opts.RawGlobalAnnServers)
  98. optsCopy.AlwaysLocalNets = make([]string, len(opts.AlwaysLocalNets))
  99. copy(optsCopy.AlwaysLocalNets, opts.AlwaysLocalNets)
  100. optsCopy.UnackedNotificationIDs = make([]string, len(opts.UnackedNotificationIDs))
  101. copy(optsCopy.UnackedNotificationIDs, opts.UnackedNotificationIDs)
  102. return optsCopy
  103. }
  104. func (opts *OptionsConfiguration) prepare(guiPWIsSet bool) {
  105. structutil.FillNilSlices(opts)
  106. opts.RawListenAddresses = stringutil.UniqueTrimmedStrings(opts.RawListenAddresses)
  107. opts.RawGlobalAnnServers = stringutil.UniqueTrimmedStrings(opts.RawGlobalAnnServers)
  108. // Very short reconnection intervals are annoying
  109. if opts.ReconnectIntervalS < 5 {
  110. opts.ReconnectIntervalS = 5
  111. }
  112. if guiPWIsSet && len(opts.UnackedNotificationIDs) > 0 {
  113. for i, key := range opts.UnackedNotificationIDs {
  114. if key == "authenticationUserAndPassword" {
  115. opts.UnackedNotificationIDs = append(opts.UnackedNotificationIDs[:i], opts.UnackedNotificationIDs[i+1:]...)
  116. break
  117. }
  118. }
  119. }
  120. // Negative limits are meaningless, zero means unlimited.
  121. if opts.ConnectionLimitEnough < 0 {
  122. opts.ConnectionLimitEnough = 0
  123. }
  124. if opts.ConnectionLimitMax < 0 {
  125. opts.ConnectionLimitMax = 0
  126. }
  127. if opts.ConnectionPriorityQUICWAN <= opts.ConnectionPriorityQUICLAN {
  128. l.Warnln("Connection priority number for QUIC over WAN must be worse (higher) than QUIC over LAN. Correcting.")
  129. opts.ConnectionPriorityQUICWAN = opts.ConnectionPriorityQUICLAN + 1
  130. }
  131. if opts.ConnectionPriorityTCPWAN <= opts.ConnectionPriorityTCPLAN {
  132. l.Warnln("Connection priority number for TCP over WAN must be worse (higher) than TCP over LAN. Correcting.")
  133. opts.ConnectionPriorityTCPWAN = opts.ConnectionPriorityTCPLAN + 1
  134. }
  135. // If usage reporting is enabled we must have a unique ID.
  136. if opts.URAccepted > 0 && opts.URUniqueID == "" {
  137. opts.URUniqueID = rand.String(8)
  138. }
  139. }
  140. // RequiresRestartOnly returns a copy with only the attributes that require
  141. // restart on change.
  142. func (opts OptionsConfiguration) RequiresRestartOnly() OptionsConfiguration {
  143. optsCopy := opts
  144. blank := OptionsConfiguration{}
  145. copyMatchingTag(&blank, &optsCopy, "restart", func(v string) bool {
  146. if len(v) > 0 && v != "true" {
  147. panic(fmt.Sprintf(`unexpected tag value: %s. Expected untagged or "true"`, v))
  148. }
  149. return v != "true"
  150. })
  151. return optsCopy
  152. }
  153. func (opts OptionsConfiguration) IsStunDisabled() bool {
  154. return opts.StunKeepaliveMinS < 1 || opts.StunKeepaliveStartS < 1 || !opts.NATEnabled
  155. }
  156. func (opts OptionsConfiguration) ListenAddresses() []string {
  157. var addresses []string
  158. for _, addr := range opts.RawListenAddresses {
  159. switch addr {
  160. case "default":
  161. addresses = append(addresses, DefaultListenAddresses...)
  162. default:
  163. addresses = append(addresses, addr)
  164. }
  165. }
  166. return stringutil.UniqueTrimmedStrings(addresses)
  167. }
  168. func (opts OptionsConfiguration) StunServers() []string {
  169. var addresses []string
  170. for _, addr := range opts.RawStunServers {
  171. switch addr {
  172. case "default":
  173. _, records, err := net.LookupSRV("stun", "udp", "syncthing.net")
  174. if err != nil {
  175. l.Warnln("Unable to resolve primary STUN servers via DNS:", err)
  176. }
  177. for _, record := range records {
  178. priority := record.Priority
  179. target := strings.TrimSuffix(record.Target, ".")
  180. address := fmt.Sprintf("%s:%d", target, record.Port)
  181. l.Debugf("Resolved primary STUN server %s with priority %d", address, priority)
  182. addresses = append(addresses, address)
  183. }
  184. fallbackAddresses := slices.Clone(DefaultFallbackStunServers)
  185. rand.Shuffle(fallbackAddresses)
  186. addresses = append(addresses, fallbackAddresses...)
  187. default:
  188. addresses = append(addresses, addr)
  189. }
  190. }
  191. addresses = stringutil.UniqueTrimmedStrings(addresses)
  192. return addresses
  193. }
  194. func (opts OptionsConfiguration) GlobalDiscoveryServers() []string {
  195. var servers []string
  196. for _, srv := range opts.RawGlobalAnnServers {
  197. switch srv {
  198. case "default":
  199. servers = append(servers, DefaultDiscoveryServers...)
  200. case "default-v4":
  201. servers = append(servers, DefaultDiscoveryServersV4...)
  202. case "default-v6":
  203. servers = append(servers, DefaultDiscoveryServersV6...)
  204. default:
  205. servers = append(servers, srv)
  206. }
  207. }
  208. return stringutil.UniqueTrimmedStrings(servers)
  209. }
  210. func (opts OptionsConfiguration) MaxFolderConcurrency() int {
  211. // If a value is set, trust that.
  212. if opts.RawMaxFolderConcurrency > 0 {
  213. return opts.RawMaxFolderConcurrency
  214. }
  215. if opts.RawMaxFolderConcurrency < 0 {
  216. // -1 etc means unlimited, which in the implementation means zero
  217. return 0
  218. }
  219. // Otherwise default to the number of CPU cores in the system as a rough
  220. // approximation of system powerfullness.
  221. if n := runtime.GOMAXPROCS(-1); n > 0 {
  222. return n
  223. }
  224. // We should never get here to begin with, but since we're here let's
  225. // use some sort of reasonable compromise between the old "no limit" and
  226. // getting nothing done... (Median number of folders out there at time
  227. // of writing is two, 95-percentile at 12 folders.)
  228. return 4 // https://xkcd.com/221/
  229. }
  230. func (opts OptionsConfiguration) MaxConcurrentIncomingRequestKiB() int {
  231. // Negative is disabled, which in limiter land is spelled zero
  232. if opts.RawMaxCIRequestKiB < 0 {
  233. return 0
  234. }
  235. if opts.RawMaxCIRequestKiB == 0 {
  236. // The default is 256 MiB
  237. return 256 * 1024 // KiB
  238. }
  239. // We can't really do less than a couple of concurrent blocks or we'll
  240. // pretty much stall completely. Check that an explicit value is large
  241. // enough.
  242. const minAllowed = 2 * protocol.MaxBlockSize / 1024
  243. if opts.RawMaxCIRequestKiB < minAllowed {
  244. return minAllowed
  245. }
  246. // Roll with it.
  247. return opts.RawMaxCIRequestKiB
  248. }
  249. func (opts OptionsConfiguration) AutoUpgradeEnabled() bool {
  250. return opts.AutoUpgradeIntervalH > 0
  251. }
  252. func (opts OptionsConfiguration) FeatureFlag(name string) bool {
  253. return slices.Contains(opts.FeatureFlags, name)
  254. }
  255. // LowestConnectionLimit is the lower of ConnectionLimitEnough or
  256. // ConnectionLimitMax, or whichever of them is actually set if only one of
  257. // them is set. It's the point where we should stop dialing.
  258. func (opts OptionsConfiguration) LowestConnectionLimit() int {
  259. limit := opts.ConnectionLimitEnough
  260. if limit == 0 || (opts.ConnectionLimitMax != 0 && opts.ConnectionLimitMax < limit) {
  261. // It doesn't really make sense to set Max lower than Enough but
  262. // someone might do it while experimenting and it's easy for us to
  263. // do the right thing.
  264. limit = opts.ConnectionLimitMax
  265. }
  266. return limit
  267. }