control.go 9.6 KB

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