control.go 9.7 KB

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