control.go 12 KB

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