1
0

control.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 server
  15. import (
  16. "context"
  17. "fmt"
  18. "net"
  19. "runtime/debug"
  20. "sync"
  21. "sync/atomic"
  22. "time"
  23. "github.com/samber/lo"
  24. "github.com/fatedier/frp/pkg/auth"
  25. "github.com/fatedier/frp/pkg/config"
  26. v1 "github.com/fatedier/frp/pkg/config/v1"
  27. pkgerr "github.com/fatedier/frp/pkg/errors"
  28. "github.com/fatedier/frp/pkg/msg"
  29. plugin "github.com/fatedier/frp/pkg/plugin/server"
  30. "github.com/fatedier/frp/pkg/transport"
  31. utilnet "github.com/fatedier/frp/pkg/util/net"
  32. "github.com/fatedier/frp/pkg/util/util"
  33. "github.com/fatedier/frp/pkg/util/version"
  34. "github.com/fatedier/frp/pkg/util/wait"
  35. "github.com/fatedier/frp/pkg/util/xlog"
  36. "github.com/fatedier/frp/server/controller"
  37. "github.com/fatedier/frp/server/metrics"
  38. "github.com/fatedier/frp/server/proxy"
  39. )
  40. type ControlManager struct {
  41. // controls indexed by run id
  42. ctlsByRunID map[string]*Control
  43. mu sync.RWMutex
  44. }
  45. func NewControlManager() *ControlManager {
  46. return &ControlManager{
  47. ctlsByRunID: make(map[string]*Control),
  48. }
  49. }
  50. func (cm *ControlManager) Add(runID string, ctl *Control) (old *Control) {
  51. cm.mu.Lock()
  52. defer cm.mu.Unlock()
  53. var ok bool
  54. old, ok = cm.ctlsByRunID[runID]
  55. if ok {
  56. old.Replaced(ctl)
  57. }
  58. cm.ctlsByRunID[runID] = ctl
  59. return
  60. }
  61. // we should make sure if it's the same control to prevent delete a new one
  62. func (cm *ControlManager) Del(runID string, ctl *Control) {
  63. cm.mu.Lock()
  64. defer cm.mu.Unlock()
  65. if c, ok := cm.ctlsByRunID[runID]; ok && c == ctl {
  66. delete(cm.ctlsByRunID, runID)
  67. }
  68. }
  69. func (cm *ControlManager) GetByID(runID string) (ctl *Control, ok bool) {
  70. cm.mu.RLock()
  71. defer cm.mu.RUnlock()
  72. ctl, ok = cm.ctlsByRunID[runID]
  73. return
  74. }
  75. func (cm *ControlManager) Close() error {
  76. cm.mu.Lock()
  77. defer cm.mu.Unlock()
  78. for _, ctl := range cm.ctlsByRunID {
  79. ctl.Close()
  80. }
  81. cm.ctlsByRunID = make(map[string]*Control)
  82. return nil
  83. }
  84. type Control struct {
  85. // all resource managers and controllers
  86. rc *controller.ResourceController
  87. // proxy manager
  88. pxyManager *proxy.Manager
  89. // plugin manager
  90. pluginManager *plugin.Manager
  91. // verifies authentication based on selected method
  92. authVerifier auth.Verifier
  93. // other components can use this to communicate with client
  94. msgTransporter transport.MessageTransporter
  95. // msgDispatcher is a wrapper for control connection.
  96. // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types.
  97. msgDispatcher *msg.Dispatcher
  98. // login message
  99. loginMsg *msg.Login
  100. // control connection
  101. conn net.Conn
  102. // work connections
  103. workConnCh chan net.Conn
  104. // proxies in one client
  105. proxies map[string]proxy.Proxy
  106. // pool count
  107. poolCount int
  108. // ports used, for limitations
  109. portsUsedNum int
  110. // last time got the Ping message
  111. lastPing atomic.Value
  112. // A new run id will be generated when a new client login.
  113. // If run id got from login message has same run id, it means it's the same client, so we can
  114. // replace old controller instantly.
  115. runID string
  116. mu sync.RWMutex
  117. // Server configuration information
  118. serverCfg *v1.ServerConfig
  119. xl *xlog.Logger
  120. ctx context.Context
  121. doneCh chan struct{}
  122. }
  123. func NewControl(
  124. ctx context.Context,
  125. rc *controller.ResourceController,
  126. pxyManager *proxy.Manager,
  127. pluginManager *plugin.Manager,
  128. authVerifier auth.Verifier,
  129. ctlConn net.Conn,
  130. loginMsg *msg.Login,
  131. serverCfg *v1.ServerConfig,
  132. ) (*Control, error) {
  133. poolCount := loginMsg.PoolCount
  134. if poolCount > int(serverCfg.Transport.MaxPoolCount) {
  135. poolCount = int(serverCfg.Transport.MaxPoolCount)
  136. }
  137. ctl := &Control{
  138. rc: rc,
  139. pxyManager: pxyManager,
  140. pluginManager: pluginManager,
  141. authVerifier: authVerifier,
  142. conn: ctlConn,
  143. loginMsg: loginMsg,
  144. workConnCh: make(chan net.Conn, poolCount+10),
  145. proxies: make(map[string]proxy.Proxy),
  146. poolCount: poolCount,
  147. portsUsedNum: 0,
  148. runID: loginMsg.RunID,
  149. serverCfg: serverCfg,
  150. xl: xlog.FromContextSafe(ctx),
  151. ctx: ctx,
  152. doneCh: make(chan struct{}),
  153. }
  154. ctl.lastPing.Store(time.Now())
  155. cryptoRW, err := utilnet.NewCryptoReadWriter(ctl.conn, []byte(ctl.serverCfg.Auth.Token))
  156. if err != nil {
  157. return nil, err
  158. }
  159. ctl.msgDispatcher = msg.NewDispatcher(cryptoRW)
  160. ctl.registerMsgHandlers()
  161. ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher.SendChannel())
  162. return ctl, nil
  163. }
  164. // Start send a login success message to client and start working.
  165. func (ctl *Control) Start() {
  166. loginRespMsg := &msg.LoginResp{
  167. Version: version.Full(),
  168. RunID: ctl.runID,
  169. Error: "",
  170. }
  171. _ = msg.WriteMsg(ctl.conn, loginRespMsg)
  172. go func() {
  173. for i := 0; i < ctl.poolCount; i++ {
  174. // ignore error here, that means that this control is closed
  175. _ = ctl.msgDispatcher.Send(&msg.ReqWorkConn{})
  176. }
  177. }()
  178. go ctl.worker()
  179. }
  180. func (ctl *Control) Close() error {
  181. ctl.conn.Close()
  182. return nil
  183. }
  184. func (ctl *Control) Replaced(newCtl *Control) {
  185. xl := ctl.xl
  186. xl.Info("Replaced by client [%s]", newCtl.runID)
  187. ctl.runID = ""
  188. ctl.conn.Close()
  189. }
  190. func (ctl *Control) RegisterWorkConn(conn net.Conn) error {
  191. xl := ctl.xl
  192. defer func() {
  193. if err := recover(); err != nil {
  194. xl.Error("panic error: %v", err)
  195. xl.Error(string(debug.Stack()))
  196. }
  197. }()
  198. select {
  199. case ctl.workConnCh <- conn:
  200. xl.Debug("new work connection registered")
  201. return nil
  202. default:
  203. xl.Debug("work connection pool is full, discarding")
  204. return fmt.Errorf("work connection pool is full, discarding")
  205. }
  206. }
  207. // When frps get one user connection, we get one work connection from the pool and return it.
  208. // If no workConn available in the pool, send message to frpc to get one or more
  209. // and wait until it is available.
  210. // return an error if wait timeout
  211. func (ctl *Control) GetWorkConn() (workConn net.Conn, err error) {
  212. xl := ctl.xl
  213. defer func() {
  214. if err := recover(); err != nil {
  215. xl.Error("panic error: %v", err)
  216. xl.Error(string(debug.Stack()))
  217. }
  218. }()
  219. var ok bool
  220. // get a work connection from the pool
  221. select {
  222. case workConn, ok = <-ctl.workConnCh:
  223. if !ok {
  224. err = pkgerr.ErrCtlClosed
  225. return
  226. }
  227. xl.Debug("get work connection from pool")
  228. default:
  229. // no work connections available in the poll, send message to frpc to get more
  230. if err := ctl.msgDispatcher.Send(&msg.ReqWorkConn{}); err != nil {
  231. return nil, fmt.Errorf("control is already closed")
  232. }
  233. select {
  234. case workConn, ok = <-ctl.workConnCh:
  235. if !ok {
  236. err = pkgerr.ErrCtlClosed
  237. xl.Warn("no work connections available, %v", err)
  238. return
  239. }
  240. case <-time.After(time.Duration(ctl.serverCfg.UserConnTimeout) * time.Second):
  241. err = fmt.Errorf("timeout trying to get work connection")
  242. xl.Warn("%v", err)
  243. return
  244. }
  245. }
  246. // When we get a work connection from pool, replace it with a new one.
  247. _ = ctl.msgDispatcher.Send(&msg.ReqWorkConn{})
  248. return
  249. }
  250. func (ctl *Control) heartbeatWorker() {
  251. xl := ctl.xl
  252. // Don't need application heartbeat if TCPMux is enabled,
  253. // yamux will do same thing.
  254. // TODO(fatedier): let default HeartbeatTimeout to -1 if TCPMux is enabled. Users can still set it to positive value to enable it.
  255. if !lo.FromPtr(ctl.serverCfg.Transport.TCPMux) && ctl.serverCfg.Transport.HeartbeatTimeout > 0 {
  256. go wait.Until(func() {
  257. if time.Since(ctl.lastPing.Load().(time.Time)) > time.Duration(ctl.serverCfg.Transport.HeartbeatTimeout)*time.Second {
  258. xl.Warn("heartbeat timeout")
  259. return
  260. }
  261. }, time.Second, ctl.doneCh)
  262. }
  263. }
  264. // block until Control closed
  265. func (ctl *Control) WaitClosed() {
  266. <-ctl.doneCh
  267. }
  268. func (ctl *Control) worker() {
  269. xl := ctl.xl
  270. go ctl.heartbeatWorker()
  271. go ctl.msgDispatcher.Run()
  272. <-ctl.msgDispatcher.Done()
  273. ctl.conn.Close()
  274. ctl.mu.Lock()
  275. defer ctl.mu.Unlock()
  276. close(ctl.workConnCh)
  277. for workConn := range ctl.workConnCh {
  278. workConn.Close()
  279. }
  280. for _, pxy := range ctl.proxies {
  281. pxy.Close()
  282. ctl.pxyManager.Del(pxy.GetName())
  283. metrics.Server.CloseProxy(pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type)
  284. notifyContent := &plugin.CloseProxyContent{
  285. User: plugin.UserInfo{
  286. User: ctl.loginMsg.User,
  287. Metas: ctl.loginMsg.Metas,
  288. RunID: ctl.loginMsg.RunID,
  289. },
  290. CloseProxy: msg.CloseProxy{
  291. ProxyName: pxy.GetName(),
  292. },
  293. }
  294. go func() {
  295. _ = ctl.pluginManager.CloseProxy(notifyContent)
  296. }()
  297. }
  298. metrics.Server.CloseClient()
  299. xl.Info("client exit success")
  300. close(ctl.doneCh)
  301. }
  302. func (ctl *Control) registerMsgHandlers() {
  303. ctl.msgDispatcher.RegisterHandler(&msg.NewProxy{}, ctl.handleNewProxy)
  304. ctl.msgDispatcher.RegisterHandler(&msg.Ping{}, ctl.handlePing)
  305. ctl.msgDispatcher.RegisterHandler(&msg.NatHoleVisitor{}, msg.AsyncHandler(ctl.handleNatHoleVisitor))
  306. ctl.msgDispatcher.RegisterHandler(&msg.NatHoleClient{}, msg.AsyncHandler(ctl.handleNatHoleClient))
  307. ctl.msgDispatcher.RegisterHandler(&msg.NatHoleReport{}, msg.AsyncHandler(ctl.handleNatHoleReport))
  308. ctl.msgDispatcher.RegisterHandler(&msg.CloseProxy{}, ctl.handleCloseProxy)
  309. }
  310. func (ctl *Control) handleNewProxy(m msg.Message) {
  311. xl := ctl.xl
  312. inMsg := m.(*msg.NewProxy)
  313. content := &plugin.NewProxyContent{
  314. User: plugin.UserInfo{
  315. User: ctl.loginMsg.User,
  316. Metas: ctl.loginMsg.Metas,
  317. RunID: ctl.loginMsg.RunID,
  318. },
  319. NewProxy: *inMsg,
  320. }
  321. var remoteAddr string
  322. retContent, err := ctl.pluginManager.NewProxy(content)
  323. if err == nil {
  324. inMsg = &retContent.NewProxy
  325. remoteAddr, err = ctl.RegisterProxy(inMsg)
  326. }
  327. // register proxy in this control
  328. resp := &msg.NewProxyResp{
  329. ProxyName: inMsg.ProxyName,
  330. }
  331. if err != nil {
  332. xl.Warn("new proxy [%s] type [%s] error: %v", inMsg.ProxyName, inMsg.ProxyType, err)
  333. resp.Error = util.GenerateResponseErrorString(fmt.Sprintf("new proxy [%s] error", inMsg.ProxyName),
  334. err, lo.FromPtr(ctl.serverCfg.DetailedErrorsToClient))
  335. } else {
  336. resp.RemoteAddr = remoteAddr
  337. xl.Info("new proxy [%s] type [%s] success", inMsg.ProxyName, inMsg.ProxyType)
  338. metrics.Server.NewProxy(inMsg.ProxyName, inMsg.ProxyType)
  339. }
  340. _ = ctl.msgDispatcher.Send(resp)
  341. }
  342. func (ctl *Control) handlePing(m msg.Message) {
  343. xl := ctl.xl
  344. inMsg := m.(*msg.Ping)
  345. content := &plugin.PingContent{
  346. User: plugin.UserInfo{
  347. User: ctl.loginMsg.User,
  348. Metas: ctl.loginMsg.Metas,
  349. RunID: ctl.loginMsg.RunID,
  350. },
  351. Ping: *inMsg,
  352. }
  353. retContent, err := ctl.pluginManager.Ping(content)
  354. if err == nil {
  355. inMsg = &retContent.Ping
  356. err = ctl.authVerifier.VerifyPing(inMsg)
  357. }
  358. if err != nil {
  359. xl.Warn("received invalid ping: %v", err)
  360. _ = ctl.msgDispatcher.Send(&msg.Pong{
  361. Error: util.GenerateResponseErrorString("invalid ping", err, lo.FromPtr(ctl.serverCfg.DetailedErrorsToClient)),
  362. })
  363. return
  364. }
  365. ctl.lastPing.Store(time.Now())
  366. xl.Debug("receive heartbeat")
  367. _ = ctl.msgDispatcher.Send(&msg.Pong{})
  368. }
  369. func (ctl *Control) handleNatHoleVisitor(m msg.Message) {
  370. inMsg := m.(*msg.NatHoleVisitor)
  371. ctl.rc.NatHoleController.HandleVisitor(inMsg, ctl.msgTransporter, ctl.loginMsg.User)
  372. }
  373. func (ctl *Control) handleNatHoleClient(m msg.Message) {
  374. inMsg := m.(*msg.NatHoleClient)
  375. ctl.rc.NatHoleController.HandleClient(inMsg, ctl.msgTransporter)
  376. }
  377. func (ctl *Control) handleNatHoleReport(m msg.Message) {
  378. inMsg := m.(*msg.NatHoleReport)
  379. ctl.rc.NatHoleController.HandleReport(inMsg)
  380. }
  381. func (ctl *Control) handleCloseProxy(m msg.Message) {
  382. xl := ctl.xl
  383. inMsg := m.(*msg.CloseProxy)
  384. _ = ctl.CloseProxy(inMsg)
  385. xl.Info("close proxy [%s] success", inMsg.ProxyName)
  386. }
  387. func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (remoteAddr string, err error) {
  388. var pxyConf v1.ProxyConfigurer
  389. // Load configures from NewProxy message and validate.
  390. pxyConf, err = config.NewProxyConfigurerFromMsg(pxyMsg, ctl.serverCfg)
  391. if err != nil {
  392. return
  393. }
  394. // User info
  395. userInfo := plugin.UserInfo{
  396. User: ctl.loginMsg.User,
  397. Metas: ctl.loginMsg.Metas,
  398. RunID: ctl.runID,
  399. }
  400. // NewProxy will return an interface Proxy.
  401. // In fact, it creates different proxies based on the proxy type. We just call run() here.
  402. pxy, err := proxy.NewProxy(ctl.ctx, &proxy.Options{
  403. UserInfo: userInfo,
  404. LoginMsg: ctl.loginMsg,
  405. PoolCount: ctl.poolCount,
  406. ResourceController: ctl.rc,
  407. GetWorkConnFn: ctl.GetWorkConn,
  408. Configurer: pxyConf,
  409. ServerCfg: ctl.serverCfg,
  410. })
  411. if err != nil {
  412. return remoteAddr, err
  413. }
  414. // Check ports used number in each client
  415. if ctl.serverCfg.MaxPortsPerClient > 0 {
  416. ctl.mu.Lock()
  417. if ctl.portsUsedNum+pxy.GetUsedPortsNum() > int(ctl.serverCfg.MaxPortsPerClient) {
  418. ctl.mu.Unlock()
  419. err = fmt.Errorf("exceed the max_ports_per_client")
  420. return
  421. }
  422. ctl.portsUsedNum += pxy.GetUsedPortsNum()
  423. ctl.mu.Unlock()
  424. defer func() {
  425. if err != nil {
  426. ctl.mu.Lock()
  427. ctl.portsUsedNum -= pxy.GetUsedPortsNum()
  428. ctl.mu.Unlock()
  429. }
  430. }()
  431. }
  432. if ctl.pxyManager.Exist(pxyMsg.ProxyName) {
  433. err = fmt.Errorf("proxy [%s] already exists", pxyMsg.ProxyName)
  434. return
  435. }
  436. remoteAddr, err = pxy.Run()
  437. if err != nil {
  438. return
  439. }
  440. defer func() {
  441. if err != nil {
  442. pxy.Close()
  443. }
  444. }()
  445. err = ctl.pxyManager.Add(pxyMsg.ProxyName, pxy)
  446. if err != nil {
  447. return
  448. }
  449. ctl.mu.Lock()
  450. ctl.proxies[pxy.GetName()] = pxy
  451. ctl.mu.Unlock()
  452. return
  453. }
  454. func (ctl *Control) CloseProxy(closeMsg *msg.CloseProxy) (err error) {
  455. ctl.mu.Lock()
  456. pxy, ok := ctl.proxies[closeMsg.ProxyName]
  457. if !ok {
  458. ctl.mu.Unlock()
  459. return
  460. }
  461. if ctl.serverCfg.MaxPortsPerClient > 0 {
  462. ctl.portsUsedNum -= pxy.GetUsedPortsNum()
  463. }
  464. pxy.Close()
  465. ctl.pxyManager.Del(pxy.GetName())
  466. delete(ctl.proxies, closeMsg.ProxyName)
  467. ctl.mu.Unlock()
  468. metrics.Server.CloseProxy(pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type)
  469. notifyContent := &plugin.CloseProxyContent{
  470. User: plugin.UserInfo{
  471. User: ctl.loginMsg.User,
  472. Metas: ctl.loginMsg.Metas,
  473. RunID: ctl.loginMsg.RunID,
  474. },
  475. CloseProxy: msg.CloseProxy{
  476. ProxyName: pxy.GetName(),
  477. },
  478. }
  479. go func() {
  480. _ = ctl.pluginManager.CloseProxy(notifyContent)
  481. }()
  482. return
  483. }