igd_service.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // Adapted from https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/IGD.go
  4. // Copyright (c) 2010 Jack Palevich (https://github.com/jackpal/Taipei-Torrent/blob/dd88a8bfac6431c01d959ce3c745e74b8a911793/LICENSE)
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. //
  32. package upnp
  33. import (
  34. "context"
  35. "encoding/xml"
  36. "errors"
  37. "fmt"
  38. "log/slog"
  39. "net"
  40. "time"
  41. "github.com/syncthing/syncthing/internal/slogutil"
  42. "github.com/syncthing/syncthing/lib/netutil"
  43. "github.com/syncthing/syncthing/lib/nat"
  44. )
  45. // An IGDService is a specific service provided by an IGD.
  46. type IGDService struct {
  47. UUID string
  48. Device upnpDevice
  49. ServiceID string
  50. URL string
  51. URN string
  52. LocalIPv4 net.IP
  53. Interface *net.Interface
  54. }
  55. // AddPinhole adds an IPv6 pinhole in accordance to http://upnp.org/specs/gw/UPnP-gw-WANIPv6FirewallControl-v1-Service.pdf
  56. // This is attempted for each IPv6 on the interface.
  57. func (s *IGDService) AddPinhole(ctx context.Context, protocol nat.Protocol, intAddr nat.Address, duration time.Duration) ([]net.IP, error) {
  58. var returnErr error
  59. var successfulIPs []net.IP
  60. if s.Interface == nil {
  61. return nil, errors.New("no interface")
  62. }
  63. addrs, err := netutil.InterfaceAddrsByInterface(s.Interface)
  64. if err != nil {
  65. return nil, err
  66. }
  67. if !intAddr.IP.IsUnspecified() {
  68. // We have an explicit listener address. Check if that's on the interface
  69. // and pinhole it if so. It's not an error if not though, so don't return
  70. // an error if one doesn't occur.
  71. if intAddr.IP.To4() != nil {
  72. l.Debugf("Listener is IPv4. Not using gateway %s", s.ID())
  73. return nil, nil
  74. }
  75. for _, addr := range addrs {
  76. ip, _, err := net.ParseCIDR(addr.String())
  77. if err != nil {
  78. return nil, err
  79. }
  80. if ip.Equal(intAddr.IP) {
  81. err := s.tryAddPinholeForIP6(ctx, protocol, intAddr.Port, duration, intAddr.IP)
  82. if err != nil {
  83. return nil, err
  84. }
  85. return []net.IP{
  86. intAddr.IP,
  87. }, nil
  88. }
  89. l.Debugf("Listener IP %s not on interface for gateway %s", intAddr.IP, s.ID())
  90. }
  91. return nil, nil
  92. }
  93. // Otherwise, try to get a pinhole for all IPs, since we are listening on all
  94. for _, addr := range addrs {
  95. ip, _, err := net.ParseCIDR(addr.String())
  96. if err != nil {
  97. slog.WarnContext(ctx, "Couldn't parse interface address", slogutil.Address(addr), slogutil.Error(err))
  98. continue
  99. }
  100. // Note that IsGlobalUnicast allows ULAs.
  101. if ip.To4() != nil || !ip.IsGlobalUnicast() || ip.IsPrivate() {
  102. continue
  103. }
  104. if err := s.tryAddPinholeForIP6(ctx, protocol, intAddr.Port, duration, ip); err != nil {
  105. slog.WarnContext(ctx, "Couldn't add pinhole", slogutil.Address(ip), slog.Int("port", intAddr.Port), slog.Any("protocol", protocol), slogutil.Error(err))
  106. returnErr = err
  107. } else {
  108. successfulIPs = append(successfulIPs, ip)
  109. }
  110. }
  111. if len(successfulIPs) > 0 {
  112. // (Maybe partial) success, we added a pinhole for at least one GUA.
  113. return successfulIPs, nil
  114. } else {
  115. return nil, returnErr
  116. }
  117. }
  118. func (s *IGDService) tryAddPinholeForIP6(ctx context.Context, protocol nat.Protocol, port int, duration time.Duration, ip net.IP) error {
  119. var protoNumber int
  120. if protocol == nat.TCP {
  121. protoNumber = 6
  122. } else if protocol == nat.UDP {
  123. protoNumber = 17
  124. } else {
  125. return errors.New("protocol not supported")
  126. }
  127. const template = `<u:AddPinhole xmlns:u="%s">
  128. <RemoteHost></RemoteHost>
  129. <RemotePort>0</RemotePort>
  130. <Protocol>%d</Protocol>
  131. <InternalPort>%d</InternalPort>
  132. <InternalClient>%s</InternalClient>
  133. <LeaseTime>%d</LeaseTime>
  134. </u:AddPinhole>`
  135. body := fmt.Sprintf(template, s.URN, protoNumber, port, ip, duration/time.Second)
  136. // IP should be a global unicast address, so we can use it as the source IP.
  137. // By the UPnP spec, the source address for unauthenticated clients should be
  138. // the same as the InternalAddress the pinhole is requested for.
  139. // Currently, WANIPv6FirewallProtocol is restricted to IPv6 gateways, so we can always set the IP.
  140. resp, err := soapRequestWithIP(ctx, s.URL, s.URN, "AddPinhole", body, &net.TCPAddr{IP: ip})
  141. if err != nil && resp != nil {
  142. var errResponse soapErrorResponse
  143. if unmarshalErr := xml.Unmarshal(resp, &errResponse); unmarshalErr != nil {
  144. // There is an error response that we cannot parse.
  145. return unmarshalErr
  146. }
  147. // There is a parsable UPnP error. Return that.
  148. return fmt.Errorf("UPnP error: %s (%d)", errResponse.ErrorDescription, errResponse.ErrorCode)
  149. } else if resp != nil {
  150. var succResponse soapAddPinholeResponse
  151. if unmarshalErr := xml.Unmarshal(resp, &succResponse); unmarshalErr != nil {
  152. // Ignore errors since this is only used for debug logging.
  153. l.Debugf("Failed to parse response from gateway %s: %s", s.ID(), unmarshalErr)
  154. } else {
  155. l.Debugf("UPnPv6: UID for pinhole on [%s]:%d/%s is %d on gateway %s", ip, port, protocol, succResponse.UniqueID, s.ID())
  156. }
  157. }
  158. // Either there was no error or an error not handled above (no response, e.g. network error).
  159. return err
  160. }
  161. // AddPortMapping adds a port mapping to the specified IGD service.
  162. func (s *IGDService) AddPortMapping(ctx context.Context, protocol nat.Protocol, internalPort, externalPort int, description string, duration time.Duration) (int, error) {
  163. if s.LocalIPv4 == nil {
  164. return 0, errors.New("no local IPv4")
  165. }
  166. const template = `<u:AddPortMapping xmlns:u="%s">
  167. <NewRemoteHost></NewRemoteHost>
  168. <NewExternalPort>%d</NewExternalPort>
  169. <NewProtocol>%s</NewProtocol>
  170. <NewInternalPort>%d</NewInternalPort>
  171. <NewInternalClient>%s</NewInternalClient>
  172. <NewEnabled>1</NewEnabled>
  173. <NewPortMappingDescription>%s</NewPortMappingDescription>
  174. <NewLeaseDuration>%d</NewLeaseDuration>
  175. </u:AddPortMapping>`
  176. body := fmt.Sprintf(template, s.URN, externalPort, protocol, internalPort, s.LocalIPv4, description, duration/time.Second)
  177. response, err := soapRequestWithIP(ctx, s.URL, s.URN, "AddPortMapping", body, &net.TCPAddr{IP: s.LocalIPv4})
  178. if err != nil && duration > 0 {
  179. // Try to repair error code 725 - OnlyPermanentLeasesSupported
  180. var envelope soapErrorResponse
  181. if unmarshalErr := xml.Unmarshal(response, &envelope); unmarshalErr != nil {
  182. return externalPort, unmarshalErr
  183. }
  184. if envelope.ErrorCode == 725 {
  185. return s.AddPortMapping(ctx, protocol, internalPort, externalPort, description, 0)
  186. }
  187. err = fmt.Errorf("UPnP Error: %s (%d)", envelope.ErrorDescription, envelope.ErrorCode)
  188. l.Debugf("Couldn't add port mapping for %s (external port %d -> internal port %d/%s): %s", s.LocalIPv4, externalPort, internalPort, protocol, err)
  189. }
  190. return externalPort, err
  191. }
  192. // DeletePortMapping deletes a port mapping from the specified IGD service.
  193. func (s *IGDService) DeletePortMapping(ctx context.Context, protocol nat.Protocol, externalPort int) error {
  194. const template = `<u:DeletePortMapping xmlns:u="%s">
  195. <NewRemoteHost></NewRemoteHost>
  196. <NewExternalPort>%d</NewExternalPort>
  197. <NewProtocol>%s</NewProtocol>
  198. </u:DeletePortMapping>`
  199. body := fmt.Sprintf(template, s.URN, externalPort, protocol)
  200. _, err := soapRequest(ctx, s.URL, s.URN, "DeletePortMapping", body)
  201. return err
  202. }
  203. // GetExternalIPv4Address queries the IGD service for its external IP address.
  204. // Returns nil if the external IP address is invalid or undefined, along with
  205. // any relevant errors
  206. func (s *IGDService) GetExternalIPv4Address(ctx context.Context) (net.IP, error) {
  207. const template = `<u:GetExternalIPAddress xmlns:u="%s" />`
  208. body := fmt.Sprintf(template, s.URN)
  209. response, err := soapRequest(ctx, s.URL, s.URN, "GetExternalIPAddress", body)
  210. if err != nil {
  211. return nil, err
  212. }
  213. var envelope soapGetExternalIPAddressResponseEnvelope
  214. if err := xml.Unmarshal(response, &envelope); err != nil {
  215. return nil, err
  216. }
  217. result := net.ParseIP(envelope.Body.GetExternalIPAddressResponse.NewExternalIPAddress)
  218. return result, nil
  219. }
  220. // GetLocalIPv4Address returns local IP address used to contact this service
  221. func (s *IGDService) GetLocalIPv4Address() net.IP {
  222. return s.LocalIPv4
  223. }
  224. // SupportsIPVersion checks whether this is a WANIPv6FirewallControl device,
  225. // in which case pinholing instead of port mapping should be done
  226. func (s *IGDService) SupportsIPVersion(version nat.IPVersion) bool {
  227. if version == nat.IPvAny {
  228. return true
  229. } else if version == nat.IPv6Only {
  230. return s.URN == urnWANIPv6FirewallControlV1
  231. } else if version == nat.IPv4Only {
  232. return s.URN != urnWANIPv6FirewallControlV1
  233. }
  234. return true
  235. }
  236. // ID returns a unique ID for the service
  237. func (s *IGDService) ID() string {
  238. return s.UUID + "/" + s.Device.FriendlyName + "/" + s.ServiceID + "/" + s.URN + "/" + s.URL
  239. }