proxy.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. "fmt"
  18. "io"
  19. "net"
  20. "reflect"
  21. "strconv"
  22. "sync"
  23. "time"
  24. libio "github.com/fatedier/golib/io"
  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/server"
  30. "github.com/fatedier/frp/pkg/util/limit"
  31. netpkg "github.com/fatedier/frp/pkg/util/net"
  32. "github.com/fatedier/frp/pkg/util/xlog"
  33. "github.com/fatedier/frp/server/controller"
  34. "github.com/fatedier/frp/server/metrics"
  35. )
  36. var proxyFactoryRegistry = map[reflect.Type]func(*BaseProxy) Proxy{}
  37. func RegisterProxyFactory(proxyConfType reflect.Type, factory func(*BaseProxy) Proxy) {
  38. proxyFactoryRegistry[proxyConfType] = factory
  39. }
  40. type GetWorkConnFn func() (net.Conn, error)
  41. type Proxy interface {
  42. Context() context.Context
  43. Run() (remoteAddr string, err error)
  44. GetName() string
  45. GetConfigurer() v1.ProxyConfigurer
  46. GetWorkConnFromPool(src, dst net.Addr) (workConn net.Conn, err error)
  47. GetUsedPortsNum() int
  48. GetResourceController() *controller.ResourceController
  49. GetUserInfo() plugin.UserInfo
  50. GetLimiter() *rate.Limiter
  51. GetLoginMsg() *msg.Login
  52. Close()
  53. }
  54. type BaseProxy struct {
  55. name string
  56. rc *controller.ResourceController
  57. listeners []net.Listener
  58. usedPortsNum int
  59. poolCount int
  60. getWorkConnFn GetWorkConnFn
  61. serverCfg *v1.ServerConfig
  62. limiter *rate.Limiter
  63. userInfo plugin.UserInfo
  64. loginMsg *msg.Login
  65. configurer v1.ProxyConfigurer
  66. mu sync.RWMutex
  67. xl *xlog.Logger
  68. ctx context.Context
  69. }
  70. func (pxy *BaseProxy) GetName() string {
  71. return pxy.name
  72. }
  73. func (pxy *BaseProxy) Context() context.Context {
  74. return pxy.ctx
  75. }
  76. func (pxy *BaseProxy) GetUsedPortsNum() int {
  77. return pxy.usedPortsNum
  78. }
  79. func (pxy *BaseProxy) GetResourceController() *controller.ResourceController {
  80. return pxy.rc
  81. }
  82. func (pxy *BaseProxy) GetUserInfo() plugin.UserInfo {
  83. return pxy.userInfo
  84. }
  85. func (pxy *BaseProxy) GetLoginMsg() *msg.Login {
  86. return pxy.loginMsg
  87. }
  88. func (pxy *BaseProxy) GetLimiter() *rate.Limiter {
  89. return pxy.limiter
  90. }
  91. func (pxy *BaseProxy) GetConfigurer() v1.ProxyConfigurer {
  92. return pxy.configurer
  93. }
  94. func (pxy *BaseProxy) Close() {
  95. xl := xlog.FromContextSafe(pxy.ctx)
  96. xl.Infof("proxy closing")
  97. for _, l := range pxy.listeners {
  98. l.Close()
  99. }
  100. }
  101. // GetWorkConnFromPool try to get a new work connections from pool
  102. // for quickly response, we immediately send the StartWorkConn message to frpc after take out one from pool
  103. func (pxy *BaseProxy) GetWorkConnFromPool(src, dst net.Addr) (workConn net.Conn, err error) {
  104. xl := xlog.FromContextSafe(pxy.ctx)
  105. // try all connections from the pool
  106. for i := 0; i < pxy.poolCount+1; i++ {
  107. if workConn, err = pxy.getWorkConnFn(); err != nil {
  108. xl.Warnf("failed to get work connection: %v", err)
  109. return
  110. }
  111. xl.Debugf("get a new work connection: [%s]", workConn.RemoteAddr().String())
  112. xl.Spawn().AppendPrefix(pxy.GetName())
  113. workConn = netpkg.NewContextConn(pxy.ctx, workConn)
  114. var (
  115. srcAddr string
  116. dstAddr string
  117. srcPortStr string
  118. dstPortStr string
  119. srcPort uint64
  120. dstPort uint64
  121. )
  122. if src != nil {
  123. srcAddr, srcPortStr, _ = net.SplitHostPort(src.String())
  124. srcPort, _ = strconv.ParseUint(srcPortStr, 10, 16)
  125. }
  126. if dst != nil {
  127. dstAddr, dstPortStr, _ = net.SplitHostPort(dst.String())
  128. dstPort, _ = strconv.ParseUint(dstPortStr, 10, 16)
  129. }
  130. err := msg.WriteMsg(workConn, &msg.StartWorkConn{
  131. ProxyName: pxy.GetName(),
  132. SrcAddr: srcAddr,
  133. SrcPort: uint16(srcPort),
  134. DstAddr: dstAddr,
  135. DstPort: uint16(dstPort),
  136. Error: "",
  137. })
  138. if err != nil {
  139. xl.Warnf("failed to send message to work connection from pool: %v, times: %d", err, i)
  140. workConn.Close()
  141. } else {
  142. break
  143. }
  144. }
  145. if err != nil {
  146. xl.Errorf("try to get work connection failed in the end")
  147. return
  148. }
  149. return
  150. }
  151. // startCommonTCPListenersHandler start a goroutine handler for each listener.
  152. func (pxy *BaseProxy) startCommonTCPListenersHandler() {
  153. xl := xlog.FromContextSafe(pxy.ctx)
  154. for _, listener := range pxy.listeners {
  155. go func(l net.Listener) {
  156. var tempDelay time.Duration // how long to sleep on accept failure
  157. for {
  158. // block
  159. // if listener is closed, err returned
  160. c, err := l.Accept()
  161. if err != nil {
  162. if err, ok := err.(interface{ Temporary() bool }); ok && err.Temporary() {
  163. if tempDelay == 0 {
  164. tempDelay = 5 * time.Millisecond
  165. } else {
  166. tempDelay *= 2
  167. }
  168. if maxTime := 1 * time.Second; tempDelay > maxTime {
  169. tempDelay = maxTime
  170. }
  171. xl.Infof("met temporary error: %s, sleep for %s ...", err, tempDelay)
  172. time.Sleep(tempDelay)
  173. continue
  174. }
  175. xl.Warnf("listener is closed: %s", err)
  176. return
  177. }
  178. xl.Infof("get a user connection [%s]", c.RemoteAddr().String())
  179. go pxy.handleUserTCPConnection(c)
  180. }
  181. }(listener)
  182. }
  183. }
  184. // HandleUserTCPConnection is used for incoming user TCP connections.
  185. func (pxy *BaseProxy) handleUserTCPConnection(userConn net.Conn) {
  186. xl := xlog.FromContextSafe(pxy.Context())
  187. defer userConn.Close()
  188. serverCfg := pxy.serverCfg
  189. cfg := pxy.configurer.GetBaseConfig()
  190. // server plugin hook
  191. rc := pxy.GetResourceController()
  192. content := &plugin.NewUserConnContent{
  193. User: pxy.GetUserInfo(),
  194. ProxyName: pxy.GetName(),
  195. ProxyType: cfg.Type,
  196. RemoteAddr: userConn.RemoteAddr().String(),
  197. }
  198. _, err := rc.PluginManager.NewUserConn(content)
  199. if err != nil {
  200. xl.Warnf("the user conn [%s] was rejected, err:%v", content.RemoteAddr, err)
  201. return
  202. }
  203. // try all connections from the pool
  204. workConn, err := pxy.GetWorkConnFromPool(userConn.RemoteAddr(), userConn.LocalAddr())
  205. if err != nil {
  206. return
  207. }
  208. defer workConn.Close()
  209. var local io.ReadWriteCloser = workConn
  210. xl.Tracef("handler user tcp connection, use_encryption: %t, use_compression: %t",
  211. cfg.Transport.UseEncryption, cfg.Transport.UseCompression)
  212. if cfg.Transport.UseEncryption {
  213. local, err = libio.WithEncryption(local, []byte(serverCfg.Auth.Token))
  214. if err != nil {
  215. xl.Errorf("create encryption stream error: %v", err)
  216. return
  217. }
  218. }
  219. if cfg.Transport.UseCompression {
  220. var recycleFn func()
  221. local, recycleFn = libio.WithCompressionFromPool(local)
  222. defer recycleFn()
  223. }
  224. if pxy.GetLimiter() != nil {
  225. local = libio.WrapReadWriteCloser(limit.NewReader(local, pxy.GetLimiter()), limit.NewWriter(local, pxy.GetLimiter()), func() error {
  226. return local.Close()
  227. })
  228. }
  229. xl.Debugf("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(),
  230. workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String())
  231. name := pxy.GetName()
  232. proxyType := cfg.Type
  233. metrics.Server.OpenConnection(name, proxyType)
  234. inCount, outCount, _ := libio.Join(local, userConn)
  235. metrics.Server.CloseConnection(name, proxyType)
  236. metrics.Server.AddTrafficIn(name, proxyType, inCount)
  237. metrics.Server.AddTrafficOut(name, proxyType, outCount)
  238. xl.Debugf("join connections closed")
  239. }
  240. type Options struct {
  241. UserInfo plugin.UserInfo
  242. LoginMsg *msg.Login
  243. PoolCount int
  244. ResourceController *controller.ResourceController
  245. GetWorkConnFn GetWorkConnFn
  246. Configurer v1.ProxyConfigurer
  247. ServerCfg *v1.ServerConfig
  248. }
  249. func NewProxy(ctx context.Context, options *Options) (pxy Proxy, err error) {
  250. configurer := options.Configurer
  251. xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(configurer.GetBaseConfig().Name)
  252. var limiter *rate.Limiter
  253. limitBytes := configurer.GetBaseConfig().Transport.BandwidthLimit.Bytes()
  254. if limitBytes > 0 && configurer.GetBaseConfig().Transport.BandwidthLimitMode == types.BandwidthLimitModeServer {
  255. limiter = rate.NewLimiter(rate.Limit(float64(limitBytes)), int(limitBytes))
  256. }
  257. basePxy := BaseProxy{
  258. name: configurer.GetBaseConfig().Name,
  259. rc: options.ResourceController,
  260. listeners: make([]net.Listener, 0),
  261. poolCount: options.PoolCount,
  262. getWorkConnFn: options.GetWorkConnFn,
  263. serverCfg: options.ServerCfg,
  264. limiter: limiter,
  265. xl: xl,
  266. ctx: xlog.NewContext(ctx, xl),
  267. userInfo: options.UserInfo,
  268. loginMsg: options.LoginMsg,
  269. configurer: configurer,
  270. }
  271. factory := proxyFactoryRegistry[reflect.TypeOf(configurer)]
  272. if factory == nil {
  273. return pxy, fmt.Errorf("proxy type not support")
  274. }
  275. pxy = factory(&basePxy)
  276. if pxy == nil {
  277. return nil, fmt.Errorf("proxy not created")
  278. }
  279. return pxy, nil
  280. }
  281. type Manager struct {
  282. // proxies indexed by proxy name
  283. pxys map[string]Proxy
  284. mu sync.RWMutex
  285. }
  286. func NewManager() *Manager {
  287. return &Manager{
  288. pxys: make(map[string]Proxy),
  289. }
  290. }
  291. func (pm *Manager) Add(name string, pxy Proxy) error {
  292. pm.mu.Lock()
  293. defer pm.mu.Unlock()
  294. if _, ok := pm.pxys[name]; ok {
  295. return fmt.Errorf("proxy name [%s] is already in use", name)
  296. }
  297. pm.pxys[name] = pxy
  298. return nil
  299. }
  300. func (pm *Manager) Exist(name string) bool {
  301. pm.mu.RLock()
  302. defer pm.mu.RUnlock()
  303. _, ok := pm.pxys[name]
  304. return ok
  305. }
  306. func (pm *Manager) Del(name string) {
  307. pm.mu.Lock()
  308. defer pm.mu.Unlock()
  309. delete(pm.pxys, name)
  310. }
  311. func (pm *Manager) GetByName(name string) (pxy Proxy, ok bool) {
  312. pm.mu.RLock()
  313. defer pm.mu.RUnlock()
  314. pxy, ok = pm.pxys[name]
  315. return
  316. }