control.go 8.8 KB

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