TCPConn.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. "context"
  22. std_errors "errors"
  23. "net"
  24. "sync/atomic"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/upstreamproxy"
  29. )
  30. // TCPConn is a customized TCP connection that supports the Closer interface
  31. // and which may be created using options in DialConfig, including
  32. // UpstreamProxyURL, DeviceBinder, IPv6Synthesizer, and ResolvedIPCallback.
  33. // DeviceBinder is implemented using SO_BINDTODEVICE/IP_BOUND_IF, which
  34. // requires syscall-level socket code.
  35. type TCPConn struct {
  36. net.Conn
  37. isClosed int32
  38. }
  39. // NewTCPDialer creates a TCP Dialer.
  40. //
  41. // Note: do not set an UpstreamProxyURL in the config when using NewTCPDialer
  42. // as a custom dialer for NewProxyAuthTransport (or http.Transport with a
  43. // ProxyUrl), as that would result in double proxy chaining.
  44. func NewTCPDialer(config *DialConfig) common.Dialer {
  45. // Use config.CustomDialer when set. This ignores all other parameters in
  46. // DialConfig.
  47. if config.CustomDialer != nil {
  48. return config.CustomDialer
  49. }
  50. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  51. if network != "tcp" {
  52. return nil, errors.Tracef("%s unsupported", network)
  53. }
  54. return DialTCP(ctx, addr, config)
  55. }
  56. }
  57. // DialTCP creates a new, connected TCPConn.
  58. func DialTCP(
  59. ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  60. var conn net.Conn
  61. var err error
  62. if config.UpstreamProxyURL != "" {
  63. conn, err = proxiedTcpDial(ctx, addr, config)
  64. } else {
  65. conn, err = tcpDial(ctx, addr, config)
  66. }
  67. if err != nil {
  68. return nil, errors.Trace(err)
  69. }
  70. // Note: when an upstream proxy is used, we don't know what IP address
  71. // was resolved, by the proxy, for that destination.
  72. if config.ResolvedIPCallback != nil && config.UpstreamProxyURL == "" {
  73. ipAddress := common.IPAddressFromAddr(conn.RemoteAddr())
  74. if ipAddress != "" {
  75. config.ResolvedIPCallback(ipAddress)
  76. }
  77. }
  78. if config.FragmentorConfig.MayFragment() {
  79. conn = fragmentor.NewConn(
  80. config.FragmentorConfig,
  81. func(message string) {
  82. NoticeFragmentor(config.DiagnosticID, message)
  83. },
  84. conn)
  85. }
  86. return conn, nil
  87. }
  88. // proxiedTcpDial wraps a tcpDial call in an upstreamproxy dial.
  89. func proxiedTcpDial(
  90. ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  91. interruptConns := common.NewConns()
  92. // Note: using interruptConns to interrupt a proxy dial assumes
  93. // that the underlying proxy code will immediately exit with an
  94. // error when all underlying conns unexpectedly close; e.g.,
  95. // the proxy handshake won't keep retrying to dial new conns.
  96. dialer := func(network, addr string) (net.Conn, error) {
  97. conn, err := tcpDial(ctx, addr, config)
  98. if conn != nil {
  99. if !interruptConns.Add(conn) {
  100. err = std_errors.New("already interrupted")
  101. conn.Close()
  102. conn = nil
  103. }
  104. }
  105. if err != nil {
  106. return nil, errors.Trace(err)
  107. }
  108. return conn, nil
  109. }
  110. upstreamDialer := upstreamproxy.NewProxyDialFunc(
  111. &upstreamproxy.UpstreamProxyConfig{
  112. ForwardDialFunc: dialer,
  113. ProxyURIString: config.UpstreamProxyURL,
  114. CustomHeaders: config.CustomHeaders,
  115. })
  116. type upstreamDialResult struct {
  117. conn net.Conn
  118. err error
  119. }
  120. resultChannel := make(chan upstreamDialResult)
  121. go func() {
  122. conn, err := upstreamDialer("tcp", addr)
  123. if _, ok := err.(*upstreamproxy.Error); ok {
  124. if config.UpstreamProxyErrorCallback != nil {
  125. config.UpstreamProxyErrorCallback(err)
  126. }
  127. }
  128. resultChannel <- upstreamDialResult{
  129. conn: conn,
  130. err: err,
  131. }
  132. }()
  133. var result upstreamDialResult
  134. select {
  135. case result = <-resultChannel:
  136. case <-ctx.Done():
  137. result.err = ctx.Err()
  138. // Interrupt the goroutine
  139. interruptConns.CloseAll()
  140. <-resultChannel
  141. }
  142. if result.err != nil {
  143. return nil, errors.Trace(result.err)
  144. }
  145. return result.conn, nil
  146. }
  147. // Close terminates a connected TCPConn or interrupts a dialing TCPConn.
  148. func (conn *TCPConn) Close() (err error) {
  149. if !atomic.CompareAndSwapInt32(&conn.isClosed, 0, 1) {
  150. return nil
  151. }
  152. return conn.Conn.Close()
  153. }
  154. // IsClosed implements the Closer iterface. The return value
  155. // indicates whether the TCPConn has been closed.
  156. func (conn *TCPConn) IsClosed() bool {
  157. return atomic.LoadInt32(&conn.isClosed) == 1
  158. }
  159. // CloseWrite calls net.TCPConn.CloseWrite when the underlying
  160. // conn is a *net.TCPConn.
  161. func (conn *TCPConn) CloseWrite() (err error) {
  162. if conn.IsClosed() {
  163. return errors.TraceNew("already closed")
  164. }
  165. tcpConn, ok := conn.Conn.(*net.TCPConn)
  166. if !ok {
  167. return errors.TraceNew("conn is not a *net.TCPConn")
  168. }
  169. return tcpConn.CloseWrite()
  170. }