stun.go 7.6 KB

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