pmp.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. // Copyright (C) 2016 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 pmp
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "log/slog"
  12. "net"
  13. "strings"
  14. "time"
  15. natpmp "github.com/jackpal/go-nat-pmp"
  16. "github.com/syncthing/syncthing/lib/nat"
  17. "github.com/syncthing/syncthing/lib/netutil"
  18. "github.com/syncthing/syncthing/lib/osutil"
  19. "github.com/syncthing/syncthing/lib/svcutil"
  20. )
  21. func init() {
  22. nat.Register(Discover)
  23. }
  24. func Discover(ctx context.Context, renewal, timeout time.Duration) []nat.Device {
  25. var ip net.IP
  26. err := svcutil.CallWithContext(ctx, func() error {
  27. var err error
  28. ip, err = netutil.Gateway()
  29. return err
  30. })
  31. if err != nil {
  32. l.Debugln("Failed to discover gateway", err)
  33. return nil
  34. }
  35. if ip == nil || ip.IsUnspecified() {
  36. return nil
  37. }
  38. l.Debugln("Discovered gateway at", ip)
  39. c := natpmp.NewClientWithTimeout(ip, timeout)
  40. // Try contacting the gateway, if it does not respond, assume it does not
  41. // speak NAT-PMP.
  42. err = svcutil.CallWithContext(ctx, func() error {
  43. _, ierr := c.GetExternalAddress()
  44. return ierr
  45. })
  46. if err != nil {
  47. if errors.Is(err, context.Canceled) {
  48. return nil
  49. }
  50. if strings.Contains(err.Error(), "Timed out") {
  51. slog.Debug("Timeout trying to get external address, assume no NAT-PMP available")
  52. return nil
  53. }
  54. }
  55. var localIP net.IP
  56. // Port comes from the natpmp package
  57. timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
  58. defer cancel()
  59. conn, err := (&net.Dialer{}).DialContext(timeoutCtx, "udp", net.JoinHostPort(ip.String(), "5351"))
  60. if err == nil {
  61. conn.Close()
  62. localIP, err = osutil.IPFromAddr(conn.LocalAddr())
  63. if localIP == nil {
  64. l.Debugln("Failed to lookup local IP", err)
  65. }
  66. }
  67. return []nat.Device{&wrapper{
  68. renewal: renewal,
  69. localIP: localIP,
  70. gatewayIP: ip,
  71. client: c,
  72. }}
  73. }
  74. type wrapper struct {
  75. renewal time.Duration
  76. localIP net.IP
  77. gatewayIP net.IP
  78. client *natpmp.Client
  79. }
  80. func (w *wrapper) ID() string {
  81. return fmt.Sprintf("NAT-PMP@%s", w.gatewayIP.String())
  82. }
  83. func (w *wrapper) GetLocalIPv4Address() net.IP {
  84. return w.localIP
  85. }
  86. func (w *wrapper) AddPortMapping(ctx context.Context, protocol nat.Protocol, internalPort, externalPort int, _ string, duration time.Duration) (int, error) {
  87. // NAT-PMP says that if duration is 0, the mapping is actually removed
  88. // Swap the zero with the renewal value, which should make the lease for the
  89. // exact amount of time between the calls.
  90. if duration == 0 {
  91. duration = w.renewal
  92. }
  93. var result *natpmp.AddPortMappingResult
  94. err := svcutil.CallWithContext(ctx, func() error {
  95. var err error
  96. result, err = w.client.AddPortMapping(strings.ToLower(string(protocol)), internalPort, externalPort, int(duration/time.Second))
  97. return err
  98. })
  99. port := 0
  100. if result != nil {
  101. port = int(result.MappedExternalPort)
  102. }
  103. return port, err
  104. }
  105. func (*wrapper) AddPinhole(_ context.Context, _ nat.Protocol, _ nat.Address, _ time.Duration) ([]net.IP, error) {
  106. // NAT-PMP doesn't support pinholes.
  107. return nil, errors.New("adding IPv6 pinholes is unsupported on NAT-PMP")
  108. }
  109. func (*wrapper) SupportsIPVersion(version nat.IPVersion) bool {
  110. // NAT-PMP gateways should always try to create port mappings and not pinholes
  111. // since NAT-PMP doesn't support IPv6.
  112. return version == nat.IPvAny || version == nat.IPv4Only
  113. }
  114. func (w *wrapper) GetExternalIPv4Address(ctx context.Context) (net.IP, error) {
  115. var result *natpmp.GetExternalAddressResult
  116. err := svcutil.CallWithContext(ctx, func() error {
  117. var err error
  118. result, err = w.client.GetExternalAddress()
  119. return err
  120. })
  121. ip := net.IPv4zero
  122. if result != nil {
  123. ip = net.IPv4(
  124. result.ExternalIPAddress[0],
  125. result.ExternalIPAddress[1],
  126. result.ExternalIPAddress[2],
  127. result.ExternalIPAddress[3],
  128. )
  129. }
  130. return ip, err
  131. }