proxy.go 7.8 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/stats"
  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. statsCollector stats.Collector
  44. listeners []net.Listener
  45. usedPortsNum int
  46. poolCount int
  47. getWorkConnFn GetWorkConnFn
  48. serverCfg config.ServerCommonConf
  49. mu sync.RWMutex
  50. xl *xlog.Logger
  51. ctx context.Context
  52. }
  53. func (pxy *BaseProxy) GetName() string {
  54. return pxy.name
  55. }
  56. func (pxy *BaseProxy) Context() context.Context {
  57. return pxy.ctx
  58. }
  59. func (pxy *BaseProxy) GetUsedPortsNum() int {
  60. return pxy.usedPortsNum
  61. }
  62. func (pxy *BaseProxy) Close() {
  63. xl := xlog.FromContextSafe(pxy.ctx)
  64. xl.Info("proxy closing")
  65. for _, l := range pxy.listeners {
  66. l.Close()
  67. }
  68. }
  69. // GetWorkConnFromPool try to get a new work connections from pool
  70. // for quickly response, we immediately send the StartWorkConn message to frpc after take out one from pool
  71. func (pxy *BaseProxy) GetWorkConnFromPool(src, dst net.Addr) (workConn net.Conn, err error) {
  72. xl := xlog.FromContextSafe(pxy.ctx)
  73. // try all connections from the pool
  74. for i := 0; i < pxy.poolCount+1; i++ {
  75. if workConn, err = pxy.getWorkConnFn(); err != nil {
  76. xl.Warn("failed to get work connection: %v", err)
  77. return
  78. }
  79. xl.Info("get a new work connection: [%s]", workConn.RemoteAddr().String())
  80. xl.Spawn().AppendPrefix(pxy.GetName())
  81. workConn = frpNet.NewContextConn(workConn, pxy.ctx)
  82. var (
  83. srcAddr string
  84. dstAddr string
  85. srcPortStr string
  86. dstPortStr string
  87. srcPort int
  88. dstPort int
  89. )
  90. if src != nil {
  91. srcAddr, srcPortStr, _ = net.SplitHostPort(src.String())
  92. srcPort, _ = strconv.Atoi(srcPortStr)
  93. }
  94. if dst != nil {
  95. dstAddr, dstPortStr, _ = net.SplitHostPort(dst.String())
  96. dstPort, _ = strconv.Atoi(dstPortStr)
  97. }
  98. err := msg.WriteMsg(workConn, &msg.StartWorkConn{
  99. ProxyName: pxy.GetName(),
  100. SrcAddr: srcAddr,
  101. SrcPort: uint16(srcPort),
  102. DstAddr: dstAddr,
  103. DstPort: uint16(dstPort),
  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, stats.Collector, 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.statsCollector, pxy.serverCfg)
  135. }
  136. }(listener)
  137. }
  138. }
  139. func NewProxy(ctx context.Context, runId string, rc *controller.ResourceController, statsCollector stats.Collector, 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. statsCollector: statsCollector,
  146. listeners: make([]net.Listener, 0),
  147. poolCount: poolCount,
  148. getWorkConnFn: getWorkConnFn,
  149. serverCfg: serverCfg,
  150. xl: xl,
  151. ctx: xlog.NewContext(ctx, xl),
  152. }
  153. switch cfg := pxyConf.(type) {
  154. case *config.TcpProxyConf:
  155. basePxy.usedPortsNum = 1
  156. pxy = &TcpProxy{
  157. BaseProxy: &basePxy,
  158. cfg: cfg,
  159. }
  160. case *config.HttpProxyConf:
  161. pxy = &HttpProxy{
  162. BaseProxy: &basePxy,
  163. cfg: cfg,
  164. }
  165. case *config.HttpsProxyConf:
  166. pxy = &HttpsProxy{
  167. BaseProxy: &basePxy,
  168. cfg: cfg,
  169. }
  170. case *config.UdpProxyConf:
  171. basePxy.usedPortsNum = 1
  172. pxy = &UdpProxy{
  173. BaseProxy: &basePxy,
  174. cfg: cfg,
  175. }
  176. case *config.StcpProxyConf:
  177. pxy = &StcpProxy{
  178. BaseProxy: &basePxy,
  179. cfg: cfg,
  180. }
  181. case *config.XtcpProxyConf:
  182. pxy = &XtcpProxy{
  183. BaseProxy: &basePxy,
  184. cfg: cfg,
  185. }
  186. default:
  187. return pxy, fmt.Errorf("proxy type not support")
  188. }
  189. return
  190. }
  191. // HandleUserTcpConnection is used for incoming tcp user connections.
  192. // It can be used for tcp, http, https type.
  193. func HandleUserTcpConnection(pxy Proxy, userConn net.Conn, statsCollector stats.Collector, serverCfg config.ServerCommonConf) {
  194. xl := xlog.FromContextSafe(pxy.Context())
  195. defer userConn.Close()
  196. // try all connections from the pool
  197. workConn, err := pxy.GetWorkConnFromPool(userConn.RemoteAddr(), userConn.LocalAddr())
  198. if err != nil {
  199. return
  200. }
  201. defer workConn.Close()
  202. var local io.ReadWriteCloser = workConn
  203. cfg := pxy.GetConf().GetBaseInfo()
  204. xl.Trace("handler user tcp connection, use_encryption: %t, use_compression: %t", cfg.UseEncryption, cfg.UseCompression)
  205. if cfg.UseEncryption {
  206. local, err = frpIo.WithEncryption(local, []byte(serverCfg.Token))
  207. if err != nil {
  208. xl.Error("create encryption stream error: %v", err)
  209. return
  210. }
  211. }
  212. if cfg.UseCompression {
  213. local = frpIo.WithCompression(local)
  214. }
  215. xl.Debug("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(),
  216. workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String())
  217. statsCollector.Mark(stats.TypeOpenConnection, &stats.OpenConnectionPayload{ProxyName: pxy.GetName()})
  218. inCount, outCount := frpIo.Join(local, userConn)
  219. statsCollector.Mark(stats.TypeCloseConnection, &stats.CloseConnectionPayload{ProxyName: pxy.GetName()})
  220. statsCollector.Mark(stats.TypeAddTrafficIn, &stats.AddTrafficInPayload{
  221. ProxyName: pxy.GetName(),
  222. TrafficBytes: inCount,
  223. })
  224. statsCollector.Mark(stats.TypeAddTrafficOut, &stats.AddTrafficOutPayload{
  225. ProxyName: pxy.GetName(),
  226. TrafficBytes: outCount,
  227. })
  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. }