natupnp.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. "sync"
  23. "time"
  24. "github.com/huin/goupnp"
  25. "github.com/huin/goupnp/dcps/internetgateway1"
  26. "github.com/huin/goupnp/dcps/internetgateway2"
  27. )
  28. const (
  29. soapRequestTimeout = 3 * time.Second
  30. rateLimit = 200 * time.Millisecond
  31. )
  32. type upnp struct {
  33. dev *goupnp.RootDevice
  34. service string
  35. client upnpClient
  36. mu sync.Mutex
  37. lastReqTime time.Time
  38. }
  39. type upnpClient interface {
  40. GetExternalIPAddress() (string, error)
  41. AddPortMapping(string, uint16, string, uint16, string, bool, string, uint32) error
  42. DeletePortMapping(string, uint16, string) error
  43. GetNATRSIPStatus() (sip bool, nat bool, err error)
  44. }
  45. func (n *upnp) natEnabled() bool {
  46. var ok bool
  47. var err error
  48. n.withRateLimit(func() error {
  49. _, ok, err = n.client.GetNATRSIPStatus()
  50. return err
  51. })
  52. return err == nil && ok
  53. }
  54. func (n *upnp) ExternalIP() (addr net.IP, err error) {
  55. var ipString string
  56. n.withRateLimit(func() error {
  57. ipString, err = n.client.GetExternalIPAddress()
  58. return err
  59. })
  60. if err != nil {
  61. return nil, err
  62. }
  63. ip := net.ParseIP(ipString)
  64. if ip == nil {
  65. return nil, errors.New("bad IP in response")
  66. }
  67. return ip, nil
  68. }
  69. func (n *upnp) AddMapping(protocol string, extport, intport int, desc string, lifetime time.Duration) error {
  70. ip, err := n.internalAddress()
  71. if err != nil {
  72. return nil
  73. }
  74. protocol = strings.ToUpper(protocol)
  75. lifetimeS := uint32(lifetime / time.Second)
  76. n.DeleteMapping(protocol, extport, intport)
  77. return n.withRateLimit(func() error {
  78. return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
  79. })
  80. }
  81. func (n *upnp) internalAddress() (net.IP, error) {
  82. devaddr, err := net.ResolveUDPAddr("udp4", n.dev.URLBase.Host)
  83. if err != nil {
  84. return nil, err
  85. }
  86. ifaces, err := net.Interfaces()
  87. if err != nil {
  88. return nil, err
  89. }
  90. for _, iface := range ifaces {
  91. addrs, err := iface.Addrs()
  92. if err != nil {
  93. return nil, err
  94. }
  95. for _, addr := range addrs {
  96. if x, ok := addr.(*net.IPNet); ok && x.Contains(devaddr.IP) {
  97. return x.IP, nil
  98. }
  99. }
  100. }
  101. return nil, fmt.Errorf("could not find local address in same net as %v", devaddr)
  102. }
  103. func (n *upnp) DeleteMapping(protocol string, extport, intport int) error {
  104. return n.withRateLimit(func() error {
  105. return n.client.DeletePortMapping("", uint16(extport), strings.ToUpper(protocol))
  106. })
  107. }
  108. func (n *upnp) String() string {
  109. return "UPNP " + n.service
  110. }
  111. func (n *upnp) withRateLimit(fn func() error) error {
  112. n.mu.Lock()
  113. defer n.mu.Unlock()
  114. lastreq := time.Since(n.lastReqTime)
  115. if lastreq < rateLimit {
  116. time.Sleep(rateLimit - lastreq)
  117. }
  118. err := fn()
  119. n.lastReqTime = time.Now()
  120. return err
  121. }
  122. // discoverUPnP searches for Internet Gateway Devices
  123. // and returns the first one it can find on the local network.
  124. func discoverUPnP() Interface {
  125. found := make(chan *upnp, 2)
  126. // IGDv1
  127. go discover(found, internetgateway1.URN_WANConnectionDevice_1, func(sc goupnp.ServiceClient) *upnp {
  128. switch sc.Service.ServiceType {
  129. case internetgateway1.URN_WANIPConnection_1:
  130. return &upnp{service: "IGDv1-IP1", client: &internetgateway1.WANIPConnection1{ServiceClient: sc}}
  131. case internetgateway1.URN_WANPPPConnection_1:
  132. return &upnp{service: "IGDv1-PPP1", client: &internetgateway1.WANPPPConnection1{ServiceClient: sc}}
  133. }
  134. return nil
  135. })
  136. // IGDv2
  137. go discover(found, internetgateway2.URN_WANConnectionDevice_2, func(sc goupnp.ServiceClient) *upnp {
  138. switch sc.Service.ServiceType {
  139. case internetgateway2.URN_WANIPConnection_1:
  140. return &upnp{service: "IGDv2-IP1", client: &internetgateway2.WANIPConnection1{ServiceClient: sc}}
  141. case internetgateway2.URN_WANIPConnection_2:
  142. return &upnp{service: "IGDv2-IP2", client: &internetgateway2.WANIPConnection2{ServiceClient: sc}}
  143. case internetgateway2.URN_WANPPPConnection_1:
  144. return &upnp{service: "IGDv2-PPP1", client: &internetgateway2.WANPPPConnection1{ServiceClient: sc}}
  145. }
  146. return nil
  147. })
  148. for i := 0; i < cap(found); i++ {
  149. if c := <-found; c != nil {
  150. return c
  151. }
  152. }
  153. return nil
  154. }
  155. // finds devices matching the given target and calls matcher for all
  156. // advertised services of each device. The first non-nil service found
  157. // is sent into out. If no service matched, nil is sent.
  158. func discover(out chan<- *upnp, target string, matcher func(goupnp.ServiceClient) *upnp) {
  159. devs, err := goupnp.DiscoverDevices(target)
  160. if err != nil {
  161. out <- nil
  162. return
  163. }
  164. found := false
  165. for i := 0; i < len(devs) && !found; i++ {
  166. if devs[i].Root == nil {
  167. continue
  168. }
  169. devs[i].Root.Device.VisitServices(func(service *goupnp.Service) {
  170. if found {
  171. return
  172. }
  173. // check for a matching IGD service
  174. sc := goupnp.ServiceClient{
  175. SOAPClient: service.NewSOAPClient(),
  176. RootDevice: devs[i].Root,
  177. Location: devs[i].Location,
  178. Service: service,
  179. }
  180. sc.SOAPClient.HTTPClient.Timeout = soapRequestTimeout
  181. upnp := matcher(sc)
  182. if upnp == nil {
  183. return
  184. }
  185. upnp.dev = devs[i].Root
  186. // check whether port mapping is enabled
  187. if upnp.natEnabled() {
  188. out <- upnp
  189. found = true
  190. }
  191. })
  192. }
  193. if !found {
  194. out <- nil
  195. }
  196. }