TCPConn.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. if config.IPv6Synthesizer != nil {
  97. // Synthesize an IPv6 address from an IPv4 one
  98. // This is for compatibility on DNS64/NAT64 networks
  99. host, port, err := net.SplitHostPort(addr)
  100. if err != nil {
  101. select {
  102. case conn.dialResult <- err:
  103. default:
  104. }
  105. return
  106. }
  107. ip := net.ParseIP(host)
  108. if ip != nil && ip.To4() != nil {
  109. synthesizedAddr := config.IPv6Synthesizer.IPv6Synthesize(host)
  110. // If IPv6Synthesize fails we will try dialing with the
  111. // original IPv4 address instead of logging an error. If
  112. // the address is unreachable an error will be emitted
  113. // from tcpDial.
  114. if synthesizedAddr != "" {
  115. addr = net.JoinHostPort(synthesizedAddr, port)
  116. }
  117. }
  118. }
  119. var netConn net.Conn
  120. var err error
  121. if config.UpstreamProxyUrl != "" {
  122. netConn, err = proxiedTcpDial(addr, config)
  123. } else {
  124. netConn, err = tcpDial(addr, config)
  125. }
  126. // Mutex is necessary for referencing conn.isClosed and conn.Conn as
  127. // TCPConn.Close may be called while this goroutine is running.
  128. conn.mutex.Lock()
  129. // If already interrupted, cleanup the net.Conn resource and discard.
  130. if conn.isClosed && netConn != nil {
  131. netConn.Close()
  132. conn.mutex.Unlock()
  133. return
  134. }
  135. conn.Conn = netConn
  136. conn.mutex.Unlock()
  137. select {
  138. case conn.dialResult <- err:
  139. default:
  140. }
  141. }()
  142. // Wait until Dial completes (or times out) or until interrupt
  143. err := <-conn.dialResult
  144. if err != nil {
  145. if config.PendingConns != nil {
  146. config.PendingConns.Remove(conn)
  147. }
  148. return nil, common.ContextError(err)
  149. }
  150. // TODO: now allow conn.dialResult to be garbage collected?
  151. return conn, nil
  152. }
  153. // proxiedTcpDial wraps a tcpDial call in an upstreamproxy dial.
  154. func proxiedTcpDial(
  155. addr string, config *DialConfig) (net.Conn, error) {
  156. dialer := func(network, addr string) (net.Conn, error) {
  157. return tcpDial(addr, config)
  158. }
  159. upstreamDialer := upstreamproxy.NewProxyDialFunc(
  160. &upstreamproxy.UpstreamProxyConfig{
  161. ForwardDialFunc: dialer,
  162. ProxyURIString: config.UpstreamProxyUrl,
  163. CustomHeaders: config.CustomHeaders,
  164. })
  165. netConn, err := upstreamDialer("tcp", addr)
  166. if _, ok := err.(*upstreamproxy.Error); ok {
  167. NoticeUpstreamProxyError(err)
  168. }
  169. return netConn, err
  170. }
  171. // Close terminates a connected TCPConn or interrupts a dialing TCPConn.
  172. func (conn *TCPConn) Close() (err error) {
  173. conn.mutex.Lock()
  174. defer conn.mutex.Unlock()
  175. if conn.isClosed {
  176. return
  177. }
  178. conn.isClosed = true
  179. if conn.Conn != nil {
  180. err = conn.Conn.Close()
  181. }
  182. select {
  183. case conn.dialResult <- errors.New("dial interrupted"):
  184. default:
  185. }
  186. return err
  187. }
  188. // IsClosed implements the Closer iterface. The return value
  189. // indicates whether the TCPConn has been closed.
  190. func (conn *TCPConn) IsClosed() bool {
  191. conn.mutex.Lock()
  192. defer conn.mutex.Unlock()
  193. return conn.isClosed
  194. }
  195. // CloseWrite calls net.TCPConn.CloseWrite when the underlying
  196. // conn is a *net.TCPConn.
  197. func (conn *TCPConn) CloseWrite() (err error) {
  198. conn.mutex.Lock()
  199. defer conn.mutex.Unlock()
  200. if conn.isClosed {
  201. return errors.New("already closed")
  202. }
  203. tcpConn, ok := conn.Conn.(*net.TCPConn)
  204. if !ok {
  205. return errors.New("conn is not a *net.TCPConn")
  206. }
  207. return tcpConn.CloseWrite()
  208. }