TCPConn.go 5.6 KB

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