service.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // Copyright (C) 2015 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 nat
  7. import (
  8. "context"
  9. "fmt"
  10. "hash/fnv"
  11. "math/rand"
  12. "net"
  13. "slices"
  14. stdsync "sync"
  15. "time"
  16. "github.com/syncthing/syncthing/lib/config"
  17. "github.com/syncthing/syncthing/lib/protocol"
  18. "github.com/syncthing/syncthing/lib/sync"
  19. )
  20. // Service runs a loop for discovery of IGDs (Internet Gateway Devices) and
  21. // setup/renewal of a port mapping.
  22. type Service struct {
  23. id protocol.DeviceID
  24. cfg config.Wrapper
  25. processScheduled chan struct{}
  26. mappings []*Mapping
  27. enabled bool
  28. mut sync.RWMutex
  29. }
  30. func NewService(id protocol.DeviceID, cfg config.Wrapper) *Service {
  31. s := &Service{
  32. id: id,
  33. cfg: cfg,
  34. processScheduled: make(chan struct{}, 1),
  35. mut: sync.NewRWMutex(),
  36. }
  37. cfgCopy := cfg.RawCopy()
  38. s.CommitConfiguration(cfgCopy, cfgCopy)
  39. return s
  40. }
  41. func (s *Service) CommitConfiguration(_, to config.Configuration) bool {
  42. s.mut.Lock()
  43. if !s.enabled && to.Options.NATEnabled {
  44. l.Debugln("Starting NAT service")
  45. s.enabled = true
  46. s.scheduleProcess()
  47. } else if s.enabled && !to.Options.NATEnabled {
  48. l.Debugln("Stopping NAT service")
  49. s.enabled = false
  50. }
  51. s.mut.Unlock()
  52. return true
  53. }
  54. func (s *Service) Serve(ctx context.Context) error {
  55. s.cfg.Subscribe(s)
  56. defer s.cfg.Unsubscribe(s)
  57. announce := stdsync.Once{}
  58. timer := time.NewTimer(0)
  59. for {
  60. select {
  61. case <-timer.C:
  62. case <-s.processScheduled:
  63. if !timer.Stop() {
  64. select {
  65. case <-timer.C:
  66. default:
  67. }
  68. }
  69. case <-ctx.Done():
  70. timer.Stop()
  71. s.mut.RLock()
  72. for _, mapping := range s.mappings {
  73. mapping.clearAddresses()
  74. }
  75. s.mut.RUnlock()
  76. return ctx.Err()
  77. }
  78. s.mut.RLock()
  79. enabled := s.enabled
  80. s.mut.RUnlock()
  81. if !enabled {
  82. continue
  83. }
  84. found, renewIn := s.process(ctx)
  85. timer.Reset(renewIn)
  86. if found != -1 {
  87. announce.Do(func() {
  88. suffix := "s"
  89. if found == 1 {
  90. suffix = ""
  91. }
  92. l.Infoln("Detected", found, "NAT service"+suffix)
  93. })
  94. }
  95. }
  96. }
  97. func (s *Service) process(ctx context.Context) (int, time.Duration) {
  98. // toRenew are mappings which are due for renewal
  99. // toUpdate are the remaining mappings, which will only be updated if one of
  100. // the old IGDs has gone away, or a new IGD has appeared, but only if we
  101. // actually need to perform a renewal.
  102. var toRenew, toUpdate []*Mapping
  103. renewIn := time.Duration(s.cfg.Options().NATRenewalM) * time.Minute
  104. if renewIn == 0 {
  105. // We always want to do renewal so lets just pick a nice sane number.
  106. renewIn = 30 * time.Minute
  107. }
  108. s.mut.RLock()
  109. for _, mapping := range s.mappings {
  110. mapping.mut.RLock()
  111. expires := mapping.expires
  112. mapping.mut.RUnlock()
  113. if expires.Before(time.Now()) {
  114. toRenew = append(toRenew, mapping)
  115. } else {
  116. toUpdate = append(toUpdate, mapping)
  117. mappingRenewIn := time.Until(expires)
  118. if mappingRenewIn < renewIn {
  119. renewIn = mappingRenewIn
  120. }
  121. }
  122. }
  123. s.mut.RUnlock()
  124. // Don't do anything, unless we really need to renew
  125. if len(toRenew) == 0 {
  126. return -1, renewIn
  127. }
  128. nats := discoverAll(ctx, time.Duration(s.cfg.Options().NATRenewalM)*time.Minute, time.Duration(s.cfg.Options().NATTimeoutS)*time.Second)
  129. for _, mapping := range toRenew {
  130. s.updateMapping(ctx, mapping, nats, true)
  131. }
  132. for _, mapping := range toUpdate {
  133. s.updateMapping(ctx, mapping, nats, false)
  134. }
  135. return len(nats), renewIn
  136. }
  137. func (s *Service) scheduleProcess() {
  138. select {
  139. case s.processScheduled <- struct{}{}: // 1-buffered
  140. default:
  141. }
  142. }
  143. func (s *Service) NewMapping(protocol Protocol, ipVersion IPVersion, ip net.IP, port int) *Mapping {
  144. mapping := &Mapping{
  145. protocol: protocol,
  146. address: Address{
  147. IP: ip,
  148. Port: port,
  149. },
  150. extAddresses: make(map[string][]Address),
  151. mut: sync.NewRWMutex(),
  152. ipVersion: ipVersion,
  153. }
  154. s.mut.Lock()
  155. s.mappings = append(s.mappings, mapping)
  156. s.mut.Unlock()
  157. s.scheduleProcess()
  158. return mapping
  159. }
  160. // RemoveMapping does not actually remove the mapping from the IGD, it just
  161. // internally removes it which stops renewing the mapping. Also, it clears any
  162. // existing mapped addresses from the mapping, which as a result should cause
  163. // discovery to reannounce the new addresses.
  164. func (s *Service) RemoveMapping(mapping *Mapping) {
  165. s.mut.Lock()
  166. defer s.mut.Unlock()
  167. for i, existing := range s.mappings {
  168. if existing == mapping {
  169. mapping.clearAddresses()
  170. last := len(s.mappings) - 1
  171. s.mappings[i] = s.mappings[last]
  172. s.mappings[last] = nil
  173. s.mappings = s.mappings[:last]
  174. return
  175. }
  176. }
  177. }
  178. // updateMapping compares the addresses of the existing mapping versus the natds
  179. // discovered, and removes any addresses of natds that do not exist, or tries to
  180. // acquire mappings for natds which the mapping was unaware of before.
  181. // Optionally takes renew flag which indicates whether or not we should renew
  182. // mappings with existing natds
  183. func (s *Service) updateMapping(ctx context.Context, mapping *Mapping, nats map[string]Device, renew bool) {
  184. renewalTime := time.Duration(s.cfg.Options().NATRenewalM) * time.Minute
  185. mapping.mut.Lock()
  186. mapping.expires = time.Now().Add(renewalTime)
  187. change := s.verifyExistingLocked(ctx, mapping, nats, renew)
  188. add := s.acquireNewLocked(ctx, mapping, nats)
  189. mapping.mut.Unlock()
  190. if change || add {
  191. mapping.notify()
  192. }
  193. }
  194. func (s *Service) verifyExistingLocked(ctx context.Context, mapping *Mapping, nats map[string]Device, renew bool) (change bool) {
  195. leaseTime := time.Duration(s.cfg.Options().NATLeaseM) * time.Minute
  196. for id, extAddrs := range mapping.extAddresses {
  197. select {
  198. case <-ctx.Done():
  199. return false
  200. default:
  201. }
  202. if nat, ok := nats[id]; !ok || len(extAddrs) == 0 {
  203. // Delete addresses for NATDevice's that do not exist anymore
  204. mapping.removeAddressLocked(id)
  205. change = true
  206. continue
  207. } else if renew {
  208. // Only perform renewals on the nat's that have the right local IP
  209. // address. For IPv6 the IP addresses are discovered by the service itself,
  210. // so this check is skipped.
  211. localIP := nat.GetLocalIPv4Address()
  212. if !mapping.validGateway(localIP) && nat.SupportsIPVersion(IPv4Only) {
  213. l.Debugf("Skipping %s for %s because of IP mismatch. %s != %s", id, mapping, mapping.address.IP, localIP)
  214. continue
  215. }
  216. if !nat.SupportsIPVersion(mapping.ipVersion) {
  217. l.Debugf("Skipping renew on gateway %s because it doesn't match the listener address family", nat.ID())
  218. continue
  219. }
  220. l.Debugf("Renewing %s -> %v open port on %s", mapping, extAddrs, id)
  221. // extAddrs either contains one IPv4 address, or possibly several
  222. // IPv6 addresses all using the same port. Therefore the first
  223. // entry always has the external port.
  224. responseAddrs, err := s.tryNATDevice(ctx, nat, mapping.address, extAddrs[0].Port, leaseTime)
  225. if err != nil {
  226. l.Debugf("Failed to renew %s -> %v open port on %s", mapping, extAddrs, id)
  227. mapping.removeAddressLocked(id)
  228. change = true
  229. continue
  230. }
  231. l.Debugf("Renewed %s -> %v open port on %s", mapping, extAddrs, id)
  232. // We shouldn't rely on the order in which the addresses are returned.
  233. // Therefore, we test for set equality and report change if there is any difference.
  234. if !addrSetsEqual(responseAddrs, extAddrs) {
  235. mapping.setAddressLocked(id, responseAddrs)
  236. change = true
  237. }
  238. }
  239. }
  240. return change
  241. }
  242. func (s *Service) acquireNewLocked(ctx context.Context, mapping *Mapping, nats map[string]Device) (change bool) {
  243. leaseTime := time.Duration(s.cfg.Options().NATLeaseM) * time.Minute
  244. addrMap := mapping.extAddresses
  245. for id, nat := range nats {
  246. select {
  247. case <-ctx.Done():
  248. return false
  249. default:
  250. }
  251. if _, ok := addrMap[id]; ok {
  252. continue
  253. }
  254. // Only perform mappings on the nat's that have the right local IP
  255. // address
  256. localIP := nat.GetLocalIPv4Address()
  257. if !mapping.validGateway(localIP) && nat.SupportsIPVersion(IPv4Only) {
  258. l.Debugf("Skipping %s for %s because of IP mismatch. %s != %s", id, mapping, mapping.address.IP, localIP)
  259. continue
  260. }
  261. l.Debugf("Trying to open port %s on %s", mapping, id)
  262. if !nat.SupportsIPVersion(mapping.ipVersion) {
  263. l.Debugf("Skipping firewall traversal on gateway %s because it doesn't match the listener address family", nat.ID())
  264. continue
  265. }
  266. addrs, err := s.tryNATDevice(ctx, nat, mapping.address, 0, leaseTime)
  267. if err != nil {
  268. l.Debugf("Failed to acquire %s open port on %s", mapping, id)
  269. continue
  270. }
  271. l.Debugf("Opened port %s -> %v on %s", mapping, addrs, id)
  272. mapping.setAddressLocked(id, addrs)
  273. change = true
  274. }
  275. return change
  276. }
  277. // tryNATDevice tries to acquire a port mapping for the given internal address to
  278. // the given external port. If external port is 0, picks a pseudo-random port.
  279. func (s *Service) tryNATDevice(ctx context.Context, natd Device, intAddr Address, extPort int, leaseTime time.Duration) ([]Address, error) {
  280. var err error
  281. var port int
  282. // For IPv6, we just try to create the pinhole. If it fails, nothing can be done (probably no IGDv2 support).
  283. // If it already exists, the relevant UPnP standard requires that the gateway recognizes this and updates the lease time.
  284. // Since we usually have a global unicast IPv6 address so no conflicting mappings, we just request the port we're running on
  285. if natd.SupportsIPVersion(IPv6Only) {
  286. ipaddrs, err := natd.AddPinhole(ctx, TCP, intAddr, leaseTime)
  287. var addrs []Address
  288. for _, ipaddr := range ipaddrs {
  289. addrs = append(addrs, Address{
  290. ipaddr,
  291. intAddr.Port,
  292. })
  293. }
  294. if err != nil {
  295. l.Debugln("Error extending lease on", natd.ID(), err)
  296. }
  297. return addrs, err
  298. }
  299. // Generate a predictable random which is based on device ID + local port + hash of the device ID
  300. // number so that the ports we'd try to acquire for the mapping would always be the same for the
  301. // same device trying to get the same internal port.
  302. predictableRand := rand.New(rand.NewSource(int64(s.id.Short()) + int64(intAddr.Port) + hash(natd.ID())))
  303. if extPort != 0 {
  304. // First try renewing our existing mapping, if we have one.
  305. name := fmt.Sprintf("syncthing-%d", extPort)
  306. port, err = natd.AddPortMapping(ctx, TCP, intAddr.Port, extPort, name, leaseTime)
  307. if err == nil {
  308. extPort = port
  309. goto findIP
  310. }
  311. l.Debugln("Error extending lease on", natd.ID(), err)
  312. }
  313. for i := 0; i < 10; i++ {
  314. select {
  315. case <-ctx.Done():
  316. return []Address{}, ctx.Err()
  317. default:
  318. }
  319. // Then try up to ten random ports.
  320. extPort = 1024 + predictableRand.Intn(65535-1024)
  321. name := fmt.Sprintf("syncthing-%d", extPort)
  322. port, err = natd.AddPortMapping(ctx, TCP, intAddr.Port, extPort, name, leaseTime)
  323. if err == nil {
  324. extPort = port
  325. goto findIP
  326. }
  327. l.Debugf("Error getting new lease on %s: %s", natd.ID(), err)
  328. }
  329. return nil, err
  330. findIP:
  331. ip, err := natd.GetExternalIPv4Address(ctx)
  332. if err != nil {
  333. l.Debugf("Error getting external ip on %s: %s", natd.ID(), err)
  334. ip = nil
  335. }
  336. return []Address{
  337. {
  338. IP: ip,
  339. Port: extPort,
  340. },
  341. }, nil
  342. }
  343. func (s *Service) String() string {
  344. return fmt.Sprintf("nat.Service@%p", s)
  345. }
  346. func hash(input string) int64 {
  347. h := fnv.New64a()
  348. h.Write([]byte(input))
  349. return int64(h.Sum64())
  350. }
  351. func addrSetsEqual(a []Address, b []Address) bool {
  352. if len(a) != len(b) {
  353. return false
  354. }
  355. for _, v := range a {
  356. if !slices.ContainsFunc(b, v.Equal) {
  357. return false
  358. }
  359. }
  360. return true
  361. }