proxy.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  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 proxy
  15. import (
  16. "context"
  17. "io"
  18. "net"
  19. "reflect"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. libio "github.com/fatedier/golib/io"
  25. libdial "github.com/fatedier/golib/net/dial"
  26. pp "github.com/pires/go-proxyproto"
  27. "golang.org/x/time/rate"
  28. "github.com/fatedier/frp/pkg/config/types"
  29. v1 "github.com/fatedier/frp/pkg/config/v1"
  30. "github.com/fatedier/frp/pkg/msg"
  31. plugin "github.com/fatedier/frp/pkg/plugin/client"
  32. "github.com/fatedier/frp/pkg/transport"
  33. "github.com/fatedier/frp/pkg/util/limit"
  34. "github.com/fatedier/frp/pkg/util/xlog"
  35. )
  36. var proxyFactoryRegistry = map[reflect.Type]func(*BaseProxy, v1.ProxyConfigurer) Proxy{}
  37. func RegisterProxyFactory(proxyConfType reflect.Type, factory func(*BaseProxy, v1.ProxyConfigurer) Proxy) {
  38. proxyFactoryRegistry[proxyConfType] = factory
  39. }
  40. // Proxy defines how to handle work connections for different proxy type.
  41. type Proxy interface {
  42. Run() error
  43. // InWorkConn accept work connections registered to server.
  44. InWorkConn(net.Conn, *msg.StartWorkConn)
  45. Close()
  46. }
  47. func NewProxy(
  48. ctx context.Context,
  49. pxyConf v1.ProxyConfigurer,
  50. clientCfg *v1.ClientCommonConfig,
  51. msgTransporter transport.MessageTransporter,
  52. ) (pxy Proxy) {
  53. var limiter *rate.Limiter
  54. limitBytes := pxyConf.GetBaseConfig().Transport.BandwidthLimit.Bytes()
  55. if limitBytes > 0 && pxyConf.GetBaseConfig().Transport.BandwidthLimitMode == types.BandwidthLimitModeClient {
  56. limiter = rate.NewLimiter(rate.Limit(float64(limitBytes)), int(limitBytes))
  57. }
  58. baseProxy := BaseProxy{
  59. baseCfg: pxyConf.GetBaseConfig(),
  60. clientCfg: clientCfg,
  61. limiter: limiter,
  62. msgTransporter: msgTransporter,
  63. xl: xlog.FromContextSafe(ctx),
  64. ctx: ctx,
  65. }
  66. factory := proxyFactoryRegistry[reflect.TypeOf(pxyConf)]
  67. if factory == nil {
  68. return nil
  69. }
  70. return factory(&baseProxy, pxyConf)
  71. }
  72. type BaseProxy struct {
  73. baseCfg *v1.ProxyBaseConfig
  74. clientCfg *v1.ClientCommonConfig
  75. msgTransporter transport.MessageTransporter
  76. limiter *rate.Limiter
  77. // proxyPlugin is used to handle connections instead of dialing to local service.
  78. // It's only validate for TCP protocol now.
  79. proxyPlugin plugin.Plugin
  80. mu sync.RWMutex
  81. xl *xlog.Logger
  82. ctx context.Context
  83. }
  84. func (pxy *BaseProxy) Run() error {
  85. if pxy.baseCfg.Plugin.Type != "" {
  86. p, err := plugin.Create(pxy.baseCfg.Plugin.Type, pxy.baseCfg.Plugin.ClientPluginOptions)
  87. if err != nil {
  88. return err
  89. }
  90. pxy.proxyPlugin = p
  91. }
  92. return nil
  93. }
  94. func (pxy *BaseProxy) Close() {
  95. if pxy.proxyPlugin != nil {
  96. pxy.proxyPlugin.Close()
  97. }
  98. }
  99. func (pxy *BaseProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  100. pxy.HandleTCPWorkConnection(conn, m, []byte(pxy.clientCfg.Auth.Token))
  101. }
  102. // Common handler for tcp work connections.
  103. func (pxy *BaseProxy) HandleTCPWorkConnection(workConn net.Conn, m *msg.StartWorkConn, encKey []byte) {
  104. xl := pxy.xl
  105. baseCfg := pxy.baseCfg
  106. var (
  107. remote io.ReadWriteCloser
  108. err error
  109. )
  110. remote = workConn
  111. if pxy.limiter != nil {
  112. remote = libio.WrapReadWriteCloser(limit.NewReader(workConn, pxy.limiter), limit.NewWriter(workConn, pxy.limiter), func() error {
  113. return workConn.Close()
  114. })
  115. }
  116. xl.Trace("handle tcp work connection, use_encryption: %t, use_compression: %t",
  117. baseCfg.Transport.UseEncryption, baseCfg.Transport.UseCompression)
  118. if baseCfg.Transport.UseEncryption {
  119. remote, err = libio.WithEncryption(remote, encKey)
  120. if err != nil {
  121. workConn.Close()
  122. xl.Error("create encryption stream error: %v", err)
  123. return
  124. }
  125. }
  126. var compressionResourceRecycleFn func()
  127. if baseCfg.Transport.UseCompression {
  128. remote, compressionResourceRecycleFn = libio.WithCompressionFromPool(remote)
  129. }
  130. // check if we need to send proxy protocol info
  131. var extraInfo plugin.ExtraInfo
  132. if baseCfg.Transport.ProxyProtocolVersion != "" {
  133. if m.SrcAddr != "" && m.SrcPort != 0 {
  134. if m.DstAddr == "" {
  135. m.DstAddr = "127.0.0.1"
  136. }
  137. srcAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.SrcAddr, strconv.Itoa(int(m.SrcPort))))
  138. dstAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.DstAddr, strconv.Itoa(int(m.DstPort))))
  139. h := &pp.Header{
  140. Command: pp.PROXY,
  141. SourceAddr: srcAddr,
  142. DestinationAddr: dstAddr,
  143. }
  144. if strings.Contains(m.SrcAddr, ".") {
  145. h.TransportProtocol = pp.TCPv4
  146. } else {
  147. h.TransportProtocol = pp.TCPv6
  148. }
  149. if baseCfg.Transport.ProxyProtocolVersion == "v1" {
  150. h.Version = 1
  151. } else if baseCfg.Transport.ProxyProtocolVersion == "v2" {
  152. h.Version = 2
  153. }
  154. extraInfo.ProxyProtocolHeader = h
  155. }
  156. }
  157. if pxy.proxyPlugin != nil {
  158. // if plugin is set, let plugin handle connection first
  159. xl.Debug("handle by plugin: %s", pxy.proxyPlugin.Name())
  160. pxy.proxyPlugin.Handle(remote, workConn, &extraInfo)
  161. xl.Debug("handle by plugin finished")
  162. return
  163. }
  164. localConn, err := libdial.Dial(
  165. net.JoinHostPort(baseCfg.LocalIP, strconv.Itoa(baseCfg.LocalPort)),
  166. libdial.WithTimeout(10*time.Second),
  167. )
  168. if err != nil {
  169. workConn.Close()
  170. xl.Error("connect to local service [%s:%d] error: %v", baseCfg.LocalIP, baseCfg.LocalPort, err)
  171. return
  172. }
  173. xl.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  174. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  175. if extraInfo.ProxyProtocolHeader != nil {
  176. if _, err := extraInfo.ProxyProtocolHeader.WriteTo(localConn); err != nil {
  177. workConn.Close()
  178. xl.Error("write proxy protocol header to local conn error: %v", err)
  179. return
  180. }
  181. }
  182. _, _, errs := libio.Join(localConn, remote)
  183. xl.Debug("join connections closed")
  184. if len(errs) > 0 {
  185. xl.Trace("join connections errors: %v", errs)
  186. }
  187. if compressionResourceRecycleFn != nil {
  188. compressionResourceRecycleFn()
  189. }
  190. }