TCPConn.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. }
  68. return conn, nil
  69. }
  70. }
  71. // interruptibleTCPDial establishes a TCP network connection. A conn is added
  72. // to config.PendingConns before blocking on network I/O, which enables interruption.
  73. // The caller is responsible for removing an established conn from PendingConns.
  74. // An upstream proxy is used when specified.
  75. //
  76. // Note: do not to set a UpstreamProxyUrl in the config when using
  77. // NewTCPDialer as a custom dialer for NewProxyAuthTransport (or http.Transport
  78. // with a ProxyUrl), as that would result in double proxy chaining.
  79. //
  80. // Note: interruption does not actually cancel a connection in progress; it
  81. // stops waiting for the goroutine blocking on connect()/Dial.
  82. func interruptibleTCPDial(addr string, config *DialConfig) (*TCPConn, error) {
  83. // Buffers the first result; senders should discard results when
  84. // sending would block, as that means the first result is already set.
  85. conn := &TCPConn{dialResult: make(chan error, 1)}
  86. // Enable interruption
  87. if config.PendingConns != nil && !config.PendingConns.Add(conn) {
  88. return nil, ContextError(errors.New("pending connections already closed"))
  89. }
  90. // Call the blocking Connect() in a goroutine. ConnectTimeout is handled
  91. // in the platform-specific tcpDial helper function.
  92. // Note: since this goroutine may be left running after an interrupt, don't
  93. // call Notice() or perform other actions unexpected after a Controller stops.
  94. // The lifetime of the goroutine may depend on the host OS TCP connect timeout
  95. // when tcpDial, amoung other things, when makes a blocking syscall.Connect()
  96. // call.
  97. go func() {
  98. var netConn net.Conn
  99. var err error
  100. if config.UpstreamProxyUrl != "" {
  101. netConn, err = proxiedTcpDial(addr, config, conn.dialResult)
  102. } else {
  103. netConn, err = tcpDial(addr, config, conn.dialResult)
  104. }
  105. // Mutex is necessary for referencing conn.isClosed and conn.Conn as
  106. // TCPConn.Close may be called while this goroutine is running.
  107. conn.mutex.Lock()
  108. // If already interrupted, cleanup the net.Conn resource and discard.
  109. if conn.isClosed && netConn != nil {
  110. netConn.Close()
  111. conn.mutex.Unlock()
  112. return
  113. }
  114. conn.Conn = netConn
  115. conn.mutex.Unlock()
  116. select {
  117. case conn.dialResult <- err:
  118. default:
  119. }
  120. }()
  121. // Wait until Dial completes (or times out) or until interrupt
  122. err := <-conn.dialResult
  123. if err != nil {
  124. return nil, ContextError(err)
  125. }
  126. return conn, nil
  127. }
  128. // proxiedTcpDial wraps a tcpDial call in an upstreamproxy dial.
  129. func proxiedTcpDial(
  130. addr string, config *DialConfig, dialResult chan error) (net.Conn, error) {
  131. dialer := func(network, addr string) (net.Conn, error) {
  132. return tcpDial(addr, config, dialResult)
  133. }
  134. upstreamDialer := upstreamproxy.NewProxyDialFunc(
  135. &upstreamproxy.UpstreamProxyConfig{
  136. ForwardDialFunc: dialer,
  137. ProxyURIString: config.UpstreamProxyUrl,
  138. })
  139. netConn, err := upstreamDialer("tcp", addr)
  140. if _, ok := err.(*upstreamproxy.Error); ok {
  141. NoticeUpstreamProxyError(err)
  142. }
  143. return netConn, err
  144. }
  145. // Close terminates a connected TCPConn or interrupts a dialing TCPConn.
  146. func (conn *TCPConn) Close() (err error) {
  147. conn.mutex.Lock()
  148. defer conn.mutex.Unlock()
  149. if conn.isClosed {
  150. return
  151. }
  152. conn.isClosed = true
  153. if conn.Conn != nil {
  154. err = conn.Conn.Close()
  155. }
  156. select {
  157. case conn.dialResult <- errors.New("dial interrupted"):
  158. default:
  159. }
  160. return err
  161. }