control.go 12 KB

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