1
0

connector.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. // Copyright 2023 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package client
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "net"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. libnet "github.com/fatedier/golib/net"
  24. fmux "github.com/hashicorp/yamux"
  25. quic "github.com/quic-go/quic-go"
  26. "github.com/samber/lo"
  27. v1 "github.com/fatedier/frp/pkg/config/v1"
  28. "github.com/fatedier/frp/pkg/transport"
  29. netpkg "github.com/fatedier/frp/pkg/util/net"
  30. "github.com/fatedier/frp/pkg/util/xlog"
  31. )
  32. // Connector is an interface for establishing connections to the server.
  33. type Connector interface {
  34. Open() error
  35. Connect() (net.Conn, error)
  36. Close() error
  37. }
  38. // defaultConnectorImpl is the default implementation of Connector for normal frpc.
  39. type defaultConnectorImpl struct {
  40. ctx context.Context
  41. cfg *v1.ClientCommonConfig
  42. muxSession *fmux.Session
  43. quicConn *quic.Conn
  44. closeOnce sync.Once
  45. }
  46. func NewConnector(ctx context.Context, cfg *v1.ClientCommonConfig) Connector {
  47. return &defaultConnectorImpl{
  48. ctx: ctx,
  49. cfg: cfg,
  50. }
  51. }
  52. // Open opens an underlying connection to the server.
  53. // The underlying connection is either a TCP connection or a QUIC connection.
  54. // After the underlying connection is established, you can call Connect() to get a stream.
  55. // If TCPMux isn't enabled, the underlying connection is nil, you will get a new real TCP connection every time you call Connect().
  56. func (c *defaultConnectorImpl) Open() error {
  57. xl := xlog.FromContextSafe(c.ctx)
  58. // special for quic
  59. if strings.EqualFold(c.cfg.Transport.Protocol, "quic") {
  60. var tlsConfig *tls.Config
  61. var err error
  62. sn := c.cfg.Transport.TLS.ServerName
  63. if sn == "" {
  64. sn = c.cfg.ServerAddr
  65. }
  66. if lo.FromPtr(c.cfg.Transport.TLS.Enable) {
  67. tlsConfig, err = transport.NewClientTLSConfig(
  68. c.cfg.Transport.TLS.CertFile,
  69. c.cfg.Transport.TLS.KeyFile,
  70. c.cfg.Transport.TLS.TrustedCaFile,
  71. sn)
  72. } else {
  73. tlsConfig, err = transport.NewClientTLSConfig("", "", "", sn)
  74. }
  75. if err != nil {
  76. xl.Warnf("fail to build tls configuration, err: %v", err)
  77. return err
  78. }
  79. tlsConfig.NextProtos = []string{"frp"}
  80. conn, err := quic.DialAddr(
  81. c.ctx,
  82. net.JoinHostPort(c.cfg.ServerAddr, strconv.Itoa(c.cfg.ServerPort)),
  83. tlsConfig, &quic.Config{
  84. MaxIdleTimeout: time.Duration(c.cfg.Transport.QUIC.MaxIdleTimeout) * time.Second,
  85. MaxIncomingStreams: int64(c.cfg.Transport.QUIC.MaxIncomingStreams),
  86. KeepAlivePeriod: time.Duration(c.cfg.Transport.QUIC.KeepalivePeriod) * time.Second,
  87. })
  88. if err != nil {
  89. return err
  90. }
  91. c.quicConn = conn
  92. return nil
  93. }
  94. if !lo.FromPtr(c.cfg.Transport.TCPMux) {
  95. return nil
  96. }
  97. conn, err := c.realConnect()
  98. if err != nil {
  99. return err
  100. }
  101. fmuxCfg := fmux.DefaultConfig()
  102. fmuxCfg.KeepAliveInterval = time.Duration(c.cfg.Transport.TCPMuxKeepaliveInterval) * time.Second
  103. // Use trace level for yamux logs
  104. fmuxCfg.LogOutput = xlog.NewTraceWriter(xl)
  105. fmuxCfg.MaxStreamWindowSize = 6 * 1024 * 1024
  106. session, err := fmux.Client(conn, fmuxCfg)
  107. if err != nil {
  108. return err
  109. }
  110. c.muxSession = session
  111. return nil
  112. }
  113. // Connect returns a stream from the underlying connection, or a new TCP connection if TCPMux isn't enabled.
  114. func (c *defaultConnectorImpl) Connect() (net.Conn, error) {
  115. if c.quicConn != nil {
  116. stream, err := c.quicConn.OpenStreamSync(context.Background())
  117. if err != nil {
  118. return nil, err
  119. }
  120. return netpkg.QuicStreamToNetConn(stream, c.quicConn), nil
  121. } else if c.muxSession != nil {
  122. stream, err := c.muxSession.OpenStream()
  123. if err != nil {
  124. return nil, err
  125. }
  126. return stream, nil
  127. }
  128. return c.realConnect()
  129. }
  130. func (c *defaultConnectorImpl) realConnect() (net.Conn, error) {
  131. xl := xlog.FromContextSafe(c.ctx)
  132. var tlsConfig *tls.Config
  133. var err error
  134. tlsEnable := lo.FromPtr(c.cfg.Transport.TLS.Enable)
  135. if c.cfg.Transport.Protocol == "wss" {
  136. tlsEnable = true
  137. }
  138. if tlsEnable {
  139. sn := c.cfg.Transport.TLS.ServerName
  140. if sn == "" {
  141. sn = c.cfg.ServerAddr
  142. }
  143. tlsConfig, err = transport.NewClientTLSConfig(
  144. c.cfg.Transport.TLS.CertFile,
  145. c.cfg.Transport.TLS.KeyFile,
  146. c.cfg.Transport.TLS.TrustedCaFile,
  147. sn)
  148. if err != nil {
  149. xl.Warnf("fail to build tls configuration, err: %v", err)
  150. return nil, err
  151. }
  152. }
  153. proxyType, addr, auth, err := libnet.ParseProxyURL(c.cfg.Transport.ProxyURL)
  154. if err != nil {
  155. xl.Errorf("fail to parse proxy url")
  156. return nil, err
  157. }
  158. dialOptions := []libnet.DialOption{}
  159. protocol := c.cfg.Transport.Protocol
  160. switch protocol {
  161. case "websocket":
  162. protocol = "tcp"
  163. dialOptions = append(dialOptions, libnet.WithAfterHook(libnet.AfterHook{Hook: netpkg.DialHookWebsocket(protocol, "")}))
  164. dialOptions = append(dialOptions, libnet.WithAfterHook(libnet.AfterHook{
  165. Hook: netpkg.DialHookCustomTLSHeadByte(tlsConfig != nil, lo.FromPtr(c.cfg.Transport.TLS.DisableCustomTLSFirstByte)),
  166. }))
  167. dialOptions = append(dialOptions, libnet.WithTLSConfig(tlsConfig))
  168. case "wss":
  169. protocol = "tcp"
  170. dialOptions = append(dialOptions, libnet.WithTLSConfigAndPriority(100, tlsConfig))
  171. // Make sure that if it is wss, the websocket hook is executed after the tls hook.
  172. dialOptions = append(dialOptions, libnet.WithAfterHook(libnet.AfterHook{Hook: netpkg.DialHookWebsocket(protocol, tlsConfig.ServerName), Priority: 110}))
  173. default:
  174. dialOptions = append(dialOptions, libnet.WithAfterHook(libnet.AfterHook{
  175. Hook: netpkg.DialHookCustomTLSHeadByte(tlsConfig != nil, lo.FromPtr(c.cfg.Transport.TLS.DisableCustomTLSFirstByte)),
  176. }))
  177. dialOptions = append(dialOptions, libnet.WithTLSConfig(tlsConfig))
  178. }
  179. if c.cfg.Transport.ConnectServerLocalIP != "" {
  180. dialOptions = append(dialOptions, libnet.WithLocalAddr(c.cfg.Transport.ConnectServerLocalIP))
  181. }
  182. dialOptions = append(dialOptions,
  183. libnet.WithProtocol(protocol),
  184. libnet.WithTimeout(time.Duration(c.cfg.Transport.DialServerTimeout)*time.Second),
  185. libnet.WithKeepAlive(time.Duration(c.cfg.Transport.DialServerKeepAlive)*time.Second),
  186. libnet.WithProxy(proxyType, addr),
  187. libnet.WithProxyAuth(auth),
  188. )
  189. conn, err := libnet.DialContext(
  190. c.ctx,
  191. net.JoinHostPort(c.cfg.ServerAddr, strconv.Itoa(c.cfg.ServerPort)),
  192. dialOptions...,
  193. )
  194. return conn, err
  195. }
  196. func (c *defaultConnectorImpl) Close() error {
  197. c.closeOnce.Do(func() {
  198. if c.quicConn != nil {
  199. _ = c.quicConn.CloseWithError(0, "")
  200. }
  201. if c.muxSession != nil {
  202. _ = c.muxSession.Close()
  203. }
  204. })
  205. return nil
  206. }