natupnp.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
  58. }
  59. func (n *upnp) internalAddress() (net.IP, error) {
  60. devaddr, err := net.ResolveUDPAddr("udp4", n.dev.URLBase.Host)
  61. if err != nil {
  62. return nil, err
  63. }
  64. ifaces, err := net.Interfaces()
  65. if err != nil {
  66. return nil, err
  67. }
  68. for _, iface := range ifaces {
  69. addrs, err := iface.Addrs()
  70. if err != nil {
  71. return nil, err
  72. }
  73. for _, addr := range addrs {
  74. switch x := addr.(type) {
  75. case *net.IPNet:
  76. if x.Contains(devaddr.IP) {
  77. return x.IP, nil
  78. }
  79. }
  80. }
  81. }
  82. return nil, fmt.Errorf("could not find local address in same net as %v", devaddr)
  83. }
  84. func (n *upnp) DeleteMapping(protocol string, extport, intport int) error {
  85. return n.client.DeletePortMapping("", uint16(extport), strings.ToUpper(protocol))
  86. }
  87. func (n *upnp) String() string {
  88. return "UPNP " + n.service
  89. }
  90. // discoverUPnP searches for Internet Gateway Devices
  91. // and returns the first one it can find on the local network.
  92. func discoverUPnP() Interface {
  93. found := make(chan *upnp, 2)
  94. // IGDv1
  95. go discover(found, internetgateway1.URN_WANConnectionDevice_1, func(dev *goupnp.RootDevice, sc goupnp.ServiceClient) *upnp {
  96. switch sc.Service.ServiceType {
  97. case internetgateway1.URN_WANIPConnection_1:
  98. return &upnp{dev, "IGDv1-IP1", &internetgateway1.WANIPConnection1{ServiceClient: sc}}
  99. case internetgateway1.URN_WANPPPConnection_1:
  100. return &upnp{dev, "IGDv1-PPP1", &internetgateway1.WANPPPConnection1{ServiceClient: sc}}
  101. }
  102. return nil
  103. })
  104. // IGDv2
  105. go discover(found, internetgateway2.URN_WANConnectionDevice_2, func(dev *goupnp.RootDevice, sc goupnp.ServiceClient) *upnp {
  106. switch sc.Service.ServiceType {
  107. case internetgateway2.URN_WANIPConnection_1:
  108. return &upnp{dev, "IGDv2-IP1", &internetgateway2.WANIPConnection1{ServiceClient: sc}}
  109. case internetgateway2.URN_WANIPConnection_2:
  110. return &upnp{dev, "IGDv2-IP2", &internetgateway2.WANIPConnection2{ServiceClient: sc}}
  111. case internetgateway2.URN_WANPPPConnection_1:
  112. return &upnp{dev, "IGDv2-PPP1", &internetgateway2.WANPPPConnection1{ServiceClient: sc}}
  113. }
  114. return nil
  115. })
  116. for i := 0; i < cap(found); i++ {
  117. if c := <-found; c != nil {
  118. return c
  119. }
  120. }
  121. return nil
  122. }
  123. // finds devices matching the given target and calls matcher for all
  124. // advertised services of each device. The first non-nil service found
  125. // is sent into out. If no service matched, nil is sent.
  126. func discover(out chan<- *upnp, target string, matcher func(*goupnp.RootDevice, goupnp.ServiceClient) *upnp) {
  127. devs, err := goupnp.DiscoverDevices(target)
  128. if err != nil {
  129. out <- nil
  130. return
  131. }
  132. found := false
  133. for i := 0; i < len(devs) && !found; i++ {
  134. if devs[i].Root == nil {
  135. continue
  136. }
  137. devs[i].Root.Device.VisitServices(func(service *goupnp.Service) {
  138. if found {
  139. return
  140. }
  141. // check for a matching IGD service
  142. sc := goupnp.ServiceClient{
  143. SOAPClient: service.NewSOAPClient(),
  144. RootDevice: devs[i].Root,
  145. Location: devs[i].Location,
  146. Service: service,
  147. }
  148. sc.SOAPClient.HTTPClient.Timeout = soapRequestTimeout
  149. upnp := matcher(devs[i].Root, sc)
  150. if upnp == nil {
  151. return
  152. }
  153. // check whether port mapping is enabled
  154. if _, nat, err := upnp.client.GetNATRSIPStatus(); err != nil || !nat {
  155. return
  156. }
  157. out <- upnp
  158. found = true
  159. })
  160. }
  161. if !found {
  162. out <- nil
  163. }
  164. }