1
0

control.go 12 KB

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