TCPConn.go 4.9 KB

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