control.go 13 KB

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