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. "io"
  19. "net"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. libnet "github.com/fatedier/golib/net"
  25. fmux "github.com/hashicorp/yamux"
  26. quic "github.com/quic-go/quic-go"
  27. "github.com/samber/lo"
  28. v1 "github.com/fatedier/frp/pkg/config/v1"
  29. "github.com/fatedier/frp/pkg/transport"
  30. netpkg "github.com/fatedier/frp/pkg/util/net"
  31. "github.com/fatedier/frp/pkg/util/xlog"
  32. )
  33. // Connector is an interface for establishing connections to the server.
  34. type Connector interface {
  35. Open() error
  36. Connect() (net.Conn, error)
  37. Close() error
  38. }
  39. // defaultConnectorImpl is the default implementation of Connector for normal frpc.
  40. type defaultConnectorImpl struct {
  41. ctx context.Context
  42. cfg *v1.ClientCommonConfig
  43. muxSession *fmux.Session
  44. quicConn quic.Connection
  45. closeOnce sync.Once
  46. }
  47. func NewConnector(ctx context.Context, cfg *v1.ClientCommonConfig) Connector {
  48. return &defaultConnectorImpl{
  49. ctx: ctx,
  50. cfg: cfg,
  51. }
  52. }
  53. // Open opens an underlying connection to the server.
  54. // The underlying connection is either a TCP connection or a QUIC connection.
  55. // After the underlying connection is established, you can call Connect() to get a stream.
  56. // If TCPMux isn't enabled, the underlying connection is nil, you will get a new real TCP connection every time you call Connect().
  57. func (c *defaultConnectorImpl) Open() error {
  58. xl := xlog.FromContextSafe(c.ctx)
  59. // special for quic
  60. if strings.EqualFold(c.cfg.Transport.Protocol, "quic") {
  61. var tlsConfig *tls.Config
  62. var err error
  63. sn := c.cfg.Transport.TLS.ServerName
  64. if sn == "" {
  65. sn = c.cfg.ServerAddr
  66. }
  67. if lo.FromPtr(c.cfg.Transport.TLS.Enable) {
  68. tlsConfig, err = transport.NewClientTLSConfig(
  69. c.cfg.Transport.TLS.CertFile,
  70. c.cfg.Transport.TLS.KeyFile,
  71. c.cfg.Transport.TLS.TrustedCaFile,
  72. sn)
  73. } else {
  74. tlsConfig, err = transport.NewClientTLSConfig("", "", "", sn)
  75. }
  76. if err != nil {
  77. xl.Warnf("fail to build tls configuration, err: %v", err)
  78. return err
  79. }
  80. tlsConfig.NextProtos = []string{"frp"}
  81. conn, err := quic.DialAddr(
  82. c.ctx,
  83. net.JoinHostPort(c.cfg.ServerAddr, strconv.Itoa(c.cfg.ServerPort)),
  84. tlsConfig, &quic.Config{
  85. MaxIdleTimeout: time.Duration(c.cfg.Transport.QUIC.MaxIdleTimeout) * time.Second,
  86. MaxIncomingStreams: int64(c.cfg.Transport.QUIC.MaxIncomingStreams),
  87. KeepAlivePeriod: time.Duration(c.cfg.Transport.QUIC.KeepalivePeriod) * time.Second,
  88. })
  89. if err != nil {
  90. return err
  91. }
  92. c.quicConn = conn
  93. return nil
  94. }
  95. if !lo.FromPtr(c.cfg.Transport.TCPMux) {
  96. return nil
  97. }
  98. conn, err := c.realConnect()
  99. if err != nil {
  100. return err
  101. }
  102. fmuxCfg := fmux.DefaultConfig()
  103. fmuxCfg.KeepAliveInterval = time.Duration(c.cfg.Transport.TCPMuxKeepaliveInterval) * time.Second
  104. fmuxCfg.LogOutput = io.Discard
  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. }