TCPConn.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "errors"
  22. "net"
  23. "sync"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/upstreamproxy"
  25. )
  26. // TCPConn is a customized TCP connection that:
  27. // - can be interrupted while dialing;
  28. // - implements a connect timeout;
  29. // - uses an upstream proxy when specified, and includes
  30. // upstream proxy dialing in the connect timeout;
  31. // - can be bound to a specific system device (for Android VpnService
  32. // routing compatibility, for example);
  33. type TCPConn struct {
  34. net.Conn
  35. mutex sync.Mutex
  36. isClosed bool
  37. dialResult chan error
  38. }
  39. // NewTCPDialer creates a TCPDialer.
  40. func NewTCPDialer(config *DialConfig) Dialer {
  41. return makeTCPDialer(config)
  42. }
  43. // DialTCP creates a new, connected TCPConn.
  44. func DialTCP(addr string, config *DialConfig) (conn net.Conn, err error) {
  45. return makeTCPDialer(config)("tcp", addr)
  46. }
  47. // makeTCPDialer creates a custom dialer which creates TCPConn.
  48. func makeTCPDialer(config *DialConfig) func(network, addr string) (net.Conn, error) {
  49. return func(network, addr string) (net.Conn, error) {
  50. if network != "tcp" {
  51. return nil, errors.New("unsupported network type in TCPConn dialer")
  52. }
  53. conn, err := interruptibleTCPDial(addr, config)
  54. if err != nil {
  55. return nil, ContextError(err)
  56. }
  57. // Note: when an upstream proxy is used, we don't know what IP address
  58. // was resolved, by the proxy, for that destination.
  59. if config.ResolvedIPCallback != nil && config.UpstreamProxyUrl == "" {
  60. remoteAddr := conn.RemoteAddr()
  61. if remoteAddr != nil {
  62. host, _, err := net.SplitHostPort(conn.RemoteAddr().String())
  63. if err == nil {
  64. config.ResolvedIPCallback(host)
  65. }
  66. } }
  67. return conn, nil
  68. }
  69. }
  70. // interruptibleTCPDial establishes a TCP network connection. A conn is added
  71. // to config.PendingConns before blocking on network I/O, which enables interruption.
  72. // The caller is responsible for removing an established conn from PendingConns.
  73. // An upstream proxy is used when specified.
  74. //
  75. // Note: do not to set a UpstreamProxyUrl in the config when using
  76. // NewTCPDialer as a custom dialer for NewProxyAuthTransport (or http.Transport
  77. // with a ProxyUrl), as that would result in double proxy chaining.
  78. //
  79. // Note: interruption does not actually cancel a connection in progress; it
  80. // stops waiting for the goroutine blocking on connect()/Dial.
  81. func interruptibleTCPDial(addr string, config *DialConfig) (*TCPConn, error) {
  82. // Buffers the first result; senders should discard results when
  83. // sending would block, as that means the first result is already set.
  84. conn := &TCPConn{dialResult: make(chan error, 1)}
  85. // Enable interruption
  86. if !config.PendingConns.Add(conn) {
  87. return nil, ContextError(errors.New("pending connections already closed"))
  88. }
  89. // Call the blocking Connect() in a goroutine. ConnectTimeout is handled
  90. // in the platform-specific tcpDial helper function.
  91. // Note: since this goroutine may be left running after an interrupt, don't
  92. // call Notice() or perform other actions unexpected after a Controller stops.
  93. // The lifetime of the goroutine may depend on the host OS TCP connect timeout
  94. // when tcpDial, amoung other things, when makes a blocking syscall.Connect()
  95. // call.
  96. go func() {
  97. var netConn net.Conn
  98. var err error
  99. if config.UpstreamProxyUrl != "" {
  100. netConn, err = proxiedTcpDial(addr, config, conn.dialResult)
  101. } else {
  102. netConn, err = tcpDial(addr, config, conn.dialResult)
  103. }
  104. // Mutex is necessary for referencing conn.isClosed and conn.Conn as
  105. // TCPConn.Close may be called while this goroutine is running.
  106. conn.mutex.Lock()
  107. // If already interrupted, cleanup the net.Conn resource and discard.
  108. if conn.isClosed && netConn != nil {
  109. netConn.Close()
  110. conn.mutex.Unlock()
  111. return
  112. }
  113. conn.Conn = netConn
  114. conn.mutex.Unlock()
  115. select {
  116. case conn.dialResult <- err:
  117. default:
  118. }
  119. }()
  120. // Wait until Dial completes (or times out) or until interrupt
  121. err := <-conn.dialResult
  122. if err != nil {
  123. return nil, ContextError(err)
  124. }
  125. return conn, nil
  126. }
  127. // proxiedTcpDial wraps a tcpDial call in an upstreamproxy dial.
  128. func proxiedTcpDial(
  129. addr string, config *DialConfig, dialResult chan error) (net.Conn, error) {
  130. dialer := func(network, addr string) (net.Conn, error) {
  131. return tcpDial(addr, config, dialResult)
  132. }
  133. upstreamDialer := upstreamproxy.NewProxyDialFunc(
  134. &upstreamproxy.UpstreamProxyConfig{
  135. ForwardDialFunc: dialer,
  136. ProxyURIString: config.UpstreamProxyUrl,
  137. })
  138. netConn, err := upstreamDialer("tcp", addr)
  139. if _, ok := err.(*upstreamproxy.Error); ok {
  140. NoticeUpstreamProxyError(err)
  141. }
  142. return netConn, err
  143. }
  144. // Close terminates a connected TCPConn or interrupts a dialing TCPConn.
  145. func (conn *TCPConn) Close() (err error) {
  146. conn.mutex.Lock()
  147. defer conn.mutex.Unlock()
  148. if conn.isClosed {
  149. return
  150. }
  151. conn.isClosed = true
  152. if conn.Conn != nil {
  153. err = conn.Conn.Close()
  154. }
  155. select {
  156. case conn.dialResult <- errors.New("dial interrupted"):
  157. default:
  158. }
  159. return err
  160. }