control.go 12 KB

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