You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

221 lines
5.1 KiB

9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package p2p
  2. import (
  3. "fmt"
  4. "net"
  5. "strconv"
  6. "time"
  7. "github.com/tendermint/tendermint/p2p/upnp"
  8. cmn "github.com/tendermint/tmlibs/common"
  9. "github.com/tendermint/tmlibs/log"
  10. )
  11. type Listener interface {
  12. Connections() <-chan net.Conn
  13. InternalAddress() *NetAddress
  14. ExternalAddress() *NetAddress
  15. String() string
  16. Stop() bool
  17. }
  18. // Implements Listener
  19. type DefaultListener struct {
  20. cmn.BaseService
  21. listener net.Listener
  22. intAddr *NetAddress
  23. extAddr *NetAddress
  24. connections chan net.Conn
  25. }
  26. const (
  27. numBufferedConnections = 10
  28. defaultExternalPort = 8770
  29. tryListenSeconds = 5
  30. )
  31. func splitHostPort(addr string) (host string, port int) {
  32. host, portStr, err := net.SplitHostPort(addr)
  33. if err != nil {
  34. cmn.PanicSanity(err)
  35. }
  36. port, err = strconv.Atoi(portStr)
  37. if err != nil {
  38. cmn.PanicSanity(err)
  39. }
  40. return host, port
  41. }
  42. // skipUPNP: If true, does not try getUPNPExternalAddress()
  43. func NewDefaultListener(protocol string, lAddr string, skipUPNP bool, logger log.Logger) Listener {
  44. // Local listen IP & port
  45. lAddrIP, lAddrPort := splitHostPort(lAddr)
  46. // Create listener
  47. var listener net.Listener
  48. var err error
  49. for i := 0; i < tryListenSeconds; i++ {
  50. listener, err = net.Listen(protocol, lAddr)
  51. if err == nil {
  52. break
  53. } else if i < tryListenSeconds-1 {
  54. time.Sleep(time.Second * 1)
  55. }
  56. }
  57. if err != nil {
  58. cmn.PanicCrisis(err)
  59. }
  60. // Actual listener local IP & port
  61. listenerIP, listenerPort := splitHostPort(listener.Addr().String())
  62. logger.Info("Local listener", "ip", listenerIP, "port", listenerPort)
  63. // Determine internal address...
  64. var intAddr *NetAddress
  65. intAddr, err = NewNetAddressString(lAddr)
  66. if err != nil {
  67. cmn.PanicCrisis(err)
  68. }
  69. // Determine external address...
  70. var extAddr *NetAddress
  71. if !skipUPNP {
  72. // If the lAddrIP is INADDR_ANY, try UPnP
  73. if lAddrIP == "" || lAddrIP == "0.0.0.0" {
  74. extAddr = getUPNPExternalAddress(lAddrPort, listenerPort, logger)
  75. }
  76. }
  77. // Otherwise just use the local address...
  78. if extAddr == nil {
  79. extAddr = getNaiveExternalAddress(listenerPort, false, logger)
  80. }
  81. if extAddr == nil {
  82. cmn.PanicCrisis("Could not determine external address!")
  83. }
  84. dl := &DefaultListener{
  85. listener: listener,
  86. intAddr: intAddr,
  87. extAddr: extAddr,
  88. connections: make(chan net.Conn, numBufferedConnections),
  89. }
  90. dl.BaseService = *cmn.NewBaseService(logger, "DefaultListener", dl)
  91. dl.Start() // Started upon construction
  92. return dl
  93. }
  94. func (l *DefaultListener) OnStart() error {
  95. l.BaseService.OnStart()
  96. go l.listenRoutine()
  97. return nil
  98. }
  99. func (l *DefaultListener) OnStop() {
  100. l.BaseService.OnStop()
  101. l.listener.Close()
  102. }
  103. // Accept connections and pass on the channel
  104. func (l *DefaultListener) listenRoutine() {
  105. for {
  106. conn, err := l.listener.Accept()
  107. if !l.IsRunning() {
  108. break // Go to cleanup
  109. }
  110. // listener wasn't stopped,
  111. // yet we encountered an error.
  112. if err != nil {
  113. cmn.PanicCrisis(err)
  114. }
  115. l.connections <- conn
  116. }
  117. // Cleanup
  118. close(l.connections)
  119. for range l.connections {
  120. // Drain
  121. }
  122. }
  123. // A channel of inbound connections.
  124. // It gets closed when the listener closes.
  125. func (l *DefaultListener) Connections() <-chan net.Conn {
  126. return l.connections
  127. }
  128. func (l *DefaultListener) InternalAddress() *NetAddress {
  129. return l.intAddr
  130. }
  131. func (l *DefaultListener) ExternalAddress() *NetAddress {
  132. return l.extAddr
  133. }
  134. // NOTE: The returned listener is already Accept()'ing.
  135. // So it's not suitable to pass into http.Serve().
  136. func (l *DefaultListener) NetListener() net.Listener {
  137. return l.listener
  138. }
  139. func (l *DefaultListener) String() string {
  140. return fmt.Sprintf("Listener(@%v)", l.extAddr)
  141. }
  142. /* external address helpers */
  143. // UPNP external address discovery & port mapping
  144. func getUPNPExternalAddress(externalPort, internalPort int, logger log.Logger) *NetAddress {
  145. logger.Info("Getting UPNP external address")
  146. nat, err := upnp.Discover()
  147. if err != nil {
  148. logger.Info("Could not perform UPNP discover", "err", err)
  149. return nil
  150. }
  151. ext, err := nat.GetExternalAddress()
  152. if err != nil {
  153. logger.Info("Could not get UPNP external address", "err", err)
  154. return nil
  155. }
  156. // UPnP can't seem to get the external port, so let's just be explicit.
  157. if externalPort == 0 {
  158. externalPort = defaultExternalPort
  159. }
  160. externalPort, err = nat.AddPortMapping("tcp", externalPort, internalPort, "tendermint", 0)
  161. if err != nil {
  162. logger.Info("Could not add UPNP port mapping", "err", err)
  163. return nil
  164. }
  165. logger.Info("Got UPNP external address", "address", ext)
  166. return NewNetAddressIPPort(ext, uint16(externalPort))
  167. }
  168. // TODO: use syscalls: see issue #712
  169. func getNaiveExternalAddress(port int, settleForLocal bool, logger log.Logger) *NetAddress {
  170. addrs, err := net.InterfaceAddrs()
  171. if err != nil {
  172. cmn.PanicCrisis(cmn.Fmt("Could not fetch interface addresses: %v", err))
  173. }
  174. for _, a := range addrs {
  175. ipnet, ok := a.(*net.IPNet)
  176. if !ok {
  177. continue
  178. }
  179. v4 := ipnet.IP.To4()
  180. if v4 == nil || (!settleForLocal && v4[0] == 127) {
  181. continue
  182. } // loopback
  183. return NewNetAddressIPPort(ipnet.IP, uint16(port))
  184. }
  185. // try again, but settle for local
  186. logger.Info("Node may not be connected to internet. Settling for local address")
  187. return getNaiveExternalAddress(port, true, logger)
  188. }