stun.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // Copyright (C) 2019 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 stun
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "net"
  12. "time"
  13. "github.com/ccding/go-stun/stun"
  14. "github.com/syncthing/syncthing/lib/config"
  15. "github.com/syncthing/syncthing/lib/svcutil"
  16. )
  17. const stunRetryInterval = 5 * time.Minute
  18. type (
  19. Host = stun.Host
  20. NATType = stun.NATType
  21. )
  22. // NAT types.
  23. const (
  24. NATError = stun.NATError
  25. NATUnknown = stun.NATUnknown
  26. NATNone = stun.NATNone
  27. NATBlocked = stun.NATBlocked
  28. NATFull = stun.NATFull
  29. NATSymmetric = stun.NATSymmetric
  30. NATRestricted = stun.NATRestricted
  31. NATPortRestricted = stun.NATPortRestricted
  32. NATSymmetricUDPFirewall = stun.NATSymmetricUDPFirewall
  33. )
  34. var errNotPunchable = errors.New("not punchable")
  35. type Subscriber interface {
  36. OnNATTypeChanged(natType NATType)
  37. OnExternalAddressChanged(address *Host, via string)
  38. }
  39. type Service struct {
  40. name string
  41. cfg config.Wrapper
  42. subscriber Subscriber
  43. client *stun.Client
  44. lastWriter LastWriter
  45. natType NATType
  46. addr *Host
  47. }
  48. type LastWriter interface {
  49. LastWrite() time.Time
  50. }
  51. func New(cfg config.Wrapper, subscriber Subscriber, conn net.PacketConn, lastWriter LastWriter) *Service {
  52. // Construct the client to use the stun conn
  53. client := stun.NewClientWithConnection(conn)
  54. client.SetSoftwareName("") // Explicitly unset this, seems to freak some servers out.
  55. // Return the service and the other conn to the client
  56. name := "Stun@"
  57. if local := conn.LocalAddr(); local != nil {
  58. name += local.Network() + "://" + local.String()
  59. } else {
  60. name += "unknown"
  61. }
  62. s := &Service{
  63. name: name,
  64. cfg: cfg,
  65. subscriber: subscriber,
  66. client: client,
  67. lastWriter: lastWriter,
  68. natType: NATUnknown,
  69. addr: nil,
  70. }
  71. return s
  72. }
  73. func (s *Service) Serve(ctx context.Context) error {
  74. defer func() {
  75. s.setNATType(NATUnknown)
  76. s.setExternalAddress(nil, "")
  77. }()
  78. timer := time.NewTimer(time.Millisecond)
  79. for {
  80. disabled:
  81. select {
  82. case <-ctx.Done():
  83. return ctx.Err()
  84. case <-timer.C:
  85. }
  86. if s.cfg.Options().IsStunDisabled() {
  87. timer.Reset(time.Second)
  88. continue
  89. }
  90. l.Debugf("Starting stun for %s", s)
  91. for _, addr := range s.cfg.Options().StunServers() {
  92. // This blocks until we hit an exit condition or there are
  93. // issues with the STUN server.
  94. if err := s.runStunForServer(ctx, addr); errors.Is(err, errNotPunchable) {
  95. break // we will sleep for a while
  96. }
  97. // Have we been asked to stop?
  98. select {
  99. case <-ctx.Done():
  100. return ctx.Err()
  101. default:
  102. }
  103. // Are we disabled?
  104. if s.cfg.Options().IsStunDisabled() {
  105. l.Infoln("STUN disabled")
  106. s.setNATType(NATUnknown)
  107. s.setExternalAddress(nil, "")
  108. goto disabled
  109. }
  110. }
  111. // We failed to contact all provided stun servers or the nat is not punchable.
  112. // Chillout for a while.
  113. timer.Reset(stunRetryInterval)
  114. }
  115. }
  116. func (s *Service) runStunForServer(ctx context.Context, addr string) error {
  117. l.Debugf("Running stun for %s via %s", s, addr)
  118. // Resolve the address, so that in case the server advertises two
  119. // IPs, we always hit the same one, as otherwise, the mapping might
  120. // expire as we hit the other address, and cause us to flip flop
  121. // between servers/external addresses, as a result flooding discovery
  122. // servers.
  123. udpAddr, err := net.ResolveUDPAddr("udp", addr)
  124. if err != nil {
  125. l.Debugf("%s stun addr resolution on %s: %s", s, addr, err)
  126. return err
  127. }
  128. s.client.SetServerAddr(udpAddr.String())
  129. var natType stun.NATType
  130. var extAddr *stun.Host
  131. err = svcutil.CallWithContext(ctx, func() error {
  132. natType, extAddr, err = s.client.Discover()
  133. return err
  134. })
  135. if err != nil {
  136. l.Debugf("%s stun discovery on %s: %v", s, addr, err)
  137. return err
  138. } else if extAddr == nil {
  139. l.Debugf("%s stun discovery on %s resulted in no address", s, addr)
  140. return fmt.Errorf("%s: no address", addr)
  141. }
  142. // The stun server is most likely borked, try another one.
  143. if natType == NATError || natType == NATUnknown || natType == NATBlocked {
  144. l.Debugf("%s stun discovery on %s resolved to %s", s, addr, natType)
  145. return fmt.Errorf("%s: bad result: %v", addr, natType)
  146. }
  147. s.setNATType(natType)
  148. l.Debugf("%s detected NAT type: %s via %s", s, natType, addr)
  149. // We can't punch through this one, so no point doing keepalives
  150. // and such, just let the caller check the nat type and work it out themselves.
  151. if !s.isCurrentNATTypePunchable() {
  152. l.Debugf("%s cannot punch %s, skipping", s, natType)
  153. return errNotPunchable
  154. }
  155. s.setExternalAddress(extAddr, addr)
  156. return s.stunKeepAlive(ctx, addr, extAddr)
  157. }
  158. func (s *Service) stunKeepAlive(ctx context.Context, addr string, extAddr *Host) error {
  159. var err error
  160. nextSleep := time.Duration(s.cfg.Options().StunKeepaliveStartS) * time.Second
  161. l.Debugf("%s starting stun keepalive via %s, next sleep %s", s, addr, nextSleep)
  162. var ourLastWrite time.Time
  163. for {
  164. if areDifferent(s.addr, extAddr) {
  165. // If the port has changed (addresses are not equal but the hosts are equal),
  166. // we're probably spending too much time between keepalives, reduce the sleep.
  167. if s.addr != nil && extAddr != nil && s.addr.IP() == extAddr.IP() {
  168. nextSleep /= 2
  169. l.Debugf("%s stun port change (%s to %s), next sleep %s", s, s.addr.TransportAddr(), extAddr.TransportAddr(), nextSleep)
  170. }
  171. s.setExternalAddress(extAddr, addr)
  172. // The stun server is probably stuffed, we've gone beyond min timeout, yet the address keeps changing.
  173. minSleep := time.Duration(s.cfg.Options().StunKeepaliveMinS) * time.Second
  174. if nextSleep < minSleep {
  175. l.Debugf("%s keepalive aborting, sleep below min: %s < %s", s, nextSleep, minSleep)
  176. return fmt.Errorf("unreasonably low keepalive: %v", minSleep)
  177. }
  178. }
  179. // Adjust the keepalives to fire only nextSleep after last write.
  180. lastWrite := ourLastWrite
  181. if quicLastWrite := s.lastWriter.LastWrite(); quicLastWrite.After(lastWrite) {
  182. lastWrite = quicLastWrite
  183. }
  184. minSleep := time.Duration(s.cfg.Options().StunKeepaliveMinS) * time.Second
  185. if nextSleep < minSleep {
  186. nextSleep = minSleep
  187. }
  188. tryLater:
  189. sleepFor := nextSleep
  190. timeUntilNextKeepalive := time.Until(lastWrite.Add(sleepFor))
  191. if timeUntilNextKeepalive > 0 {
  192. sleepFor = timeUntilNextKeepalive
  193. }
  194. l.Debugf("%s stun sleeping for %s", s, sleepFor)
  195. select {
  196. case <-time.After(sleepFor):
  197. case <-ctx.Done():
  198. l.Debugf("%s stopping, aborting stun", s)
  199. return ctx.Err()
  200. }
  201. if s.cfg.Options().IsStunDisabled() {
  202. // Disabled, give up
  203. l.Debugf("%s disabled, aborting stun ", s)
  204. return errors.New("disabled")
  205. }
  206. // Check if any writes happened while we were sleeping, if they did, sleep again
  207. lastWrite = s.lastWriter.LastWrite()
  208. if gap := time.Since(lastWrite); gap < nextSleep {
  209. l.Debugf("%s stun last write gap less than next sleep: %s < %s. Will try later", s, gap, nextSleep)
  210. goto tryLater
  211. }
  212. l.Debugf("%s stun keepalive", s)
  213. extAddr, err = s.client.Keepalive()
  214. if err != nil {
  215. l.Debugf("%s stun keepalive on %s: %s (%v)", s, addr, err, extAddr)
  216. return err
  217. }
  218. ourLastWrite = time.Now()
  219. }
  220. }
  221. func (s *Service) setNATType(natType NATType) {
  222. if natType != s.natType {
  223. l.Debugf("Notifying %s of NAT type change: %s", s.subscriber, natType)
  224. s.subscriber.OnNATTypeChanged(natType)
  225. }
  226. s.natType = natType
  227. }
  228. func (s *Service) setExternalAddress(addr *Host, via string) {
  229. if areDifferent(s.addr, addr) {
  230. l.Debugf("Notifying %s of address change: %s via %s", s.subscriber, addr, via)
  231. s.subscriber.OnExternalAddressChanged(addr, via)
  232. }
  233. s.addr = addr
  234. }
  235. func (s *Service) String() string {
  236. return s.name
  237. }
  238. func (s *Service) isCurrentNATTypePunchable() bool {
  239. return s.natType == NATNone || s.natType == NATPortRestricted || s.natType == NATRestricted || s.natType == NATFull || s.natType == NATSymmetricUDPFirewall
  240. }
  241. func areDifferent(first, second *Host) bool {
  242. if (first == nil) != (second == nil) {
  243. return true
  244. }
  245. if first != nil {
  246. return first.TransportAddr() != second.TransportAddr()
  247. }
  248. return false
  249. }