TCPConn.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. "syscall"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/upstreamproxy"
  31. )
  32. // TCPConn is a customized TCP connection that supports the Closer interface
  33. // and which may be created using options in DialConfig, including
  34. // UpstreamProxyURL, DeviceBinder, IPv6Synthesizer, and ResolvedIPCallback.
  35. // DeviceBinder is implemented using SO_BINDTODEVICE/IP_BOUND_IF, which
  36. // requires syscall-level socket code.
  37. type TCPConn struct {
  38. net.Conn
  39. isClosed int32
  40. }
  41. // NewTCPDialer creates a TCP Dialer.
  42. //
  43. // Note: do not set an UpstreamProxyURL in the config when using NewTCPDialer
  44. // as a custom dialer for NewProxyAuthTransport (or http.Transport with a
  45. // ProxyUrl), as that would result in double proxy chaining.
  46. func NewTCPDialer(config *DialConfig) common.Dialer {
  47. // Use config.CustomDialer when set. This ignores all other parameters in
  48. // DialConfig.
  49. if config.CustomDialer != nil {
  50. return config.CustomDialer
  51. }
  52. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  53. if network != "tcp" {
  54. return nil, errors.Tracef("%s unsupported", network)
  55. }
  56. return DialTCP(ctx, addr, config)
  57. }
  58. }
  59. // DialTCP creates a new, connected TCPConn.
  60. func DialTCP(
  61. ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  62. var conn net.Conn
  63. var err error
  64. if config.UpstreamProxyURL != "" {
  65. conn, err = proxiedTcpDial(ctx, addr, config)
  66. } else {
  67. conn, err = tcpDial(ctx, addr, config)
  68. }
  69. if err != nil {
  70. return nil, errors.Trace(err)
  71. }
  72. // Note: when an upstream proxy is used, we don't know what IP address
  73. // was resolved, by the proxy, for that destination.
  74. if config.ResolvedIPCallback != nil && config.UpstreamProxyURL == "" {
  75. ipAddress := common.IPAddressFromAddr(conn.RemoteAddr())
  76. if ipAddress != "" {
  77. config.ResolvedIPCallback(ipAddress)
  78. }
  79. }
  80. if config.FragmentorConfig.MayFragment() {
  81. conn = fragmentor.NewConn(
  82. config.FragmentorConfig,
  83. func(message string) {
  84. NoticeFragmentor(config.DiagnosticID, message)
  85. },
  86. conn)
  87. }
  88. return conn, nil
  89. }
  90. // proxiedTcpDial wraps a tcpDial call in an upstreamproxy dial.
  91. func proxiedTcpDial(
  92. ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  93. interruptConns := common.NewConns[net.Conn]()
  94. // Note: using interruptConns to interrupt a proxy dial assumes
  95. // that the underlying proxy code will immediately exit with an
  96. // error when all underlying conns unexpectedly close; e.g.,
  97. // the proxy handshake won't keep retrying to dial new conns.
  98. dialer := func(network, addr string) (net.Conn, error) {
  99. conn, err := tcpDial(ctx, addr, config)
  100. if conn != nil {
  101. if !interruptConns.Add(conn) {
  102. err = std_errors.New("already interrupted")
  103. conn.Close()
  104. conn = nil
  105. }
  106. }
  107. if err != nil {
  108. return nil, errors.Trace(err)
  109. }
  110. return conn, nil
  111. }
  112. upstreamDialer := upstreamproxy.NewProxyDialFunc(
  113. &upstreamproxy.UpstreamProxyConfig{
  114. ForwardDialFunc: dialer,
  115. ProxyURIString: config.UpstreamProxyURL,
  116. CustomHeaders: config.CustomHeaders,
  117. })
  118. type upstreamDialResult struct {
  119. conn net.Conn
  120. err error
  121. }
  122. resultChannel := make(chan upstreamDialResult)
  123. go func() {
  124. conn, err := upstreamDialer("tcp", addr)
  125. if _, ok := err.(*upstreamproxy.Error); ok {
  126. if config.UpstreamProxyErrorCallback != nil {
  127. config.UpstreamProxyErrorCallback(err)
  128. }
  129. }
  130. resultChannel <- upstreamDialResult{
  131. conn: conn,
  132. err: err,
  133. }
  134. }()
  135. var result upstreamDialResult
  136. select {
  137. case result = <-resultChannel:
  138. case <-ctx.Done():
  139. result.err = ctx.Err()
  140. // Interrupt the goroutine
  141. interruptConns.CloseAll()
  142. <-resultChannel
  143. }
  144. if result.err != nil {
  145. return nil, errors.Trace(result.err)
  146. }
  147. return result.conn, nil
  148. }
  149. // Close terminates a connected TCPConn or interrupts a dialing TCPConn.
  150. func (conn *TCPConn) Close() (err error) {
  151. if !atomic.CompareAndSwapInt32(&conn.isClosed, 0, 1) {
  152. return nil
  153. }
  154. return conn.Conn.Close()
  155. }
  156. // IsClosed implements the Closer iterface. The return value
  157. // indicates whether the TCPConn has been closed.
  158. func (conn *TCPConn) IsClosed() bool {
  159. return atomic.LoadInt32(&conn.isClosed) == 1
  160. }
  161. // CloseWrite calls net.TCPConn.CloseWrite when the underlying
  162. // conn is a *net.TCPConn.
  163. func (conn *TCPConn) CloseWrite() (err error) {
  164. if conn.IsClosed() {
  165. return errors.TraceNew("already closed")
  166. }
  167. tcpConn, ok := conn.Conn.(*net.TCPConn)
  168. if !ok {
  169. return errors.TraceNew("conn is not a *net.TCPConn")
  170. }
  171. return tcpConn.CloseWrite()
  172. }
  173. func tcpDial(ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  174. // Get the remote IP and port, resolving a domain name if necessary
  175. host, port, err := net.SplitHostPort(addr)
  176. if err != nil {
  177. return nil, errors.Trace(err)
  178. }
  179. if config.ResolveIP == nil {
  180. // Fail even if we don't need a resolver for this dial: this is a code
  181. // misconfiguration.
  182. return nil, errors.TraceNew("missing resolver")
  183. }
  184. ipAddrs, err := config.ResolveIP(ctx, host)
  185. if err != nil {
  186. return nil, errors.Trace(err)
  187. }
  188. if len(ipAddrs) < 1 {
  189. return nil, errors.TraceNew("no IP address")
  190. }
  191. // When configured, attempt to synthesize IPv6 addresses from
  192. // an IPv4 addresses for compatibility on DNS64/NAT64 networks.
  193. // If synthesize fails, try the original addresses.
  194. if config.IPv6Synthesizer != nil {
  195. for i, ipAddr := range ipAddrs {
  196. if ipAddr.To4() != nil {
  197. synthesizedIPAddress := config.IPv6Synthesizer.IPv6Synthesize(ipAddr.String())
  198. if synthesizedIPAddress != "" {
  199. synthesizedAddr := net.ParseIP(synthesizedIPAddress)
  200. if synthesizedAddr != nil {
  201. ipAddrs[i] = synthesizedAddr
  202. }
  203. }
  204. }
  205. }
  206. }
  207. // Iterate over a pseudorandom permutation of the destination
  208. // IPs and attempt connections.
  209. //
  210. // Only continue retrying as long as the dial context is not
  211. // done. Unlike net.Dial, we do not fractionalize the context
  212. // deadline, as the dial is generally intended to apply to a
  213. // single attempt. So these serial retries are most useful in
  214. // cases of immediate failure, such as "no route to host"
  215. // errors when a host resolves to both IPv4 and IPv6 but IPv6
  216. // addresses are unreachable.
  217. //
  218. // Retries at higher levels cover other cases: e.g.,
  219. // Controller.remoteServerListFetcher will retry its entire
  220. // operation and tcpDial will try a new permutation; or similarly,
  221. // Controller.establishCandidateGenerator will retry a candidate
  222. // tunnel server dials.
  223. // Don't shuffle or otherwise mutate the slice returned by ResolveIP.
  224. permutedIndexes := prng.Perm(len(ipAddrs))
  225. lastErr := errors.TraceNew("unknown error")
  226. for _, index := range permutedIndexes {
  227. dialer := &net.Dialer{
  228. Control: func(_, _ string, c syscall.RawConn) error {
  229. var controlErr error
  230. err := c.Control(func(fd uintptr) {
  231. socketFD := int(fd)
  232. setAdditionalSocketOptions(socketFD)
  233. if config.BPFProgramInstructions != nil {
  234. err := setSocketBPF(config.BPFProgramInstructions, socketFD)
  235. if err != nil {
  236. controlErr = errors.Tracef("setSocketBPF failed: %s", err)
  237. return
  238. }
  239. }
  240. if config.DeviceBinder != nil {
  241. _, err := config.DeviceBinder.BindToDevice(socketFD)
  242. if err != nil {
  243. controlErr = errors.Tracef("BindToDevice failed: %s", err)
  244. return
  245. }
  246. }
  247. })
  248. if controlErr != nil {
  249. return errors.Trace(controlErr)
  250. }
  251. return errors.Trace(err)
  252. },
  253. }
  254. conn, err := dialer.DialContext(
  255. ctx, "tcp", net.JoinHostPort(ipAddrs[index].String(), port))
  256. if err != nil {
  257. lastErr = errors.Trace(err)
  258. continue
  259. }
  260. return &TCPConn{Conn: conn}, nil
  261. }
  262. return nil, lastErr
  263. }