portmapper.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package inproxy
  20. import (
  21. "context"
  22. "fmt"
  23. "sync"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  26. "tailscale.com/net/portmapper"
  27. "tailscale.com/util/clientmetric"
  28. )
  29. // initPortMapper resets port mapping metrics state associated with the
  30. // current network when the network changes, as indicated by
  31. // WebRTCDialCoordinator.NetworkID. initPortMapper also configures the port
  32. // mapping routines to use WebRTCDialCoordinator.BindToDevice. Varying
  33. // WebRTCDialCoordinator.BindToDevice between dials in a single process is not
  34. // supported.
  35. func initPortMapper(coordinator WebRTCDialCoordinator) {
  36. // It's safe for multiple, concurrent client dials to call
  37. // resetRespondingPortMappingTypes: as long as the network ID does not
  38. // change, calls won't clear any valid port mapping type metrics that
  39. // were just recorded.
  40. resetRespondingPortMappingTypes(coordinator.NetworkID())
  41. // WebRTCDialCoordinator.BindToDevice is set as a global variable in
  42. // tailscale.com/net/portmapper. It's safe to repeatedly call
  43. // setPortMapperBindToDevice here, under the assumption that
  44. // WebRTCDialCoordinator.BindToDevice is the same single, static function
  45. // for all dials. This assumption is true for Psiphon.
  46. setPortMapperBindToDevice(coordinator)
  47. }
  48. // portMapper represents a UDP port mapping from a local port to an external,
  49. // publicly addressable IP and port. Port mapping is implemented using
  50. // tailscale.com/net/portmapper, which probes the local network and gateway
  51. // for UPnP-IGD, NAT-PMP, and PCP port mapping capabilities.
  52. type portMapper struct {
  53. havePortMappingOnce sync.Once
  54. portMappingAddress chan string
  55. client *portmapper.Client
  56. }
  57. // newPortMapper initializes a new port mapper, configured to map to the
  58. // specified localPort. newPortMapper does not initiate any network
  59. // operations (it's safe to call when DisablePortMapping is set).
  60. func newPortMapper(
  61. logger common.Logger,
  62. localPort int) *portMapper {
  63. portMappingLogger := func(format string, args ...any) {
  64. logger.WithTrace().Info("port mapping: " + fmt.Sprintf(format, args))
  65. }
  66. p := &portMapper{
  67. portMappingAddress: make(chan string, 1),
  68. }
  69. // This code assumes assumes tailscale NewClient call does only
  70. // initialization; this is the case as of tailscale.com/net/portmapper
  71. // v1.36.2.
  72. //
  73. // This code further assumes that the onChanged callback passed to
  74. // NewClient will not be invoked until after the
  75. // GetCachedMappingOrStartCreatingOne call in portMapper.start; and so
  76. // the p.client reference within callback will be valid.
  77. client := portmapper.NewClient(portMappingLogger, nil, nil, func() {
  78. p.havePortMappingOnce.Do(func() {
  79. address, ok := p.client.GetCachedMappingOrStartCreatingOne()
  80. if ok {
  81. // With sync.Once and a buffer size of 1, this send won't block.
  82. p.portMappingAddress <- address.String()
  83. } else {
  84. // This is not an expected case; there should be a port
  85. // mapping when NewClient is invoked.
  86. //
  87. // TODO: deliver "" to the channel? Otherwise, receiving on
  88. // portMapper.portMappingExternalAddress will hang, or block
  89. // until a context is done.
  90. portMappingLogger("unexpected missing port mapping")
  91. }
  92. })
  93. })
  94. p.client = client
  95. p.client.SetLocalPort(uint16(localPort))
  96. return p
  97. }
  98. // start initiates the port mapping attempt.
  99. func (p *portMapper) start() {
  100. _, _ = p.client.GetCachedMappingOrStartCreatingOne()
  101. }
  102. // portMappingExternalAddress returns a channel which recieves a successful
  103. // port mapping external address, if any.
  104. func (p *portMapper) portMappingExternalAddress() <-chan string {
  105. return p.portMappingAddress
  106. }
  107. // close releases the port mapping
  108. func (p *portMapper) close() error {
  109. return errors.Trace(p.client.Close())
  110. }
  111. // probePortMapping discovers and reports which port mapping protocols are
  112. // supported on this network. probePortMapping does not establish a port mapping.
  113. //
  114. // It is intended that in-proxies amake a blocking call to probePortMapping on
  115. // start up (and after a network change) in order to report fresh port
  116. // mapping type metrics, for matching optimization in the ProxyAnnounce
  117. // request. Clients don't incur the delay of a probe call -- which produces
  118. // no port mapping -- and instead opportunistically grab port mapping type
  119. // metrics via getRespondingPortMappingTypes.
  120. func probePortMapping(
  121. ctx context.Context,
  122. logger common.Logger) (PortMappingTypes, error) {
  123. portMappingLogger := func(format string, args ...any) {
  124. logger.WithTrace().Info("port mapping probe: " + fmt.Sprintf(format, args))
  125. }
  126. client := portmapper.NewClient(portMappingLogger, nil, nil, nil)
  127. defer client.Close()
  128. result, err := client.Probe(ctx)
  129. if err != nil {
  130. return nil, errors.Trace(err)
  131. }
  132. portMappingTypes := PortMappingTypes{}
  133. if result.UPnP {
  134. portMappingTypes = append(portMappingTypes, PortMappingTypeUPnP)
  135. }
  136. if result.PMP {
  137. portMappingTypes = append(portMappingTypes, PortMappingTypePMP)
  138. }
  139. if result.PCP {
  140. portMappingTypes = append(portMappingTypes, PortMappingTypePCP)
  141. }
  142. // An empty lists means discovery is needed or the available port mappings
  143. // are unknown; a list with None indicates that a probe returned no
  144. // supported port mapping types.
  145. if len(portMappingTypes) == 0 {
  146. portMappingTypes = append(portMappingTypes, PortMappingTypeNone)
  147. }
  148. return portMappingTypes, nil
  149. }
  150. var respondingPortMappingTypesMutex sync.Mutex
  151. var respondingPortMappingTypesNetworkID string
  152. // resetRespondingPortMappingTypes clears tailscale.com/net/portmapper global
  153. // metrics fields which indicate which port mapping types are responding on
  154. // the current network. These metrics should be cleared whenever the current
  155. // network changes, as indicated by networkID.
  156. //
  157. // Limitations: there may be edge conditions where a
  158. // tailscale.com/net/portmapper client logs metrics concurrent to
  159. // resetRespondingPortMappingTypes being called with a new networkID. If
  160. // incorrect port mapping type metrics are supported, the Broker may log
  161. // incorrect statistics. However, Broker client/in-proxy matching is based on
  162. // actually established port mappings.
  163. func resetRespondingPortMappingTypes(networkID string) {
  164. respondingPortMappingTypesMutex.Lock()
  165. defer respondingPortMappingTypesMutex.Unlock()
  166. if respondingPortMappingTypesNetworkID != networkID {
  167. // Iterating over all metric fields appears to be the only API available.
  168. for _, metric := range clientmetric.Metrics() {
  169. switch metric.Name() {
  170. case "portmap_upnp_ok", "portmap_pmp_ok", "portmap_pcp_ok":
  171. metric.Set(0)
  172. }
  173. }
  174. respondingPortMappingTypesNetworkID = networkID
  175. }
  176. }
  177. // getRespondingPortMappingTypes returns the port mapping types that responded
  178. // during recent portMapper.start invocations as well as probePortMapping
  179. // invocations. The returned list is used for reporting metrics. See
  180. // resetRespondingPortMappingTypes for considerations due to accessing
  181. // tailscale.com/net/portmapper global metrics fields.
  182. //
  183. // To avoid delays, we do not run probePortMapping for regular client dials,
  184. // and so instead use this tailscale.com/net/portmapper metrics field
  185. // approach.
  186. //
  187. // Limitations: the return value represents all port mapping types that
  188. // responded in this session, since the last network change
  189. // (resetRespondingPortMappingTypes call); and do not indicate which of
  190. // several port mapping types may have been used for a particular dial.
  191. func getRespondingPortMappingTypes(networkID string) PortMappingTypes {
  192. respondingPortMappingTypesMutex.Lock()
  193. defer respondingPortMappingTypesMutex.Unlock()
  194. portMappingTypes := PortMappingTypes{}
  195. if respondingPortMappingTypesNetworkID != networkID {
  196. // The network changed since the last resetRespondingPortMappingTypes
  197. // call, and resetRespondingPortMappingTypes has not yet been called
  198. // again. Ignore the current metrics.
  199. return portMappingTypes
  200. }
  201. // Iterating over all metric fields appears to be the only API available.
  202. for _, metric := range clientmetric.Metrics() {
  203. if metric.Name() == "portmap_upnp_ok" && metric.Value() > 1 {
  204. portMappingTypes = append(portMappingTypes, PortMappingTypeUPnP)
  205. }
  206. if metric.Name() == "portmap_pmp_ok" && metric.Value() > 1 {
  207. portMappingTypes = append(portMappingTypes, PortMappingTypePMP)
  208. }
  209. if metric.Name() == "portmap_pcp_ok" && metric.Value() > 1 {
  210. portMappingTypes = append(portMappingTypes, PortMappingTypePCP)
  211. }
  212. }
  213. return portMappingTypes
  214. }