control.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. ServerUdpPort: config.ServerCommonCfg.BindUdpPort,
  85. Error: "",
  86. }
  87. msg.WriteMsg(ctl.conn, loginRespMsg)
  88. go ctl.writer()
  89. for i := 0; i < ctl.poolCount; i++ {
  90. ctl.sendCh <- &msg.ReqWorkConn{}
  91. }
  92. go ctl.manager()
  93. go ctl.reader()
  94. go ctl.stoper()
  95. }
  96. func (ctl *Control) RegisterWorkConn(conn net.Conn) {
  97. defer func() {
  98. if err := recover(); err != nil {
  99. ctl.conn.Error("panic error: %v", err)
  100. }
  101. }()
  102. select {
  103. case ctl.workConnCh <- conn:
  104. ctl.conn.Debug("new work connection registered")
  105. default:
  106. ctl.conn.Debug("work connection pool is full, discarding")
  107. conn.Close()
  108. }
  109. }
  110. // When frps get one user connection, we get one work connection from the pool and return it.
  111. // If no workConn available in the pool, send message to frpc to get one or more
  112. // and wait until it is available.
  113. // return an error if wait timeout
  114. func (ctl *Control) GetWorkConn() (workConn net.Conn, err error) {
  115. defer func() {
  116. if err := recover(); err != nil {
  117. ctl.conn.Error("panic error: %v", err)
  118. }
  119. }()
  120. var ok bool
  121. // get a work connection from the pool
  122. select {
  123. case workConn, ok = <-ctl.workConnCh:
  124. if !ok {
  125. err = errors.ErrCtlClosed
  126. return
  127. }
  128. ctl.conn.Debug("get work connection from pool")
  129. default:
  130. // no work connections available in the poll, send message to frpc to get more
  131. err = errors.PanicToError(func() {
  132. ctl.sendCh <- &msg.ReqWorkConn{}
  133. })
  134. if err != nil {
  135. ctl.conn.Error("%v", err)
  136. return
  137. }
  138. select {
  139. case workConn, ok = <-ctl.workConnCh:
  140. if !ok {
  141. err = errors.ErrCtlClosed
  142. ctl.conn.Warn("no work connections avaiable, %v", err)
  143. return
  144. }
  145. case <-time.After(time.Duration(config.ServerCommonCfg.UserConnTimeout) * time.Second):
  146. err = fmt.Errorf("timeout trying to get work connection")
  147. ctl.conn.Warn("%v", err)
  148. return
  149. }
  150. }
  151. // When we get a work connection from pool, replace it with a new one.
  152. errors.PanicToError(func() {
  153. ctl.sendCh <- &msg.ReqWorkConn{}
  154. })
  155. return
  156. }
  157. func (ctl *Control) Replaced(newCtl *Control) {
  158. ctl.conn.Info("Replaced by client [%s]", newCtl.runId)
  159. ctl.runId = ""
  160. ctl.allShutdown.Start()
  161. }
  162. func (ctl *Control) writer() {
  163. defer func() {
  164. if err := recover(); err != nil {
  165. ctl.conn.Error("panic error: %v", err)
  166. }
  167. }()
  168. defer ctl.allShutdown.Start()
  169. defer ctl.writerShutdown.Done()
  170. encWriter, err := crypto.NewWriter(ctl.conn, []byte(config.ServerCommonCfg.PrivilegeToken))
  171. if err != nil {
  172. ctl.conn.Error("crypto new writer error: %v", err)
  173. ctl.allShutdown.Start()
  174. return
  175. }
  176. for {
  177. if m, ok := <-ctl.sendCh; !ok {
  178. ctl.conn.Info("control writer is closing")
  179. return
  180. } else {
  181. if err := msg.WriteMsg(encWriter, m); err != nil {
  182. ctl.conn.Warn("write message to control connection error: %v", err)
  183. return
  184. }
  185. }
  186. }
  187. }
  188. func (ctl *Control) reader() {
  189. defer func() {
  190. if err := recover(); err != nil {
  191. ctl.conn.Error("panic error: %v", err)
  192. }
  193. }()
  194. defer ctl.allShutdown.Start()
  195. defer ctl.readerShutdown.Done()
  196. encReader := crypto.NewReader(ctl.conn, []byte(config.ServerCommonCfg.PrivilegeToken))
  197. for {
  198. if m, err := msg.ReadMsg(encReader); err != nil {
  199. if err == io.EOF {
  200. ctl.conn.Debug("control connection closed")
  201. return
  202. } else {
  203. ctl.conn.Warn("read error: %v", err)
  204. return
  205. }
  206. } else {
  207. ctl.readCh <- m
  208. }
  209. }
  210. }
  211. func (ctl *Control) stoper() {
  212. defer func() {
  213. if err := recover(); err != nil {
  214. ctl.conn.Error("panic error: %v", err)
  215. }
  216. }()
  217. ctl.allShutdown.WaitStart()
  218. close(ctl.readCh)
  219. ctl.managerShutdown.WaitDone()
  220. close(ctl.sendCh)
  221. ctl.writerShutdown.WaitDone()
  222. ctl.conn.Close()
  223. ctl.readerShutdown.WaitDone()
  224. close(ctl.workConnCh)
  225. for workConn := range ctl.workConnCh {
  226. workConn.Close()
  227. }
  228. ctl.mu.Lock()
  229. defer ctl.mu.Unlock()
  230. for _, pxy := range ctl.proxies {
  231. pxy.Close()
  232. ctl.svr.DelProxy(pxy.GetName())
  233. StatsCloseProxy(pxy.GetName(), pxy.GetConf().GetBaseInfo().ProxyType)
  234. }
  235. ctl.allShutdown.Done()
  236. ctl.conn.Info("client exit success")
  237. StatsCloseClient()
  238. }
  239. func (ctl *Control) manager() {
  240. defer func() {
  241. if err := recover(); err != nil {
  242. ctl.conn.Error("panic error: %v", err)
  243. }
  244. }()
  245. defer ctl.allShutdown.Start()
  246. defer ctl.managerShutdown.Done()
  247. heartbeat := time.NewTicker(time.Second)
  248. defer heartbeat.Stop()
  249. for {
  250. select {
  251. case <-heartbeat.C:
  252. if time.Since(ctl.lastPing) > time.Duration(config.ServerCommonCfg.HeartBeatTimeout)*time.Second {
  253. ctl.conn.Warn("heartbeat timeout")
  254. ctl.allShutdown.Start()
  255. }
  256. case rawMsg, ok := <-ctl.readCh:
  257. if !ok {
  258. return
  259. }
  260. switch m := rawMsg.(type) {
  261. case *msg.NewProxy:
  262. // register proxy in this control
  263. remoteAddr, err := ctl.RegisterProxy(m)
  264. resp := &msg.NewProxyResp{
  265. ProxyName: m.ProxyName,
  266. }
  267. if err != nil {
  268. resp.Error = err.Error()
  269. ctl.conn.Warn("new proxy [%s] error: %v", m.ProxyName, err)
  270. } else {
  271. resp.RemoteAddr = remoteAddr
  272. ctl.conn.Info("new proxy [%s] success", m.ProxyName)
  273. StatsNewProxy(m.ProxyName, m.ProxyType)
  274. }
  275. ctl.sendCh <- resp
  276. case *msg.CloseProxy:
  277. ctl.CloseProxy(m)
  278. ctl.conn.Info("close proxy [%s] success", m.ProxyName)
  279. case *msg.Ping:
  280. ctl.lastPing = time.Now()
  281. ctl.conn.Debug("receive heartbeat")
  282. ctl.sendCh <- &msg.Pong{}
  283. }
  284. }
  285. }
  286. }
  287. func (ctl *Control) RegisterProxy(pxyMsg *msg.NewProxy) (remoteAddr string, err error) {
  288. var pxyConf config.ProxyConf
  289. // Load configures from NewProxy message and check.
  290. pxyConf, err = config.NewProxyConf(pxyMsg)
  291. if err != nil {
  292. return
  293. }
  294. // NewProxy will return a interface Proxy.
  295. // In fact it create different proxies by different proxy type, we just call run() here.
  296. pxy, err := NewProxy(ctl, pxyConf)
  297. if err != nil {
  298. return remoteAddr, err
  299. }
  300. remoteAddr, err = pxy.Run()
  301. if err != nil {
  302. return
  303. }
  304. defer func() {
  305. if err != nil {
  306. pxy.Close()
  307. }
  308. }()
  309. err = ctl.svr.RegisterProxy(pxyMsg.ProxyName, pxy)
  310. if err != nil {
  311. return
  312. }
  313. ctl.mu.Lock()
  314. ctl.proxies[pxy.GetName()] = pxy
  315. ctl.mu.Unlock()
  316. return
  317. }
  318. func (ctl *Control) CloseProxy(closeMsg *msg.CloseProxy) (err error) {
  319. ctl.mu.Lock()
  320. defer ctl.mu.Unlock()
  321. pxy, ok := ctl.proxies[closeMsg.ProxyName]
  322. if !ok {
  323. return
  324. }
  325. pxy.Close()
  326. ctl.svr.DelProxy(pxy.GetName())
  327. delete(ctl.proxies, closeMsg.ProxyName)
  328. StatsCloseProxy(pxy.GetName(), pxy.GetConf().GetBaseInfo().ProxyType)
  329. return
  330. }