control.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 []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([]Proxy, 0),
  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. for _, pxy := range ctl.proxies {
  228. pxy.Close()
  229. ctl.svr.DelProxy(pxy.GetName())
  230. StatsCloseProxy(pxy.GetConf().GetBaseInfo().ProxyType)
  231. }
  232. ctl.allShutdown.Done()
  233. ctl.conn.Info("client exit success")
  234. StatsCloseClient()
  235. }
  236. func (ctl *Control) manager() {
  237. defer func() {
  238. if err := recover(); err != nil {
  239. ctl.conn.Error("panic error: %v", err)
  240. }
  241. }()
  242. defer ctl.allShutdown.Start()
  243. defer ctl.managerShutdown.Done()
  244. heartbeat := time.NewTicker(time.Second)
  245. defer heartbeat.Stop()
  246. for {
  247. select {
  248. case <-heartbeat.C:
  249. if time.Since(ctl.lastPing) > time.Duration(config.ServerCommonCfg.HeartBeatTimeout)*time.Second {
  250. ctl.conn.Warn("heartbeat timeout")
  251. ctl.allShutdown.Start()
  252. }
  253. case rawMsg, ok := <-ctl.readCh:
  254. if !ok {
  255. return
  256. }
  257. switch m := rawMsg.(type) {
  258. case *msg.NewProxy:
  259. // register proxy in this control
  260. err := ctl.RegisterProxy(m)
  261. resp := &msg.NewProxyResp{
  262. ProxyName: m.ProxyName,
  263. }
  264. if err != nil {
  265. resp.Error = err.Error()
  266. ctl.conn.Warn("new proxy [%s] error: %v", m.ProxyName, err)
  267. } else {
  268. ctl.conn.Info("new proxy [%s] success", m.ProxyName)
  269. StatsNewProxy(m.ProxyName, m.ProxyType)
  270. }
  271. ctl.sendCh <- resp
  272. case *msg.Ping:
  273. ctl.lastPing = time.Now()
  274. ctl.conn.Debug("receive heartbeat")
  275. ctl.sendCh <- &msg.Pong{}
  276. }
  277. }
  278. }
  279. }
  280. func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (err error) {
  281. var pxyConf config.ProxyConf
  282. // Load configures from NewProxy message and check.
  283. pxyConf, err = config.NewProxyConf(pxyMsg)
  284. if err != nil {
  285. return err
  286. }
  287. // NewProxy will return a interface Proxy.
  288. // In fact it create different proxies by different proxy type, we just call run() here.
  289. pxy, err := NewProxy(ctl, pxyConf)
  290. if err != nil {
  291. return err
  292. }
  293. err = pxy.Run()
  294. if err != nil {
  295. return err
  296. }
  297. defer func() {
  298. if err != nil {
  299. pxy.Close()
  300. }
  301. }()
  302. err = ctl.svr.RegisterProxy(pxyMsg.ProxyName, pxy)
  303. if err != nil {
  304. return err
  305. }
  306. ctl.proxies = append(ctl.proxies, pxy)
  307. return nil
  308. }