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. "fmt"
  10. "net"
  11. "strings"
  12. "time"
  13. "github.com/jackpal/gateway"
  14. "github.com/jackpal/go-nat-pmp"
  15. "github.com/pkg/errors"
  16. "github.com/syncthing/syncthing/lib/nat"
  17. "github.com/syncthing/syncthing/lib/util"
  18. )
  19. func init() {
  20. nat.Register(Discover)
  21. }
  22. func Discover(ctx context.Context, renewal, timeout time.Duration) []nat.Device {
  23. var ip net.IP
  24. err := util.CallWithContext(ctx, func() error {
  25. var err error
  26. ip, err = gateway.DiscoverGateway()
  27. return err
  28. })
  29. if err != nil {
  30. l.Debugln("Failed to discover gateway", err)
  31. return nil
  32. }
  33. if ip == nil || ip.IsUnspecified() {
  34. return nil
  35. }
  36. l.Debugln("Discovered gateway at", ip)
  37. c := natpmp.NewClientWithTimeout(ip, timeout)
  38. // Try contacting the gateway, if it does not respond, assume it does not
  39. // speak NAT-PMP.
  40. err = util.CallWithContext(ctx, func() error {
  41. _, ierr := c.GetExternalAddress()
  42. return ierr
  43. })
  44. if err != nil {
  45. if errors.Cause(err) == context.Canceled {
  46. return nil
  47. }
  48. if strings.Contains(err.Error(), "Timed out") {
  49. l.Debugln("Timeout trying to get external address, assume no NAT-PMP available")
  50. return nil
  51. }
  52. }
  53. var localIP net.IP
  54. // Port comes from the natpmp package
  55. timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
  56. defer cancel()
  57. conn, err := (&net.Dialer{}).DialContext(timeoutCtx, "udp", net.JoinHostPort(ip.String(), "5351"))
  58. if err == nil {
  59. conn.Close()
  60. localIPAddress, _, err := net.SplitHostPort(conn.LocalAddr().String())
  61. if err == nil {
  62. localIP = net.ParseIP(localIPAddress)
  63. } else {
  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) GetLocalIPAddress() net.IP {
  84. return w.localIP
  85. }
  86. func (w *wrapper) AddPortMapping(ctx context.Context, protocol nat.Protocol, internalPort, externalPort int, description 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 := util.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 (w *wrapper) GetExternalIPAddress(ctx context.Context) (net.IP, error) {
  106. var result *natpmp.GetExternalAddressResult
  107. err := util.CallWithContext(ctx, func() error {
  108. var err error
  109. result, err = w.client.GetExternalAddress()
  110. return err
  111. })
  112. ip := net.IPv4zero
  113. if result != nil {
  114. ip = net.IPv4(
  115. result.ExternalIPAddress[0],
  116. result.ExternalIPAddress[1],
  117. result.ExternalIPAddress[2],
  118. result.ExternalIPAddress[3],
  119. )
  120. }
  121. return ip, err
  122. }