natupnp.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package nat
  17. import (
  18. "errors"
  19. "fmt"
  20. "net"
  21. "strings"
  22. "time"
  23. "github.com/huin/goupnp"
  24. "github.com/huin/goupnp/dcps/internetgateway1"
  25. "github.com/huin/goupnp/dcps/internetgateway2"
  26. )
  27. const soapRequestTimeout = 3 * time.Second
  28. type upnp struct {
  29. dev *goupnp.RootDevice
  30. service string
  31. client upnpClient
  32. }
  33. type upnpClient interface {
  34. GetExternalIPAddress() (string, error)
  35. AddPortMapping(string, uint16, string, uint16, string, bool, string, uint32) error
  36. DeletePortMapping(string, uint16, string) error
  37. GetNATRSIPStatus() (sip bool, nat bool, err error)
  38. }
  39. func (n *upnp) ExternalIP() (addr net.IP, err error) {
  40. ipString, err := n.client.GetExternalIPAddress()
  41. if err != nil {
  42. return nil, err
  43. }
  44. ip := net.ParseIP(ipString)
  45. if ip == nil {
  46. return nil, errors.New("bad IP in response")
  47. }
  48. return ip, nil
  49. }
  50. func (n *upnp) AddMapping(protocol string, extport, intport int, desc string, lifetime time.Duration) error {
  51. ip, err := n.internalAddress()
  52. if err != nil {
  53. return nil
  54. }
  55. protocol = strings.ToUpper(protocol)
  56. lifetimeS := uint32(lifetime / time.Second)
  57. n.DeleteMapping(protocol, extport, intport)
  58. return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
  59. }
  60. func (n *upnp) internalAddress() (net.IP, error) {
  61. devaddr, err := net.ResolveUDPAddr("udp4", n.dev.URLBase.Host)
  62. if err != nil {
  63. return nil, err
  64. }
  65. ifaces, err := net.Interfaces()
  66. if err != nil {
  67. return nil, err
  68. }
  69. for _, iface := range ifaces {
  70. addrs, err := iface.Addrs()
  71. if err != nil {
  72. return nil, err
  73. }
  74. for _, addr := range addrs {
  75. switch x := addr.(type) {
  76. case *net.IPNet:
  77. if x.Contains(devaddr.IP) {
  78. return x.IP, nil
  79. }
  80. }
  81. }
  82. }
  83. return nil, fmt.Errorf("could not find local address in same net as %v", devaddr)
  84. }
  85. func (n *upnp) DeleteMapping(protocol string, extport, intport int) error {
  86. return n.client.DeletePortMapping("", uint16(extport), strings.ToUpper(protocol))
  87. }
  88. func (n *upnp) String() string {
  89. return "UPNP " + n.service
  90. }
  91. // discoverUPnP searches for Internet Gateway Devices
  92. // and returns the first one it can find on the local network.
  93. func discoverUPnP() Interface {
  94. found := make(chan *upnp, 2)
  95. // IGDv1
  96. go discover(found, internetgateway1.URN_WANConnectionDevice_1, func(dev *goupnp.RootDevice, sc goupnp.ServiceClient) *upnp {
  97. switch sc.Service.ServiceType {
  98. case internetgateway1.URN_WANIPConnection_1:
  99. return &upnp{dev, "IGDv1-IP1", &internetgateway1.WANIPConnection1{ServiceClient: sc}}
  100. case internetgateway1.URN_WANPPPConnection_1:
  101. return &upnp{dev, "IGDv1-PPP1", &internetgateway1.WANPPPConnection1{ServiceClient: sc}}
  102. }
  103. return nil
  104. })
  105. // IGDv2
  106. go discover(found, internetgateway2.URN_WANConnectionDevice_2, func(dev *goupnp.RootDevice, sc goupnp.ServiceClient) *upnp {
  107. switch sc.Service.ServiceType {
  108. case internetgateway2.URN_WANIPConnection_1:
  109. return &upnp{dev, "IGDv2-IP1", &internetgateway2.WANIPConnection1{ServiceClient: sc}}
  110. case internetgateway2.URN_WANIPConnection_2:
  111. return &upnp{dev, "IGDv2-IP2", &internetgateway2.WANIPConnection2{ServiceClient: sc}}
  112. case internetgateway2.URN_WANPPPConnection_1:
  113. return &upnp{dev, "IGDv2-PPP1", &internetgateway2.WANPPPConnection1{ServiceClient: sc}}
  114. }
  115. return nil
  116. })
  117. for i := 0; i < cap(found); i++ {
  118. if c := <-found; c != nil {
  119. return c
  120. }
  121. }
  122. return nil
  123. }
  124. // finds devices matching the given target and calls matcher for all
  125. // advertised services of each device. The first non-nil service found
  126. // is sent into out. If no service matched, nil is sent.
  127. func discover(out chan<- *upnp, target string, matcher func(*goupnp.RootDevice, goupnp.ServiceClient) *upnp) {
  128. devs, err := goupnp.DiscoverDevices(target)
  129. if err != nil {
  130. out <- nil
  131. return
  132. }
  133. found := false
  134. for i := 0; i < len(devs) && !found; i++ {
  135. if devs[i].Root == nil {
  136. continue
  137. }
  138. devs[i].Root.Device.VisitServices(func(service *goupnp.Service) {
  139. if found {
  140. return
  141. }
  142. // check for a matching IGD service
  143. sc := goupnp.ServiceClient{
  144. SOAPClient: service.NewSOAPClient(),
  145. RootDevice: devs[i].Root,
  146. Location: devs[i].Location,
  147. Service: service,
  148. }
  149. sc.SOAPClient.HTTPClient.Timeout = soapRequestTimeout
  150. upnp := matcher(devs[i].Root, sc)
  151. if upnp == nil {
  152. return
  153. }
  154. // check whether port mapping is enabled
  155. if _, nat, err := upnp.client.GetNATRSIPStatus(); err != nil || !nat {
  156. return
  157. }
  158. out <- upnp
  159. found = true
  160. })
  161. }
  162. if !found {
  163. out <- nil
  164. }
  165. }