control.go 14 KB

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