proxy.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. "bytes"
  17. "context"
  18. "io"
  19. "net"
  20. "reflect"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. libio "github.com/fatedier/golib/io"
  26. libdial "github.com/fatedier/golib/net/dial"
  27. pp "github.com/pires/go-proxyproto"
  28. "golang.org/x/time/rate"
  29. "github.com/fatedier/frp/pkg/config/types"
  30. v1 "github.com/fatedier/frp/pkg/config/v1"
  31. "github.com/fatedier/frp/pkg/msg"
  32. plugin "github.com/fatedier/frp/pkg/plugin/client"
  33. "github.com/fatedier/frp/pkg/transport"
  34. "github.com/fatedier/frp/pkg/util/limit"
  35. "github.com/fatedier/frp/pkg/util/xlog"
  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. 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. mu sync.RWMutex
  82. xl *xlog.Logger
  83. ctx context.Context
  84. }
  85. func (pxy *BaseProxy) Run() error {
  86. if pxy.baseCfg.Plugin.Type != "" {
  87. p, err := plugin.Create(pxy.baseCfg.Plugin.Type, pxy.baseCfg.Plugin.ClientPluginOptions)
  88. if err != nil {
  89. return err
  90. }
  91. pxy.proxyPlugin = p
  92. }
  93. return nil
  94. }
  95. func (pxy *BaseProxy) Close() {
  96. if pxy.proxyPlugin != nil {
  97. pxy.proxyPlugin.Close()
  98. }
  99. }
  100. func (pxy *BaseProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  101. pxy.HandleTCPWorkConnection(conn, m, []byte(pxy.clientCfg.Auth.Token))
  102. }
  103. // Common handler for tcp work connections.
  104. func (pxy *BaseProxy) HandleTCPWorkConnection(workConn net.Conn, m *msg.StartWorkConn, encKey []byte) {
  105. xl := pxy.xl
  106. baseCfg := pxy.baseCfg
  107. var (
  108. remote io.ReadWriteCloser
  109. err error
  110. )
  111. remote = workConn
  112. if pxy.limiter != nil {
  113. remote = libio.WrapReadWriteCloser(limit.NewReader(workConn, pxy.limiter), limit.NewWriter(workConn, pxy.limiter), func() error {
  114. return workConn.Close()
  115. })
  116. }
  117. xl.Trace("handle tcp work connection, use_encryption: %t, use_compression: %t",
  118. baseCfg.Transport.UseEncryption, baseCfg.Transport.UseCompression)
  119. if baseCfg.Transport.UseEncryption {
  120. remote, err = libio.WithEncryption(remote, encKey)
  121. if err != nil {
  122. workConn.Close()
  123. xl.Error("create encryption stream error: %v", err)
  124. return
  125. }
  126. }
  127. var compressionResourceRecycleFn func()
  128. if baseCfg.Transport.UseCompression {
  129. remote, compressionResourceRecycleFn = libio.WithCompressionFromPool(remote)
  130. }
  131. // check if we need to send proxy protocol info
  132. var extraInfo []byte
  133. if baseCfg.Transport.ProxyProtocolVersion != "" {
  134. if m.SrcAddr != "" && m.SrcPort != 0 {
  135. if m.DstAddr == "" {
  136. m.DstAddr = "127.0.0.1"
  137. }
  138. srcAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.SrcAddr, strconv.Itoa(int(m.SrcPort))))
  139. dstAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.DstAddr, strconv.Itoa(int(m.DstPort))))
  140. h := &pp.Header{
  141. Command: pp.PROXY,
  142. SourceAddr: srcAddr,
  143. DestinationAddr: dstAddr,
  144. }
  145. if strings.Contains(m.SrcAddr, ".") {
  146. h.TransportProtocol = pp.TCPv4
  147. } else {
  148. h.TransportProtocol = pp.TCPv6
  149. }
  150. if baseCfg.Transport.ProxyProtocolVersion == "v1" {
  151. h.Version = 1
  152. } else if baseCfg.Transport.ProxyProtocolVersion == "v2" {
  153. h.Version = 2
  154. }
  155. buf := bytes.NewBuffer(nil)
  156. _, _ = h.WriteTo(buf)
  157. extraInfo = buf.Bytes()
  158. }
  159. }
  160. if pxy.proxyPlugin != nil {
  161. // if plugin is set, let plugin handle connection first
  162. xl.Debug("handle by plugin: %s", pxy.proxyPlugin.Name())
  163. pxy.proxyPlugin.Handle(remote, workConn, extraInfo)
  164. xl.Debug("handle by plugin finished")
  165. return
  166. }
  167. localConn, err := libdial.Dial(
  168. net.JoinHostPort(baseCfg.LocalIP, strconv.Itoa(baseCfg.LocalPort)),
  169. libdial.WithTimeout(10*time.Second),
  170. )
  171. if err != nil {
  172. workConn.Close()
  173. xl.Error("connect to local service [%s:%d] error: %v", baseCfg.LocalIP, baseCfg.LocalPort, err)
  174. return
  175. }
  176. xl.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  177. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  178. if len(extraInfo) > 0 {
  179. if _, err := localConn.Write(extraInfo); err != nil {
  180. workConn.Close()
  181. xl.Error("write extraInfo to local conn error: %v", err)
  182. return
  183. }
  184. }
  185. _, _, errs := libio.Join(localConn, remote)
  186. xl.Debug("join connections closed")
  187. if len(errs) > 0 {
  188. xl.Trace("join connections errors: %v", errs)
  189. }
  190. if compressionResourceRecycleFn != nil {
  191. compressionResourceRecycleFn()
  192. }
  193. }