proxy.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. "github.com/fatedier/frp/models/config"
  23. "github.com/fatedier/frp/models/msg"
  24. "github.com/fatedier/frp/server/controller"
  25. "github.com/fatedier/frp/server/metrics"
  26. frpNet "github.com/fatedier/frp/utils/net"
  27. "github.com/fatedier/frp/utils/xlog"
  28. frpIo "github.com/fatedier/golib/io"
  29. )
  30. type GetWorkConnFn func() (net.Conn, error)
  31. type Proxy interface {
  32. Context() context.Context
  33. Run() (remoteAddr string, err error)
  34. GetName() string
  35. GetConf() config.ProxyConf
  36. GetWorkConnFromPool(src, dst net.Addr) (workConn net.Conn, err error)
  37. GetUsedPortsNum() int
  38. Close()
  39. }
  40. type BaseProxy struct {
  41. name string
  42. rc *controller.ResourceController
  43. listeners []net.Listener
  44. usedPortsNum int
  45. poolCount int
  46. getWorkConnFn GetWorkConnFn
  47. serverCfg config.ServerCommonConf
  48. mu sync.RWMutex
  49. xl *xlog.Logger
  50. ctx context.Context
  51. }
  52. func (pxy *BaseProxy) GetName() string {
  53. return pxy.name
  54. }
  55. func (pxy *BaseProxy) Context() context.Context {
  56. return pxy.ctx
  57. }
  58. func (pxy *BaseProxy) GetUsedPortsNum() int {
  59. return pxy.usedPortsNum
  60. }
  61. func (pxy *BaseProxy) Close() {
  62. xl := xlog.FromContextSafe(pxy.ctx)
  63. xl.Info("proxy closing")
  64. for _, l := range pxy.listeners {
  65. l.Close()
  66. }
  67. }
  68. // GetWorkConnFromPool try to get a new work connections from pool
  69. // for quickly response, we immediately send the StartWorkConn message to frpc after take out one from pool
  70. func (pxy *BaseProxy) GetWorkConnFromPool(src, dst net.Addr) (workConn net.Conn, err error) {
  71. xl := xlog.FromContextSafe(pxy.ctx)
  72. // try all connections from the pool
  73. for i := 0; i < pxy.poolCount+1; i++ {
  74. if workConn, err = pxy.getWorkConnFn(); err != nil {
  75. xl.Warn("failed to get work connection: %v", err)
  76. return
  77. }
  78. xl.Info("get a new work connection: [%s]", workConn.RemoteAddr().String())
  79. xl.Spawn().AppendPrefix(pxy.GetName())
  80. workConn = frpNet.NewContextConn(workConn, pxy.ctx)
  81. var (
  82. srcAddr string
  83. dstAddr string
  84. srcPortStr string
  85. dstPortStr string
  86. srcPort int
  87. dstPort int
  88. )
  89. if src != nil {
  90. srcAddr, srcPortStr, _ = net.SplitHostPort(src.String())
  91. srcPort, _ = strconv.Atoi(srcPortStr)
  92. }
  93. if dst != nil {
  94. dstAddr, dstPortStr, _ = net.SplitHostPort(dst.String())
  95. dstPort, _ = strconv.Atoi(dstPortStr)
  96. }
  97. err := msg.WriteMsg(workConn, &msg.StartWorkConn{
  98. ProxyName: pxy.GetName(),
  99. SrcAddr: srcAddr,
  100. SrcPort: uint16(srcPort),
  101. DstAddr: dstAddr,
  102. DstPort: uint16(dstPort),
  103. Error: "",
  104. })
  105. if err != nil {
  106. xl.Warn("failed to send message to work connection from pool: %v, times: %d", err, i)
  107. workConn.Close()
  108. } else {
  109. break
  110. }
  111. }
  112. if err != nil {
  113. xl.Error("try to get work connection failed in the end")
  114. return
  115. }
  116. return
  117. }
  118. // startListenHandler start a goroutine handler for each listener.
  119. // p: p will just be passed to handler(Proxy, frpNet.Conn).
  120. // handler: each proxy type can set different handler function to deal with connections accepted from listeners.
  121. func (pxy *BaseProxy) startListenHandler(p Proxy, handler func(Proxy, net.Conn, config.ServerCommonConf)) {
  122. xl := xlog.FromContextSafe(pxy.ctx)
  123. for _, listener := range pxy.listeners {
  124. go func(l net.Listener) {
  125. for {
  126. // block
  127. // if listener is closed, err returned
  128. c, err := l.Accept()
  129. if err != nil {
  130. xl.Info("listener is closed")
  131. return
  132. }
  133. xl.Debug("get a user connection [%s]", c.RemoteAddr().String())
  134. go handler(p, c, pxy.serverCfg)
  135. }
  136. }(listener)
  137. }
  138. }
  139. func NewProxy(ctx context.Context, runId string, rc *controller.ResourceController, poolCount int,
  140. getWorkConnFn GetWorkConnFn, pxyConf config.ProxyConf, serverCfg config.ServerCommonConf) (pxy Proxy, err error) {
  141. xl := xlog.FromContextSafe(ctx).Spawn().AppendPrefix(pxyConf.GetBaseInfo().ProxyName)
  142. basePxy := BaseProxy{
  143. name: pxyConf.GetBaseInfo().ProxyName,
  144. rc: rc,
  145. listeners: make([]net.Listener, 0),
  146. poolCount: poolCount,
  147. getWorkConnFn: getWorkConnFn,
  148. serverCfg: serverCfg,
  149. xl: xl,
  150. ctx: xlog.NewContext(ctx, xl),
  151. }
  152. switch cfg := pxyConf.(type) {
  153. case *config.TcpProxyConf:
  154. basePxy.usedPortsNum = 1
  155. pxy = &TcpProxy{
  156. BaseProxy: &basePxy,
  157. cfg: cfg,
  158. }
  159. case *config.TcpMuxProxyConf:
  160. pxy = &TcpMuxProxy{
  161. BaseProxy: &basePxy,
  162. cfg: cfg,
  163. }
  164. case *config.HttpProxyConf:
  165. pxy = &HttpProxy{
  166. BaseProxy: &basePxy,
  167. cfg: cfg,
  168. }
  169. case *config.HttpsProxyConf:
  170. pxy = &HttpsProxy{
  171. BaseProxy: &basePxy,
  172. cfg: cfg,
  173. }
  174. case *config.UdpProxyConf:
  175. basePxy.usedPortsNum = 1
  176. pxy = &UdpProxy{
  177. BaseProxy: &basePxy,
  178. cfg: cfg,
  179. }
  180. case *config.StcpProxyConf:
  181. pxy = &StcpProxy{
  182. BaseProxy: &basePxy,
  183. cfg: cfg,
  184. }
  185. case *config.XtcpProxyConf:
  186. pxy = &XtcpProxy{
  187. BaseProxy: &basePxy,
  188. cfg: cfg,
  189. }
  190. default:
  191. return pxy, fmt.Errorf("proxy type not support")
  192. }
  193. return
  194. }
  195. // HandleUserTcpConnection is used for incoming tcp user connections.
  196. // It can be used for tcp, http, https type.
  197. func HandleUserTcpConnection(pxy Proxy, userConn net.Conn, serverCfg config.ServerCommonConf) {
  198. xl := xlog.FromContextSafe(pxy.Context())
  199. defer userConn.Close()
  200. // try all connections from the pool
  201. workConn, err := pxy.GetWorkConnFromPool(userConn.RemoteAddr(), userConn.LocalAddr())
  202. if err != nil {
  203. return
  204. }
  205. defer workConn.Close()
  206. var local io.ReadWriteCloser = workConn
  207. cfg := pxy.GetConf().GetBaseInfo()
  208. xl.Trace("handler user tcp connection, use_encryption: %t, use_compression: %t", cfg.UseEncryption, cfg.UseCompression)
  209. if cfg.UseEncryption {
  210. local, err = frpIo.WithEncryption(local, []byte(serverCfg.Token))
  211. if err != nil {
  212. xl.Error("create encryption stream error: %v", err)
  213. return
  214. }
  215. }
  216. if cfg.UseCompression {
  217. local = frpIo.WithCompression(local)
  218. }
  219. xl.Debug("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(),
  220. workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String())
  221. name := pxy.GetName()
  222. proxyType := pxy.GetConf().GetBaseInfo().ProxyType
  223. metrics.Server.OpenConnection(name, proxyType)
  224. inCount, outCount := frpIo.Join(local, userConn)
  225. metrics.Server.CloseConnection(name, proxyType)
  226. metrics.Server.AddTrafficIn(name, proxyType, inCount)
  227. metrics.Server.AddTrafficOut(name, proxyType, outCount)
  228. xl.Debug("join connections closed")
  229. }
  230. type ProxyManager struct {
  231. // proxies indexed by proxy name
  232. pxys map[string]Proxy
  233. mu sync.RWMutex
  234. }
  235. func NewProxyManager() *ProxyManager {
  236. return &ProxyManager{
  237. pxys: make(map[string]Proxy),
  238. }
  239. }
  240. func (pm *ProxyManager) Add(name string, pxy Proxy) error {
  241. pm.mu.Lock()
  242. defer pm.mu.Unlock()
  243. if _, ok := pm.pxys[name]; ok {
  244. return fmt.Errorf("proxy name [%s] is already in use", name)
  245. }
  246. pm.pxys[name] = pxy
  247. return nil
  248. }
  249. func (pm *ProxyManager) Del(name string) {
  250. pm.mu.Lock()
  251. defer pm.mu.Unlock()
  252. delete(pm.pxys, name)
  253. }
  254. func (pm *ProxyManager) GetByName(name string) (pxy Proxy, ok bool) {
  255. pm.mu.RLock()
  256. defer pm.mu.RUnlock()
  257. pxy, ok = pm.pxys[name]
  258. return
  259. }