igd_service.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. switch protocol {
  121. case nat.TCP:
  122. protoNumber = 6
  123. case nat.UDP:
  124. protoNumber = 17
  125. default:
  126. return errors.New("protocol not supported")
  127. }
  128. const template = `<u:AddPinhole xmlns:u="%s">
  129. <RemoteHost></RemoteHost>
  130. <RemotePort>0</RemotePort>
  131. <Protocol>%d</Protocol>
  132. <InternalPort>%d</InternalPort>
  133. <InternalClient>%s</InternalClient>
  134. <LeaseTime>%d</LeaseTime>
  135. </u:AddPinhole>`
  136. body := fmt.Sprintf(template, s.URN, protoNumber, port, ip, duration/time.Second)
  137. // IP should be a global unicast address, so we can use it as the source IP.
  138. // By the UPnP spec, the source address for unauthenticated clients should be
  139. // the same as the InternalAddress the pinhole is requested for.
  140. // Currently, WANIPv6FirewallProtocol is restricted to IPv6 gateways, so we can always set the IP.
  141. resp, err := soapRequestWithIP(ctx, s.URL, s.URN, "AddPinhole", body, &net.TCPAddr{IP: ip})
  142. if err != nil && resp != nil {
  143. var errResponse soapErrorResponse
  144. if unmarshalErr := xml.Unmarshal(resp, &errResponse); unmarshalErr != nil {
  145. // There is an error response that we cannot parse.
  146. return unmarshalErr
  147. }
  148. // There is a parsable UPnP error. Return that.
  149. return fmt.Errorf("UPnP error: %s (%d)", errResponse.ErrorDescription, errResponse.ErrorCode)
  150. } else if resp != nil {
  151. var succResponse soapAddPinholeResponse
  152. if unmarshalErr := xml.Unmarshal(resp, &succResponse); unmarshalErr != nil {
  153. // Ignore errors since this is only used for debug logging.
  154. l.Debugf("Failed to parse response from gateway %s: %s", s.ID(), unmarshalErr)
  155. } else {
  156. l.Debugf("UPnPv6: UID for pinhole on [%s]:%d/%s is %d on gateway %s", ip, port, protocol, succResponse.UniqueID, s.ID())
  157. }
  158. }
  159. // Either there was no error or an error not handled above (no response, e.g. network error).
  160. return err
  161. }
  162. // AddPortMapping adds a port mapping to the specified IGD service.
  163. func (s *IGDService) AddPortMapping(ctx context.Context, protocol nat.Protocol, internalPort, externalPort int, description string, duration time.Duration) (int, error) {
  164. if s.LocalIPv4 == nil {
  165. return 0, errors.New("no local IPv4")
  166. }
  167. const template = `<u:AddPortMapping xmlns:u="%s">
  168. <NewRemoteHost></NewRemoteHost>
  169. <NewExternalPort>%d</NewExternalPort>
  170. <NewProtocol>%s</NewProtocol>
  171. <NewInternalPort>%d</NewInternalPort>
  172. <NewInternalClient>%s</NewInternalClient>
  173. <NewEnabled>1</NewEnabled>
  174. <NewPortMappingDescription>%s</NewPortMappingDescription>
  175. <NewLeaseDuration>%d</NewLeaseDuration>
  176. </u:AddPortMapping>`
  177. body := fmt.Sprintf(template, s.URN, externalPort, protocol, internalPort, s.LocalIPv4, description, duration/time.Second)
  178. response, err := soapRequestWithIP(ctx, s.URL, s.URN, "AddPortMapping", body, &net.TCPAddr{IP: s.LocalIPv4})
  179. if err != nil && duration > 0 {
  180. // Try to repair error code 725 - OnlyPermanentLeasesSupported
  181. var envelope soapErrorResponse
  182. if unmarshalErr := xml.Unmarshal(response, &envelope); unmarshalErr != nil {
  183. return externalPort, unmarshalErr
  184. }
  185. if envelope.ErrorCode == 725 {
  186. return s.AddPortMapping(ctx, protocol, internalPort, externalPort, description, 0)
  187. }
  188. err = fmt.Errorf("UPnP Error: %s (%d)", envelope.ErrorDescription, envelope.ErrorCode)
  189. l.Debugf("Couldn't add port mapping for %s (external port %d -> internal port %d/%s): %s", s.LocalIPv4, externalPort, internalPort, protocol, err)
  190. }
  191. return externalPort, err
  192. }
  193. // DeletePortMapping deletes a port mapping from the specified IGD service.
  194. func (s *IGDService) DeletePortMapping(ctx context.Context, protocol nat.Protocol, externalPort int) error {
  195. const template = `<u:DeletePortMapping xmlns:u="%s">
  196. <NewRemoteHost></NewRemoteHost>
  197. <NewExternalPort>%d</NewExternalPort>
  198. <NewProtocol>%s</NewProtocol>
  199. </u:DeletePortMapping>`
  200. body := fmt.Sprintf(template, s.URN, externalPort, protocol)
  201. _, err := soapRequest(ctx, s.URL, s.URN, "DeletePortMapping", body)
  202. return err
  203. }
  204. // GetExternalIPv4Address queries the IGD service for its external IP address.
  205. // Returns nil if the external IP address is invalid or undefined, along with
  206. // any relevant errors
  207. func (s *IGDService) GetExternalIPv4Address(ctx context.Context) (net.IP, error) {
  208. const template = `<u:GetExternalIPAddress xmlns:u="%s" />`
  209. body := fmt.Sprintf(template, s.URN)
  210. response, err := soapRequest(ctx, s.URL, s.URN, "GetExternalIPAddress", body)
  211. if err != nil {
  212. return nil, err
  213. }
  214. var envelope soapGetExternalIPAddressResponseEnvelope
  215. if err := xml.Unmarshal(response, &envelope); err != nil {
  216. return nil, err
  217. }
  218. result := net.ParseIP(envelope.Body.GetExternalIPAddressResponse.NewExternalIPAddress)
  219. return result, nil
  220. }
  221. // GetLocalIPv4Address returns local IP address used to contact this service
  222. func (s *IGDService) GetLocalIPv4Address() net.IP {
  223. return s.LocalIPv4
  224. }
  225. // SupportsIPVersion checks whether this is a WANIPv6FirewallControl device,
  226. // in which case pinholing instead of port mapping should be done
  227. func (s *IGDService) SupportsIPVersion(version nat.IPVersion) bool {
  228. switch version {
  229. case nat.IPvAny:
  230. return true
  231. case nat.IPv6Only:
  232. return s.URN == urnWANIPv6FirewallControlV1
  233. case nat.IPv4Only:
  234. return s.URN != urnWANIPv6FirewallControlV1
  235. }
  236. return true
  237. }
  238. // ID returns a unique ID for the service
  239. func (s *IGDService) ID() string {
  240. return s.UUID + "/" + s.Device.FriendlyName + "/" + s.ServiceID + "/" + s.URN + "/" + s.URL
  241. }