tcp_listen.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package connections
  7. import (
  8. "crypto/tls"
  9. "net"
  10. "net/url"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/syncthing/syncthing/lib/dialer"
  15. "github.com/syncthing/syncthing/lib/nat"
  16. )
  17. func init() {
  18. for _, scheme := range []string{"tcp", "tcp4", "tcp6"} {
  19. listeners[scheme] = newTCPListener
  20. }
  21. }
  22. type tcpListener struct {
  23. onAddressesChangedNotifier
  24. uri *url.URL
  25. tlsCfg *tls.Config
  26. stop chan struct{}
  27. conns chan IntermediateConnection
  28. natService *nat.Service
  29. mapping *nat.Mapping
  30. address *url.URL
  31. err error
  32. mut sync.RWMutex
  33. }
  34. func (t *tcpListener) Serve() {
  35. t.mut.Lock()
  36. t.err = nil
  37. t.mut.Unlock()
  38. tcaddr, err := net.ResolveTCPAddr(t.uri.Scheme, t.uri.Host)
  39. if err != nil {
  40. t.mut.Lock()
  41. t.err = err
  42. t.mut.Unlock()
  43. l.Infoln("listen (BEP/tcp):", err)
  44. return
  45. }
  46. listener, err := net.ListenTCP(t.uri.Scheme, tcaddr)
  47. if err != nil {
  48. t.mut.Lock()
  49. t.err = err
  50. t.mut.Unlock()
  51. l.Infoln("listen (BEP/tcp):", err)
  52. return
  53. }
  54. defer listener.Close()
  55. mapping := t.natService.NewMapping(nat.TCP, tcaddr.IP, tcaddr.Port)
  56. mapping.OnChanged(func(_ *nat.Mapping, _, _ []nat.Address) {
  57. t.notifyAddressesChanged(t)
  58. })
  59. defer t.natService.RemoveMapping(mapping)
  60. t.mut.Lock()
  61. t.mapping = mapping
  62. t.mut.Unlock()
  63. for {
  64. listener.SetDeadline(time.Now().Add(time.Second))
  65. conn, err := listener.Accept()
  66. select {
  67. case <-t.stop:
  68. if err == nil {
  69. conn.Close()
  70. }
  71. t.mut.Lock()
  72. t.mapping = nil
  73. t.mut.Unlock()
  74. return
  75. default:
  76. }
  77. if err != nil {
  78. if err, ok := err.(*net.OpError); !ok || !err.Timeout() {
  79. l.Warnln("Accepting connection (BEP/tcp):", err)
  80. }
  81. continue
  82. }
  83. l.Debugln("connect from", conn.RemoteAddr())
  84. err = dialer.SetTCPOptions(conn.(*net.TCPConn))
  85. if err != nil {
  86. l.Infoln(err)
  87. }
  88. tc := tls.Server(conn, t.tlsCfg)
  89. err = tc.Handshake()
  90. if err != nil {
  91. l.Infoln("TLS handshake (BEP/tcp):", err)
  92. tc.Close()
  93. continue
  94. }
  95. t.conns <- IntermediateConnection{tc, "TCP (Server)", tcpPriority}
  96. }
  97. }
  98. func (t *tcpListener) Stop() {
  99. close(t.stop)
  100. }
  101. func (t *tcpListener) URI() *url.URL {
  102. return t.uri
  103. }
  104. func (t *tcpListener) WANAddresses() []*url.URL {
  105. uris := t.LANAddresses()
  106. t.mut.RLock()
  107. if t.mapping != nil {
  108. addrs := t.mapping.ExternalAddresses()
  109. for _, addr := range addrs {
  110. uri := *t.uri
  111. // Does net.JoinHostPort internally
  112. uri.Host = addr.String()
  113. uris = append(uris, &uri)
  114. }
  115. }
  116. t.mut.RUnlock()
  117. return uris
  118. }
  119. func (t *tcpListener) LANAddresses() []*url.URL {
  120. return []*url.URL{t.uri}
  121. }
  122. func (t *tcpListener) Error() error {
  123. t.mut.RLock()
  124. err := t.err
  125. t.mut.RUnlock()
  126. return err
  127. }
  128. func (t *tcpListener) String() string {
  129. return t.uri.String()
  130. }
  131. func newTCPListener(uri *url.URL, tlsCfg *tls.Config, conns chan IntermediateConnection, natService *nat.Service) genericListener {
  132. return &tcpListener{
  133. uri: fixupPort(uri),
  134. tlsCfg: tlsCfg,
  135. conns: conns,
  136. natService: natService,
  137. stop: make(chan struct{}),
  138. }
  139. }
  140. func isPublicIPv4(ip net.IP) bool {
  141. ip = ip.To4()
  142. if ip == nil {
  143. // Not an IPv4 address (IPv6)
  144. return false
  145. }
  146. // IsGlobalUnicast below only checks that it's not link local or
  147. // multicast, and we want to exclude private (NAT:ed) addresses as well.
  148. rfc1918 := []net.IPNet{
  149. {IP: net.IP{10, 0, 0, 0}, Mask: net.IPMask{255, 0, 0, 0}},
  150. {IP: net.IP{172, 16, 0, 0}, Mask: net.IPMask{255, 240, 0, 0}},
  151. {IP: net.IP{192, 168, 0, 0}, Mask: net.IPMask{255, 255, 0, 0}},
  152. }
  153. for _, n := range rfc1918 {
  154. if n.Contains(ip) {
  155. return false
  156. }
  157. }
  158. return ip.IsGlobalUnicast()
  159. }
  160. func isPublicIPv6(ip net.IP) bool {
  161. if ip.To4() != nil {
  162. // Not an IPv6 address (IPv4)
  163. // (To16() returns a v6 mapped v4 address so can't be used to check
  164. // that it's an actual v6 address)
  165. return false
  166. }
  167. return ip.IsGlobalUnicast()
  168. }
  169. func fixupPort(uri *url.URL) *url.URL {
  170. copyURI := *uri
  171. host, port, err := net.SplitHostPort(uri.Host)
  172. if err != nil && strings.HasPrefix(err.Error(), "missing port") {
  173. // addr is on the form "1.2.3.4"
  174. copyURI.Host = net.JoinHostPort(host, "22000")
  175. } else if err == nil && port == "" {
  176. // addr is on the form "1.2.3.4:"
  177. copyURI.Host = net.JoinHostPort(host, "22000")
  178. }
  179. return &copyURI
  180. }