stun.go 8.9 KB

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