TCPConn.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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/common"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/upstreamproxy"
  26. )
  27. // TCPConn is a customized TCP connection that:
  28. // - can be interrupted while dialing;
  29. // - implements a connect timeout;
  30. // - uses an upstream proxy when specified, and includes
  31. // upstream proxy dialing in the connect timeout;
  32. // - can be bound to a specific system device (for Android VpnService
  33. // routing compatibility, for example);
  34. type TCPConn struct {
  35. net.Conn
  36. mutex sync.Mutex
  37. isClosed bool
  38. dialResult chan error
  39. }
  40. // NewTCPDialer creates a TCPDialer.
  41. func NewTCPDialer(config *DialConfig) Dialer {
  42. return makeTCPDialer(config)
  43. }
  44. // DialTCP creates a new, connected TCPConn.
  45. func DialTCP(addr string, config *DialConfig) (conn net.Conn, err error) {
  46. return makeTCPDialer(config)("tcp", addr)
  47. }
  48. // makeTCPDialer creates a custom dialer which creates TCPConn.
  49. func makeTCPDialer(config *DialConfig) func(network, addr string) (net.Conn, error) {
  50. return func(network, addr string) (net.Conn, error) {
  51. if network != "tcp" {
  52. return nil, errors.New("unsupported network type in TCPConn dialer")
  53. }
  54. conn, err := interruptibleTCPDial(addr, config)
  55. if err != nil {
  56. return nil, common.ContextError(err)
  57. }
  58. // Note: when an upstream proxy is used, we don't know what IP address
  59. // was resolved, by the proxy, for that destination.
  60. if config.ResolvedIPCallback != nil && config.UpstreamProxyUrl == "" {
  61. ipAddress := common.IPAddressFromAddr(conn.RemoteAddr())
  62. if ipAddress != "" {
  63. config.ResolvedIPCallback(ipAddress)
  64. }
  65. }
  66. return conn, nil
  67. }
  68. }
  69. // interruptibleTCPDial establishes a TCP network connection. A conn is added
  70. // to config.PendingConns before blocking on network I/O, which enables interruption.
  71. // The caller is responsible for removing an established conn from PendingConns.
  72. // An upstream proxy is used when specified.
  73. //
  74. // Note: do not to set a UpstreamProxyUrl in the config when using
  75. // NewTCPDialer as a custom dialer for NewProxyAuthTransport (or http.Transport
  76. // with a ProxyUrl), as that would result in double proxy chaining.
  77. //
  78. // Note: interruption does not actually cancel a connection in progress; it
  79. // stops waiting for the goroutine blocking on connect()/Dial.
  80. func interruptibleTCPDial(addr string, config *DialConfig) (*TCPConn, error) {
  81. // Buffers the first result; senders should discard results when
  82. // sending would block, as that means the first result is already set.
  83. conn := &TCPConn{dialResult: make(chan error, 1)}
  84. // Enable interruption
  85. if config.PendingConns != nil && !config.PendingConns.Add(conn) {
  86. return nil, common.ContextError(errors.New("pending connections already closed"))
  87. }
  88. // Call the blocking Connect() in a goroutine. ConnectTimeout is handled
  89. // in the platform-specific tcpDial helper function.
  90. // Note: since this goroutine may be left running after an interrupt, don't
  91. // call Notice() or perform other actions unexpected after a Controller stops.
  92. // The lifetime of the goroutine may depend on the host OS TCP connect timeout
  93. // when tcpDial, amoung other things, when makes a blocking syscall.Connect()
  94. // call.
  95. go func() {
  96. var netConn net.Conn
  97. var err error
  98. if config.UpstreamProxyUrl != "" {
  99. netConn, err = proxiedTcpDial(addr, config, conn.dialResult)
  100. } else {
  101. netConn, err = tcpDial(addr, config, conn.dialResult)
  102. }
  103. // Mutex is necessary for referencing conn.isClosed and conn.Conn as
  104. // TCPConn.Close may be called while this goroutine is running.
  105. conn.mutex.Lock()
  106. // If already interrupted, cleanup the net.Conn resource and discard.
  107. if conn.isClosed && netConn != nil {
  108. netConn.Close()
  109. conn.mutex.Unlock()
  110. return
  111. }
  112. conn.Conn = netConn
  113. conn.mutex.Unlock()
  114. select {
  115. case conn.dialResult <- err:
  116. default:
  117. }
  118. }()
  119. // Wait until Dial completes (or times out) or until interrupt
  120. err := <-conn.dialResult
  121. if err != nil {
  122. if config.PendingConns != nil {
  123. config.PendingConns.Remove(conn)
  124. }
  125. return nil, common.ContextError(err)
  126. }
  127. // TODO: now allow conn.dialResult to be garbage collected?
  128. return conn, nil
  129. }
  130. // proxiedTcpDial wraps a tcpDial call in an upstreamproxy dial.
  131. func proxiedTcpDial(
  132. addr string, config *DialConfig, dialResult chan error) (net.Conn, error) {
  133. dialer := func(network, addr string) (net.Conn, error) {
  134. return tcpDial(addr, config, dialResult)
  135. }
  136. upstreamDialer := upstreamproxy.NewProxyDialFunc(
  137. &upstreamproxy.UpstreamProxyConfig{
  138. ForwardDialFunc: dialer,
  139. ProxyURIString: config.UpstreamProxyUrl,
  140. CustomHeaders: config.UpstreamProxyCustomHeaders,
  141. })
  142. netConn, err := upstreamDialer("tcp", addr)
  143. if _, ok := err.(*upstreamproxy.Error); ok {
  144. NoticeUpstreamProxyError(err)
  145. }
  146. return netConn, err
  147. }
  148. // Close terminates a connected TCPConn or interrupts a dialing TCPConn.
  149. func (conn *TCPConn) Close() (err error) {
  150. conn.mutex.Lock()
  151. defer conn.mutex.Unlock()
  152. if conn.isClosed {
  153. return
  154. }
  155. conn.isClosed = true
  156. if conn.Conn != nil {
  157. err = conn.Conn.Close()
  158. }
  159. select {
  160. case conn.dialResult <- errors.New("dial interrupted"):
  161. default:
  162. }
  163. return err
  164. }