control.go 9.9 KB

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