1
0

proxy.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. "sync"
  22. "time"
  23. libio "github.com/fatedier/golib/io"
  24. libnet "github.com/fatedier/golib/net"
  25. "golang.org/x/time/rate"
  26. "github.com/fatedier/frp/pkg/config/types"
  27. v1 "github.com/fatedier/frp/pkg/config/v1"
  28. "github.com/fatedier/frp/pkg/msg"
  29. plugin "github.com/fatedier/frp/pkg/plugin/client"
  30. "github.com/fatedier/frp/pkg/transport"
  31. "github.com/fatedier/frp/pkg/util/limit"
  32. netpkg "github.com/fatedier/frp/pkg/util/net"
  33. "github.com/fatedier/frp/pkg/util/xlog"
  34. "github.com/fatedier/frp/pkg/vnet"
  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. SetInWorkConnCallback(func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) /* continue */ bool)
  46. Close()
  47. }
  48. func NewProxy(
  49. ctx context.Context,
  50. pxyConf v1.ProxyConfigurer,
  51. clientCfg *v1.ClientCommonConfig,
  52. msgTransporter transport.MessageTransporter,
  53. vnetController *vnet.Controller,
  54. ) (pxy Proxy) {
  55. var limiter *rate.Limiter
  56. limitBytes := pxyConf.GetBaseConfig().Transport.BandwidthLimit.Bytes()
  57. if limitBytes > 0 && pxyConf.GetBaseConfig().Transport.BandwidthLimitMode == types.BandwidthLimitModeClient {
  58. limiter = rate.NewLimiter(rate.Limit(float64(limitBytes)), int(limitBytes))
  59. }
  60. baseProxy := BaseProxy{
  61. baseCfg: pxyConf.GetBaseConfig(),
  62. clientCfg: clientCfg,
  63. limiter: limiter,
  64. msgTransporter: msgTransporter,
  65. vnetController: vnetController,
  66. xl: xlog.FromContextSafe(ctx),
  67. ctx: ctx,
  68. }
  69. factory := proxyFactoryRegistry[reflect.TypeOf(pxyConf)]
  70. if factory == nil {
  71. return nil
  72. }
  73. return factory(&baseProxy, pxyConf)
  74. }
  75. type BaseProxy struct {
  76. baseCfg *v1.ProxyBaseConfig
  77. clientCfg *v1.ClientCommonConfig
  78. msgTransporter transport.MessageTransporter
  79. vnetController *vnet.Controller
  80. limiter *rate.Limiter
  81. // proxyPlugin is used to handle connections instead of dialing to local service.
  82. // It's only validate for TCP protocol now.
  83. proxyPlugin plugin.Plugin
  84. inWorkConnCallback func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) /* continue */ bool
  85. mu sync.RWMutex
  86. xl *xlog.Logger
  87. ctx context.Context
  88. }
  89. func (pxy *BaseProxy) Run() error {
  90. if pxy.baseCfg.Plugin.Type != "" {
  91. p, err := plugin.Create(pxy.baseCfg.Plugin.Type, plugin.PluginContext{
  92. Name: pxy.baseCfg.Name,
  93. VnetController: pxy.vnetController,
  94. }, pxy.baseCfg.Plugin.ClientPluginOptions)
  95. if err != nil {
  96. return err
  97. }
  98. pxy.proxyPlugin = p
  99. }
  100. return nil
  101. }
  102. func (pxy *BaseProxy) Close() {
  103. if pxy.proxyPlugin != nil {
  104. pxy.proxyPlugin.Close()
  105. }
  106. }
  107. func (pxy *BaseProxy) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) {
  108. pxy.inWorkConnCallback = cb
  109. }
  110. func (pxy *BaseProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  111. if pxy.inWorkConnCallback != nil {
  112. if !pxy.inWorkConnCallback(pxy.baseCfg, conn, m) {
  113. return
  114. }
  115. }
  116. pxy.HandleTCPWorkConnection(conn, m, []byte(pxy.clientCfg.Auth.Token))
  117. }
  118. // Common handler for tcp work connections.
  119. func (pxy *BaseProxy) HandleTCPWorkConnection(workConn net.Conn, m *msg.StartWorkConn, encKey []byte) {
  120. xl := pxy.xl
  121. baseCfg := pxy.baseCfg
  122. var (
  123. remote io.ReadWriteCloser
  124. err error
  125. )
  126. remote = workConn
  127. if pxy.limiter != nil {
  128. remote = libio.WrapReadWriteCloser(limit.NewReader(workConn, pxy.limiter), limit.NewWriter(workConn, pxy.limiter), func() error {
  129. return workConn.Close()
  130. })
  131. }
  132. xl.Tracef("handle tcp work connection, useEncryption: %t, useCompression: %t",
  133. baseCfg.Transport.UseEncryption, baseCfg.Transport.UseCompression)
  134. if baseCfg.Transport.UseEncryption {
  135. remote, err = libio.WithEncryption(remote, encKey)
  136. if err != nil {
  137. workConn.Close()
  138. xl.Errorf("create encryption stream error: %v", err)
  139. return
  140. }
  141. }
  142. var compressionResourceRecycleFn func()
  143. if baseCfg.Transport.UseCompression {
  144. remote, compressionResourceRecycleFn = libio.WithCompressionFromPool(remote)
  145. }
  146. // check if we need to send proxy protocol info
  147. var connInfo plugin.ConnectionInfo
  148. if m.SrcAddr != "" && m.SrcPort != 0 {
  149. if m.DstAddr == "" {
  150. m.DstAddr = "127.0.0.1"
  151. }
  152. srcAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.SrcAddr, strconv.Itoa(int(m.SrcPort))))
  153. dstAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.DstAddr, strconv.Itoa(int(m.DstPort))))
  154. connInfo.SrcAddr = srcAddr
  155. connInfo.DstAddr = dstAddr
  156. }
  157. if baseCfg.Transport.ProxyProtocolVersion != "" && m.SrcAddr != "" && m.SrcPort != 0 {
  158. // Use the common proxy protocol builder function
  159. header := netpkg.BuildProxyProtocolHeaderStruct(connInfo.SrcAddr, connInfo.DstAddr, baseCfg.Transport.ProxyProtocolVersion)
  160. connInfo.ProxyProtocolHeader = header
  161. }
  162. connInfo.Conn = remote
  163. connInfo.UnderlyingConn = workConn
  164. if pxy.proxyPlugin != nil {
  165. // if plugin is set, let plugin handle connection first
  166. xl.Debugf("handle by plugin: %s", pxy.proxyPlugin.Name())
  167. pxy.proxyPlugin.Handle(pxy.ctx, &connInfo)
  168. xl.Debugf("handle by plugin finished")
  169. return
  170. }
  171. localConn, err := libnet.Dial(
  172. net.JoinHostPort(baseCfg.LocalIP, strconv.Itoa(baseCfg.LocalPort)),
  173. libnet.WithTimeout(10*time.Second),
  174. )
  175. if err != nil {
  176. workConn.Close()
  177. xl.Errorf("connect to local service [%s:%d] error: %v", baseCfg.LocalIP, baseCfg.LocalPort, err)
  178. return
  179. }
  180. xl.Debugf("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  181. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  182. if connInfo.ProxyProtocolHeader != nil {
  183. if _, err := connInfo.ProxyProtocolHeader.WriteTo(localConn); err != nil {
  184. workConn.Close()
  185. xl.Errorf("write proxy protocol header to local conn error: %v", err)
  186. return
  187. }
  188. }
  189. _, _, errs := libio.Join(localConn, remote)
  190. xl.Debugf("join connections closed")
  191. if len(errs) > 0 {
  192. xl.Tracef("join connections errors: %v", errs)
  193. }
  194. if compressionResourceRecycleFn != nil {
  195. compressionResourceRecycleFn()
  196. }
  197. }