1
0

proxy.go 9.5 KB

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