control.go 13 KB

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