igd_service.go 9.7 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. "net"
  39. "time"
  40. "github.com/syncthing/syncthing/lib/netutil"
  41. "github.com/syncthing/syncthing/lib/nat"
  42. )
  43. // An IGDService is a specific service provided by an IGD.
  44. type IGDService struct {
  45. UUID string
  46. Device upnpDevice
  47. ServiceID string
  48. URL string
  49. URN string
  50. LocalIPv4 net.IP
  51. Interface *net.Interface
  52. nat.Service
  53. }
  54. // AddPinhole adds an IPv6 pinhole in accordance to http://upnp.org/specs/gw/UPnP-gw-WANIPv6FirewallControl-v1-Service.pdf
  55. // This is attempted for each IPv6 on the interface.
  56. func (s *IGDService) AddPinhole(ctx context.Context, protocol nat.Protocol, intAddr nat.Address, duration time.Duration) ([]net.IP, error) {
  57. var returnErr error
  58. var successfulIPs []net.IP
  59. if s.Interface == nil {
  60. return nil, errors.New("no interface")
  61. }
  62. addrs, err := netutil.InterfaceAddrsByInterface(s.Interface)
  63. if err != nil {
  64. return nil, err
  65. }
  66. if !intAddr.IP.IsUnspecified() {
  67. // We have an explicit listener address. Check if that's on the interface
  68. // and pinhole it if so. It's not an error if not though, so don't return
  69. // an error if one doesn't occur.
  70. if intAddr.IP.To4() != nil {
  71. l.Debugf("Listener is IPv4. Not using gateway %s", s.ID())
  72. return nil, nil
  73. }
  74. for _, addr := range addrs {
  75. ip, _, err := net.ParseCIDR(addr.String())
  76. if err != nil {
  77. return nil, err
  78. }
  79. if ip.Equal(intAddr.IP) {
  80. err := s.tryAddPinholeForIP6(ctx, protocol, intAddr.Port, duration, intAddr.IP)
  81. if err != nil {
  82. return nil, err
  83. }
  84. return []net.IP{
  85. intAddr.IP,
  86. }, nil
  87. }
  88. l.Debugf("Listener IP %s not on interface for gateway %s", intAddr.IP, s.ID())
  89. }
  90. return nil, nil
  91. }
  92. // Otherwise, try to get a pinhole for all IPs, since we are listening on all
  93. for _, addr := range addrs {
  94. ip, _, err := net.ParseCIDR(addr.String())
  95. if err != nil {
  96. l.Infof("Couldn't parse address %s: %s", addr, err)
  97. continue
  98. }
  99. // Note that IsGlobalUnicast allows ULAs.
  100. if ip.To4() != nil || !ip.IsGlobalUnicast() || ip.IsPrivate() {
  101. continue
  102. }
  103. if err := s.tryAddPinholeForIP6(ctx, protocol, intAddr.Port, duration, ip); err != nil {
  104. l.Infof("Couldn't add pinhole for [%s]:%d/%s. %s", ip, intAddr.Port, protocol, err)
  105. returnErr = err
  106. } else {
  107. successfulIPs = append(successfulIPs, ip)
  108. }
  109. }
  110. if len(successfulIPs) > 0 {
  111. // (Maybe partial) success, we added a pinhole for at least one GUA.
  112. return successfulIPs, nil
  113. } else {
  114. return nil, returnErr
  115. }
  116. }
  117. func (s *IGDService) tryAddPinholeForIP6(ctx context.Context, protocol nat.Protocol, port int, duration time.Duration, ip net.IP) error {
  118. var protoNumber int
  119. if protocol == nat.TCP {
  120. protoNumber = 6
  121. } else if protocol == nat.UDP {
  122. protoNumber = 17
  123. } else {
  124. return errors.New("protocol not supported")
  125. }
  126. const template = `<u:AddPinhole xmlns:u="%s">
  127. <RemoteHost></RemoteHost>
  128. <RemotePort>0</RemotePort>
  129. <Protocol>%d</Protocol>
  130. <InternalPort>%d</InternalPort>
  131. <InternalClient>%s</InternalClient>
  132. <LeaseTime>%d</LeaseTime>
  133. </u:AddPinhole>`
  134. body := fmt.Sprintf(template, s.URN, protoNumber, port, ip, duration/time.Second)
  135. // IP should be a global unicast address, so we can use it as the source IP.
  136. // By the UPnP spec, the source address for unauthenticated clients should be
  137. // the same as the InternalAddress the pinhole is requested for.
  138. // Currently, WANIPv6FirewallProtocol is restricted to IPv6 gateways, so we can always set the IP.
  139. resp, err := soapRequestWithIP(ctx, s.URL, s.URN, "AddPinhole", body, &net.TCPAddr{IP: ip})
  140. if err != nil && resp != nil {
  141. var errResponse soapErrorResponse
  142. if unmarshalErr := xml.Unmarshal(resp, &errResponse); unmarshalErr != nil {
  143. // There is an error response that we cannot parse.
  144. return unmarshalErr
  145. }
  146. // There is a parsable UPnP error. Return that.
  147. return fmt.Errorf("UPnP error: %s (%d)", errResponse.ErrorDescription, errResponse.ErrorCode)
  148. } else if resp != nil {
  149. var succResponse soapAddPinholeResponse
  150. if unmarshalErr := xml.Unmarshal(resp, &succResponse); unmarshalErr != nil {
  151. // Ignore errors since this is only used for debug logging.
  152. l.Debugf("Failed to parse response from gateway %s: %s", s.ID(), unmarshalErr)
  153. } else {
  154. l.Debugf("UPnPv6: UID for pinhole on [%s]:%d/%s is %d on gateway %s", ip, port, protocol, succResponse.UniqueID, s.ID())
  155. }
  156. }
  157. // Either there was no error or an error not handled above (no response, e.g. network error).
  158. return err
  159. }
  160. // AddPortMapping adds a port mapping to the specified IGD service.
  161. func (s *IGDService) AddPortMapping(ctx context.Context, protocol nat.Protocol, internalPort, externalPort int, description string, duration time.Duration) (int, error) {
  162. if s.LocalIPv4 == nil {
  163. return 0, errors.New("no local IPv4")
  164. }
  165. const template = `<u:AddPortMapping xmlns:u="%s">
  166. <NewRemoteHost></NewRemoteHost>
  167. <NewExternalPort>%d</NewExternalPort>
  168. <NewProtocol>%s</NewProtocol>
  169. <NewInternalPort>%d</NewInternalPort>
  170. <NewInternalClient>%s</NewInternalClient>
  171. <NewEnabled>1</NewEnabled>
  172. <NewPortMappingDescription>%s</NewPortMappingDescription>
  173. <NewLeaseDuration>%d</NewLeaseDuration>
  174. </u:AddPortMapping>`
  175. body := fmt.Sprintf(template, s.URN, externalPort, protocol, internalPort, s.LocalIPv4, description, duration/time.Second)
  176. response, err := soapRequestWithIP(ctx, s.URL, s.URN, "AddPortMapping", body, &net.TCPAddr{IP: s.LocalIPv4})
  177. if err != nil && duration > 0 {
  178. // Try to repair error code 725 - OnlyPermanentLeasesSupported
  179. var envelope soapErrorResponse
  180. if unmarshalErr := xml.Unmarshal(response, &envelope); unmarshalErr != nil {
  181. return externalPort, unmarshalErr
  182. }
  183. if envelope.ErrorCode == 725 {
  184. return s.AddPortMapping(ctx, protocol, internalPort, externalPort, description, 0)
  185. }
  186. err = fmt.Errorf("UPnP Error: %s (%d)", envelope.ErrorDescription, envelope.ErrorCode)
  187. l.Debugf("Couldn't add port mapping for %s (external port %d -> internal port %d/%s): %s", s.LocalIPv4, externalPort, internalPort, protocol, err)
  188. }
  189. return externalPort, err
  190. }
  191. // DeletePortMapping deletes a port mapping from the specified IGD service.
  192. func (s *IGDService) DeletePortMapping(ctx context.Context, protocol nat.Protocol, externalPort int) error {
  193. const template = `<u:DeletePortMapping xmlns:u="%s">
  194. <NewRemoteHost></NewRemoteHost>
  195. <NewExternalPort>%d</NewExternalPort>
  196. <NewProtocol>%s</NewProtocol>
  197. </u:DeletePortMapping>`
  198. body := fmt.Sprintf(template, s.URN, externalPort, protocol)
  199. _, err := soapRequest(ctx, s.URL, s.URN, "DeletePortMapping", body)
  200. return err
  201. }
  202. // GetExternalIPv4Address queries the IGD service for its external IP address.
  203. // Returns nil if the external IP address is invalid or undefined, along with
  204. // any relevant errors
  205. func (s *IGDService) GetExternalIPv4Address(ctx context.Context) (net.IP, error) {
  206. const template = `<u:GetExternalIPAddress xmlns:u="%s" />`
  207. body := fmt.Sprintf(template, s.URN)
  208. response, err := soapRequest(ctx, s.URL, s.URN, "GetExternalIPAddress", body)
  209. if err != nil {
  210. return nil, err
  211. }
  212. var envelope soapGetExternalIPAddressResponseEnvelope
  213. if err := xml.Unmarshal(response, &envelope); err != nil {
  214. return nil, err
  215. }
  216. result := net.ParseIP(envelope.Body.GetExternalIPAddressResponse.NewExternalIPAddress)
  217. return result, nil
  218. }
  219. // GetLocalIPv4Address returns local IP address used to contact this service
  220. func (s *IGDService) GetLocalIPv4Address() net.IP {
  221. return s.LocalIPv4
  222. }
  223. // SupportsIPVersion checks whether this is a WANIPv6FirewallControl device,
  224. // in which case pinholing instead of port mapping should be done
  225. func (s *IGDService) SupportsIPVersion(version nat.IPVersion) bool {
  226. if version == nat.IPvAny {
  227. return true
  228. } else if version == nat.IPv6Only {
  229. return s.URN == urnWANIPv6FirewallControlV1
  230. } else if version == nat.IPv4Only {
  231. return s.URN != urnWANIPv6FirewallControlV1
  232. }
  233. return true
  234. }
  235. // ID returns a unique ID for the service
  236. func (s *IGDService) ID() string {
  237. return s.UUID + "/" + s.Device.FriendlyName + "/" + s.ServiceID + "/" + s.URN + "/" + s.URL
  238. }