control.go 14 KB

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