pmp.go 3.4 KB

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