1
0

control.go 14 KB

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