igd_service.go 9.6 KB

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