control.go 7.5 KB

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