control.go 14 KB

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