control.go 12 KB

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