TCPConn.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. "errors"
  23. "fmt"
  24. "net"
  25. "sync/atomic"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  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, common.ContextError(fmt.Errorf("%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, common.ContextError(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.IsFragmenting() {
  74. conn = fragmentor.NewConn(
  75. config.FragmentorConfig,
  76. func(message string) { NoticeInfo(message) },
  77. conn)
  78. }
  79. return conn, nil
  80. }
  81. // proxiedTcpDial wraps a tcpDial call in an upstreamproxy dial.
  82. func proxiedTcpDial(
  83. ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  84. interruptConns := common.NewConns()
  85. // Note: using interruptConns to interrupt a proxy dial assumes
  86. // that the underlying proxy code will immediately exit with an
  87. // error when all underlying conns unexpectedly close; e.g.,
  88. // the proxy handshake won't keep retrying to dial new conns.
  89. dialer := func(network, addr string) (net.Conn, error) {
  90. conn, err := tcpDial(ctx, addr, config)
  91. if conn != nil {
  92. if !interruptConns.Add(conn) {
  93. err = errors.New("already interrupted")
  94. conn.Close()
  95. conn = nil
  96. }
  97. }
  98. if err != nil {
  99. return nil, common.ContextError(err)
  100. }
  101. return conn, nil
  102. }
  103. upstreamDialer := upstreamproxy.NewProxyDialFunc(
  104. &upstreamproxy.UpstreamProxyConfig{
  105. ForwardDialFunc: dialer,
  106. ProxyURIString: config.UpstreamProxyURL,
  107. CustomHeaders: config.CustomHeaders,
  108. })
  109. type upstreamDialResult struct {
  110. conn net.Conn
  111. err error
  112. }
  113. resultChannel := make(chan upstreamDialResult)
  114. go func() {
  115. conn, err := upstreamDialer("tcp", addr)
  116. if _, ok := err.(*upstreamproxy.Error); ok {
  117. NoticeUpstreamProxyError(err)
  118. }
  119. resultChannel <- upstreamDialResult{
  120. conn: conn,
  121. err: err,
  122. }
  123. }()
  124. var result upstreamDialResult
  125. select {
  126. case result = <-resultChannel:
  127. case <-ctx.Done():
  128. result.err = ctx.Err()
  129. // Interrupt the goroutine
  130. interruptConns.CloseAll()
  131. <-resultChannel
  132. }
  133. if result.err != nil {
  134. return nil, common.ContextError(result.err)
  135. }
  136. return result.conn, nil
  137. }
  138. // Close terminates a connected TCPConn or interrupts a dialing TCPConn.
  139. func (conn *TCPConn) Close() (err error) {
  140. if !atomic.CompareAndSwapInt32(&conn.isClosed, 0, 1) {
  141. return nil
  142. }
  143. return conn.Conn.Close()
  144. }
  145. // IsClosed implements the Closer iterface. The return value
  146. // indicates whether the TCPConn has been closed.
  147. func (conn *TCPConn) IsClosed() bool {
  148. return atomic.LoadInt32(&conn.isClosed) == 1
  149. }
  150. // CloseWrite calls net.TCPConn.CloseWrite when the underlying
  151. // conn is a *net.TCPConn.
  152. func (conn *TCPConn) CloseWrite() (err error) {
  153. if conn.IsClosed() {
  154. return common.ContextError(errors.New("already closed"))
  155. }
  156. tcpConn, ok := conn.Conn.(*net.TCPConn)
  157. if !ok {
  158. return common.ContextError(errors.New("conn is not a *net.TCPConn"))
  159. }
  160. return tcpConn.CloseWrite()
  161. }