control.go 9.7 KB

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