service.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. "time"
  18. "github.com/fatedier/frp/assets"
  19. "github.com/fatedier/frp/models/config"
  20. "github.com/fatedier/frp/models/msg"
  21. "github.com/fatedier/frp/utils/log"
  22. "github.com/fatedier/frp/utils/net"
  23. "github.com/fatedier/frp/utils/util"
  24. "github.com/fatedier/frp/utils/version"
  25. "github.com/fatedier/frp/utils/vhost"
  26. )
  27. var ServerService *Service
  28. // Server service.
  29. type Service struct {
  30. // Accept connections from client.
  31. listener net.Listener
  32. // For http proxies, route requests to different clients by hostname and other infomation.
  33. VhostHttpMuxer *vhost.HttpMuxer
  34. // For https proxies, route requests to different clients by hostname and other infomation.
  35. VhostHttpsMuxer *vhost.HttpsMuxer
  36. // Manage all controllers.
  37. ctlManager *ControlManager
  38. // Manage all proxies.
  39. pxyManager *ProxyManager
  40. }
  41. func NewService() (svr *Service, err error) {
  42. svr = &Service{
  43. ctlManager: NewControlManager(),
  44. pxyManager: NewProxyManager(),
  45. }
  46. // Init assets.
  47. err = assets.Load(config.ServerCommonCfg.AssetsDir)
  48. if err != nil {
  49. err = fmt.Errorf("Load assets error: %v", err)
  50. return
  51. }
  52. // Listen for accepting connections from client.
  53. svr.listener, err = net.ListenTcp(config.ServerCommonCfg.BindAddr, config.ServerCommonCfg.BindPort)
  54. if err != nil {
  55. err = fmt.Errorf("Create server listener error, %v", err)
  56. return
  57. }
  58. // Create http vhost muxer.
  59. if config.ServerCommonCfg.VhostHttpPort != 0 {
  60. var l net.Listener
  61. l, err = net.ListenTcp(config.ServerCommonCfg.BindAddr, config.ServerCommonCfg.VhostHttpPort)
  62. if err != nil {
  63. err = fmt.Errorf("Create vhost http listener error, %v", err)
  64. return
  65. }
  66. svr.VhostHttpMuxer, err = vhost.NewHttpMuxer(l, 30*time.Second)
  67. if err != nil {
  68. err = fmt.Errorf("Create vhost httpMuxer error, %v", err)
  69. return
  70. }
  71. }
  72. // Create https vhost muxer.
  73. if config.ServerCommonCfg.VhostHttpsPort != 0 {
  74. var l net.Listener
  75. l, err = net.ListenTcp(config.ServerCommonCfg.BindAddr, config.ServerCommonCfg.VhostHttpsPort)
  76. if err != nil {
  77. err = fmt.Errorf("Create vhost https listener error, %v", err)
  78. return
  79. }
  80. svr.VhostHttpsMuxer, err = vhost.NewHttpsMuxer(l, 30*time.Second)
  81. if err != nil {
  82. err = fmt.Errorf("Create vhost httpsMuxer error, %v", err)
  83. return
  84. }
  85. }
  86. // Create dashboard web server.
  87. if config.ServerCommonCfg.DashboardPort != 0 {
  88. err = RunDashboardServer(config.ServerCommonCfg.BindAddr, config.ServerCommonCfg.DashboardPort)
  89. if err != nil {
  90. err = fmt.Errorf("Create dashboard web server error, %v", err)
  91. return
  92. }
  93. }
  94. return
  95. }
  96. func (svr *Service) Run() {
  97. // Listen for incoming connections from client.
  98. for {
  99. c, err := svr.listener.Accept()
  100. if err != nil {
  101. log.Warn("Listener for incoming connections from client closed")
  102. return
  103. }
  104. // Start a new goroutine for dealing connections.
  105. go func(frpConn net.Conn) {
  106. var rawMsg msg.Message
  107. if rawMsg, err = msg.ReadMsg(frpConn); err != nil {
  108. log.Warn("Failed to read message: %v", err)
  109. frpConn.Close()
  110. return
  111. }
  112. switch m := rawMsg.(type) {
  113. case *msg.Login:
  114. err = svr.RegisterControl(frpConn, m)
  115. // If login failed, send error message there.
  116. // Otherwise send success message in control's work goroutine.
  117. if err != nil {
  118. frpConn.Warn("%v", err)
  119. msg.WriteMsg(frpConn, &msg.LoginResp{
  120. Version: version.Full(),
  121. Error: err.Error(),
  122. })
  123. frpConn.Close()
  124. }
  125. case *msg.NewWorkConn:
  126. svr.RegisterWorkConn(frpConn, m)
  127. default:
  128. log.Warn("Error message type for the new connection [%s]", frpConn.RemoteAddr().String())
  129. frpConn.Close()
  130. }
  131. }(c)
  132. }
  133. }
  134. func (svr *Service) RegisterControl(ctlConn net.Conn, loginMsg *msg.Login) (err error) {
  135. ctlConn.Info("client login info: ip [%s] version [%s] hostname [%s] os [%s] arch [%s]",
  136. ctlConn.RemoteAddr().String(), loginMsg.Version, loginMsg.Hostname, loginMsg.Os, loginMsg.Arch)
  137. // Check client version.
  138. if ok, msg := version.Compat(loginMsg.Version); !ok {
  139. err = fmt.Errorf("%s", msg)
  140. return
  141. }
  142. // Check auth.
  143. nowTime := time.Now().Unix()
  144. if config.ServerCommonCfg.AuthTimeout != 0 && nowTime-loginMsg.Timestamp > config.ServerCommonCfg.AuthTimeout {
  145. err = fmt.Errorf("authorization timeout")
  146. return
  147. }
  148. if util.GetAuthKey(config.ServerCommonCfg.PrivilegeToken, loginMsg.Timestamp) != loginMsg.PrivilegeKey {
  149. err = fmt.Errorf("authorization failed")
  150. return
  151. }
  152. // If client's RunId is empty, it's a new client, we just create a new controller.
  153. // Otherwise, we check if there is one controller has the same run id. If so, we release previous controller and start new one.
  154. if loginMsg.RunId == "" {
  155. loginMsg.RunId, err = util.RandId()
  156. if err != nil {
  157. return
  158. }
  159. }
  160. ctl := NewControl(svr, ctlConn, loginMsg)
  161. if oldCtl := svr.ctlManager.Add(loginMsg.RunId, ctl); oldCtl != nil {
  162. oldCtl.allShutdown.WaitDown()
  163. }
  164. ctlConn.AddLogPrefix(loginMsg.RunId)
  165. ctl.Start()
  166. // for statistics
  167. StatsNewClient()
  168. return
  169. }
  170. // RegisterWorkConn register a new work connection to control and proxies need it.
  171. func (svr *Service) RegisterWorkConn(workConn net.Conn, newMsg *msg.NewWorkConn) {
  172. ctl, exist := svr.ctlManager.GetById(newMsg.RunId)
  173. if !exist {
  174. workConn.Warn("No client control found for run id [%s]", newMsg.RunId)
  175. return
  176. }
  177. ctl.RegisterWorkConn(workConn)
  178. return
  179. }
  180. func (svr *Service) RegisterProxy(name string, pxy Proxy) error {
  181. err := svr.pxyManager.Add(name, pxy)
  182. return err
  183. }
  184. func (svr *Service) DelProxy(name string) {
  185. svr.pxyManager.Del(name)
  186. }