proxy.go 6.8 KB

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