proxy.go 7.0 KB

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