control.go 12 KB

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