service.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. "fmt"
  9. "hash/fnv"
  10. "math/rand"
  11. "net"
  12. stdsync "sync"
  13. "time"
  14. "github.com/thejerf/suture"
  15. "github.com/syncthing/syncthing/lib/config"
  16. "github.com/syncthing/syncthing/lib/protocol"
  17. "github.com/syncthing/syncthing/lib/sync"
  18. "github.com/syncthing/syncthing/lib/util"
  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. suture.Service
  24. id protocol.DeviceID
  25. cfg config.Wrapper
  26. mappings []*Mapping
  27. timer *time.Timer
  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. timer: time.NewTimer(0),
  35. mut: sync.NewRWMutex(),
  36. }
  37. s.Service = util.AsService(s.serve)
  38. return s
  39. }
  40. func (s *Service) serve(stop chan struct{}) {
  41. announce := stdsync.Once{}
  42. s.mut.Lock()
  43. s.timer.Reset(0)
  44. s.mut.Unlock()
  45. for {
  46. select {
  47. case <-s.timer.C:
  48. if found := s.process(stop); found != -1 {
  49. announce.Do(func() {
  50. suffix := "s"
  51. if found == 1 {
  52. suffix = ""
  53. }
  54. l.Infoln("Detected", found, "NAT service"+suffix)
  55. })
  56. }
  57. case <-stop:
  58. s.timer.Stop()
  59. s.mut.RLock()
  60. for _, mapping := range s.mappings {
  61. mapping.clearAddresses()
  62. }
  63. s.mut.RUnlock()
  64. return
  65. }
  66. }
  67. }
  68. func (s *Service) process(stop chan struct{}) int {
  69. // toRenew are mappings which are due for renewal
  70. // toUpdate are the remaining mappings, which will only be updated if one of
  71. // the old IGDs has gone away, or a new IGD has appeared, but only if we
  72. // actually need to perform a renewal.
  73. var toRenew, toUpdate []*Mapping
  74. renewIn := time.Duration(s.cfg.Options().NATRenewalM) * time.Minute
  75. if renewIn == 0 {
  76. // We always want to do renewal so lets just pick a nice sane number.
  77. renewIn = 30 * time.Minute
  78. }
  79. s.mut.RLock()
  80. for _, mapping := range s.mappings {
  81. if mapping.expires.Before(time.Now()) {
  82. toRenew = append(toRenew, mapping)
  83. } else {
  84. toUpdate = append(toUpdate, mapping)
  85. mappingRenewIn := time.Until(mapping.expires)
  86. if mappingRenewIn < renewIn {
  87. renewIn = mappingRenewIn
  88. }
  89. }
  90. }
  91. // Reset the timer while holding the lock, because of the following race:
  92. // T1: process acquires lock
  93. // T1: process checks the mappings and gets next renewal time in 30m
  94. // T2: process releases the lock
  95. // T2: NewMapping acquires the lock
  96. // T2: NewMapping adds mapping
  97. // T2: NewMapping releases the lock
  98. // T2: NewMapping resets timer to 1s
  99. // T1: process resets timer to 30
  100. s.timer.Reset(renewIn)
  101. s.mut.RUnlock()
  102. // Don't do anything, unless we really need to renew
  103. if len(toRenew) == 0 {
  104. return -1
  105. }
  106. nats := discoverAll(time.Duration(s.cfg.Options().NATRenewalM)*time.Minute, time.Duration(s.cfg.Options().NATTimeoutS)*time.Second, stop)
  107. for _, mapping := range toRenew {
  108. s.updateMapping(mapping, nats, true, stop)
  109. }
  110. for _, mapping := range toUpdate {
  111. s.updateMapping(mapping, nats, false, stop)
  112. }
  113. return len(nats)
  114. }
  115. func (s *Service) NewMapping(protocol Protocol, ip net.IP, port int) *Mapping {
  116. mapping := &Mapping{
  117. protocol: protocol,
  118. address: Address{
  119. IP: ip,
  120. Port: port,
  121. },
  122. extAddresses: make(map[string]Address),
  123. mut: sync.NewRWMutex(),
  124. }
  125. s.mut.Lock()
  126. s.mappings = append(s.mappings, mapping)
  127. // Reset the timer while holding the lock, see process() for explanation
  128. s.timer.Reset(time.Second)
  129. s.mut.Unlock()
  130. return mapping
  131. }
  132. // RemoveMapping does not actually remove the mapping from the IGD, it just
  133. // internally removes it which stops renewing the mapping. Also, it clears any
  134. // existing mapped addresses from the mapping, which as a result should cause
  135. // discovery to reannounce the new addresses.
  136. func (s *Service) RemoveMapping(mapping *Mapping) {
  137. s.mut.Lock()
  138. defer s.mut.Unlock()
  139. for i, existing := range s.mappings {
  140. if existing == mapping {
  141. mapping.clearAddresses()
  142. last := len(s.mappings) - 1
  143. s.mappings[i] = s.mappings[last]
  144. s.mappings[last] = nil
  145. s.mappings = s.mappings[:last]
  146. return
  147. }
  148. }
  149. }
  150. // updateMapping compares the addresses of the existing mapping versus the natds
  151. // discovered, and removes any addresses of natds that do not exist, or tries to
  152. // acquire mappings for natds which the mapping was unaware of before.
  153. // Optionally takes renew flag which indicates whether or not we should renew
  154. // mappings with existing natds
  155. func (s *Service) updateMapping(mapping *Mapping, nats map[string]Device, renew bool, stop chan struct{}) {
  156. var added, removed []Address
  157. renewalTime := time.Duration(s.cfg.Options().NATRenewalM) * time.Minute
  158. mapping.expires = time.Now().Add(renewalTime)
  159. newAdded, newRemoved := s.verifyExistingMappings(mapping, nats, renew, stop)
  160. added = append(added, newAdded...)
  161. removed = append(removed, newRemoved...)
  162. newAdded, newRemoved = s.acquireNewMappings(mapping, nats, stop)
  163. added = append(added, newAdded...)
  164. removed = append(removed, newRemoved...)
  165. if len(added) > 0 || len(removed) > 0 {
  166. mapping.notify(added, removed)
  167. }
  168. }
  169. func (s *Service) verifyExistingMappings(mapping *Mapping, nats map[string]Device, renew bool, stop chan struct{}) ([]Address, []Address) {
  170. var added, removed []Address
  171. leaseTime := time.Duration(s.cfg.Options().NATLeaseM) * time.Minute
  172. for id, address := range mapping.addressMap() {
  173. select {
  174. case <-stop:
  175. return nil, nil
  176. default:
  177. }
  178. // Delete addresses for NATDevice's that do not exist anymore
  179. nat, ok := nats[id]
  180. if !ok {
  181. mapping.removeAddress(id)
  182. removed = append(removed, address)
  183. continue
  184. } else if renew {
  185. // Only perform renewals on the nat's that have the right local IP
  186. // address
  187. localIP := nat.GetLocalIPAddress()
  188. if !mapping.validGateway(localIP) {
  189. l.Debugf("Skipping %s for %s because of IP mismatch. %s != %s", id, mapping, mapping.address.IP, localIP)
  190. continue
  191. }
  192. l.Debugf("Renewing %s -> %s mapping on %s", mapping, address, id)
  193. addr, err := s.tryNATDevice(nat, mapping.address.Port, address.Port, leaseTime, stop)
  194. if err != nil {
  195. l.Debugf("Failed to renew %s -> mapping on %s", mapping, address, id)
  196. mapping.removeAddress(id)
  197. removed = append(removed, address)
  198. continue
  199. }
  200. l.Debugf("Renewed %s -> %s mapping on %s", mapping, address, id)
  201. if !addr.Equal(address) {
  202. mapping.removeAddress(id)
  203. mapping.setAddress(id, addr)
  204. removed = append(removed, address)
  205. added = append(added, address)
  206. }
  207. }
  208. }
  209. return added, removed
  210. }
  211. func (s *Service) acquireNewMappings(mapping *Mapping, nats map[string]Device, stop chan struct{}) ([]Address, []Address) {
  212. var added, removed []Address
  213. leaseTime := time.Duration(s.cfg.Options().NATLeaseM) * time.Minute
  214. addrMap := mapping.addressMap()
  215. for id, nat := range nats {
  216. select {
  217. case <-stop:
  218. return nil, nil
  219. default:
  220. }
  221. if _, ok := addrMap[id]; ok {
  222. continue
  223. }
  224. // Only perform mappings on the nat's that have the right local IP
  225. // address
  226. localIP := nat.GetLocalIPAddress()
  227. if !mapping.validGateway(localIP) {
  228. l.Debugf("Skipping %s for %s because of IP mismatch. %s != %s", id, mapping, mapping.address.IP, localIP)
  229. continue
  230. }
  231. l.Debugf("Acquiring %s mapping on %s", mapping, id)
  232. addr, err := s.tryNATDevice(nat, mapping.address.Port, 0, leaseTime, stop)
  233. if err != nil {
  234. l.Debugf("Failed to acquire %s mapping on %s", mapping, id)
  235. continue
  236. }
  237. l.Debugf("Acquired %s -> %s mapping on %s", mapping, addr, id)
  238. mapping.setAddress(id, addr)
  239. added = append(added, addr)
  240. }
  241. return added, removed
  242. }
  243. // tryNATDevice tries to acquire a port mapping for the given internal address to
  244. // the given external port. If external port is 0, picks a pseudo-random port.
  245. func (s *Service) tryNATDevice(natd Device, intPort, extPort int, leaseTime time.Duration, stop chan struct{}) (Address, error) {
  246. var err error
  247. var port int
  248. // Generate a predictable random which is based on device ID + local port + hash of the device ID
  249. // number so that the ports we'd try to acquire for the mapping would always be the same for the
  250. // same device trying to get the same internal port.
  251. predictableRand := rand.New(rand.NewSource(int64(s.id.Short()) + int64(intPort) + hash(natd.ID())))
  252. if extPort != 0 {
  253. // First try renewing our existing mapping, if we have one.
  254. name := fmt.Sprintf("syncthing-%d", extPort)
  255. port, err = natd.AddPortMapping(TCP, intPort, extPort, name, leaseTime)
  256. if err == nil {
  257. extPort = port
  258. goto findIP
  259. }
  260. l.Debugln("Error extending lease on", natd.ID(), err)
  261. }
  262. for i := 0; i < 10; i++ {
  263. select {
  264. case <-stop:
  265. return Address{}, nil
  266. default:
  267. }
  268. // Then try up to ten random ports.
  269. extPort = 1024 + predictableRand.Intn(65535-1024)
  270. name := fmt.Sprintf("syncthing-%d", extPort)
  271. port, err = natd.AddPortMapping(TCP, intPort, extPort, name, leaseTime)
  272. if err == nil {
  273. extPort = port
  274. goto findIP
  275. }
  276. l.Debugln("Error getting new lease on", natd.ID(), err)
  277. }
  278. return Address{}, err
  279. findIP:
  280. ip, err := natd.GetExternalIPAddress()
  281. if err != nil {
  282. l.Debugln("Error getting external ip on", natd.ID(), err)
  283. ip = nil
  284. }
  285. return Address{
  286. IP: ip,
  287. Port: extPort,
  288. }, nil
  289. }
  290. func hash(input string) int64 {
  291. h := fnv.New64a()
  292. h.Write([]byte(input))
  293. return int64(h.Sum64())
  294. }