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.

213 lines
4.7 KiB

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