TCPConn.go 5.2 KB

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