TCPConn.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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) Dialer {
  45. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  46. if network != "tcp" {
  47. return nil, errors.Tracef("%s unsupported", network)
  48. }
  49. return DialTCP(ctx, addr, config)
  50. }
  51. }
  52. // DialTCP creates a new, connected TCPConn.
  53. func DialTCP(
  54. ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  55. var conn net.Conn
  56. var err error
  57. if config.UpstreamProxyURL != "" {
  58. conn, err = proxiedTcpDial(ctx, addr, config)
  59. } else {
  60. conn, err = tcpDial(ctx, addr, config)
  61. }
  62. if err != nil {
  63. return nil, errors.Trace(err)
  64. }
  65. // Note: when an upstream proxy is used, we don't know what IP address
  66. // was resolved, by the proxy, for that destination.
  67. if config.ResolvedIPCallback != nil && config.UpstreamProxyURL == "" {
  68. ipAddress := common.IPAddressFromAddr(conn.RemoteAddr())
  69. if ipAddress != "" {
  70. config.ResolvedIPCallback(ipAddress)
  71. }
  72. }
  73. if config.FragmentorConfig.MayFragment() {
  74. conn = fragmentor.NewConn(
  75. config.FragmentorConfig,
  76. func(message string) {
  77. NoticeFragmentor(config.DiagnosticID, message)
  78. },
  79. conn)
  80. }
  81. return conn, nil
  82. }
  83. // proxiedTcpDial wraps a tcpDial call in an upstreamproxy dial.
  84. func proxiedTcpDial(
  85. ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  86. interruptConns := common.NewConns()
  87. // Note: using interruptConns to interrupt a proxy dial assumes
  88. // that the underlying proxy code will immediately exit with an
  89. // error when all underlying conns unexpectedly close; e.g.,
  90. // the proxy handshake won't keep retrying to dial new conns.
  91. dialer := func(network, addr string) (net.Conn, error) {
  92. conn, err := tcpDial(ctx, addr, config)
  93. if conn != nil {
  94. if !interruptConns.Add(conn) {
  95. err = std_errors.New("already interrupted")
  96. conn.Close()
  97. conn = nil
  98. }
  99. }
  100. if err != nil {
  101. return nil, errors.Trace(err)
  102. }
  103. return conn, nil
  104. }
  105. upstreamDialer := upstreamproxy.NewProxyDialFunc(
  106. &upstreamproxy.UpstreamProxyConfig{
  107. ForwardDialFunc: dialer,
  108. ProxyURIString: config.UpstreamProxyURL,
  109. CustomHeaders: config.CustomHeaders,
  110. })
  111. type upstreamDialResult struct {
  112. conn net.Conn
  113. err error
  114. }
  115. resultChannel := make(chan upstreamDialResult)
  116. go func() {
  117. conn, err := upstreamDialer("tcp", addr)
  118. if _, ok := err.(*upstreamproxy.Error); ok {
  119. NoticeUpstreamProxyError(err)
  120. }
  121. resultChannel <- upstreamDialResult{
  122. conn: conn,
  123. err: err,
  124. }
  125. }()
  126. var result upstreamDialResult
  127. select {
  128. case result = <-resultChannel:
  129. case <-ctx.Done():
  130. result.err = ctx.Err()
  131. // Interrupt the goroutine
  132. interruptConns.CloseAll()
  133. <-resultChannel
  134. }
  135. if result.err != nil {
  136. return nil, errors.Trace(result.err)
  137. }
  138. return result.conn, nil
  139. }
  140. // Close terminates a connected TCPConn or interrupts a dialing TCPConn.
  141. func (conn *TCPConn) Close() (err error) {
  142. if !atomic.CompareAndSwapInt32(&conn.isClosed, 0, 1) {
  143. return nil
  144. }
  145. return conn.Conn.Close()
  146. }
  147. // IsClosed implements the Closer iterface. The return value
  148. // indicates whether the TCPConn has been closed.
  149. func (conn *TCPConn) IsClosed() bool {
  150. return atomic.LoadInt32(&conn.isClosed) == 1
  151. }
  152. // CloseWrite calls net.TCPConn.CloseWrite when the underlying
  153. // conn is a *net.TCPConn.
  154. func (conn *TCPConn) CloseWrite() (err error) {
  155. if conn.IsClosed() {
  156. return errors.TraceNew("already closed")
  157. }
  158. tcpConn, ok := conn.Conn.(*net.TCPConn)
  159. if !ok {
  160. return errors.TraceNew("conn is not a *net.TCPConn")
  161. }
  162. return tcpConn.CloseWrite()
  163. }