service.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. "bytes"
  17. "context"
  18. "crypto/tls"
  19. "fmt"
  20. "io"
  21. "net"
  22. "net/http"
  23. "sort"
  24. "strconv"
  25. "time"
  26. "github.com/fatedier/frp/assets"
  27. "github.com/fatedier/frp/pkg/auth"
  28. "github.com/fatedier/frp/pkg/config"
  29. modelmetrics "github.com/fatedier/frp/pkg/metrics"
  30. "github.com/fatedier/frp/pkg/msg"
  31. "github.com/fatedier/frp/pkg/nathole"
  32. plugin "github.com/fatedier/frp/pkg/plugin/server"
  33. "github.com/fatedier/frp/pkg/transport"
  34. "github.com/fatedier/frp/pkg/util/log"
  35. frpNet "github.com/fatedier/frp/pkg/util/net"
  36. "github.com/fatedier/frp/pkg/util/tcpmux"
  37. "github.com/fatedier/frp/pkg/util/util"
  38. "github.com/fatedier/frp/pkg/util/version"
  39. "github.com/fatedier/frp/pkg/util/vhost"
  40. "github.com/fatedier/frp/pkg/util/xlog"
  41. "github.com/fatedier/frp/server/controller"
  42. "github.com/fatedier/frp/server/group"
  43. "github.com/fatedier/frp/server/metrics"
  44. "github.com/fatedier/frp/server/ports"
  45. "github.com/fatedier/frp/server/proxy"
  46. "github.com/fatedier/frp/server/visitor"
  47. "github.com/fatedier/golib/net/mux"
  48. fmux "github.com/hashicorp/yamux"
  49. )
  50. const (
  51. connReadTimeout time.Duration = 10 * time.Second
  52. vhostReadWriteTimeout time.Duration = 30 * time.Second
  53. )
  54. // Server service
  55. type Service struct {
  56. // Dispatch connections to different handlers listen on same port
  57. muxer *mux.Mux
  58. // Accept connections from client
  59. listener net.Listener
  60. // Accept connections using kcp
  61. kcpListener net.Listener
  62. // Accept connections using websocket
  63. websocketListener net.Listener
  64. // Accept frp tls connections
  65. tlsListener net.Listener
  66. // Manage all controllers
  67. ctlManager *ControlManager
  68. // Manage all proxies
  69. pxyManager *proxy.Manager
  70. // Manage all plugins
  71. pluginManager *plugin.Manager
  72. // HTTP vhost router
  73. httpVhostRouter *vhost.Routers
  74. // All resource managers and controllers
  75. rc *controller.ResourceController
  76. // Verifies authentication based on selected method
  77. authVerifier auth.Verifier
  78. tlsConfig *tls.Config
  79. cfg config.ServerCommonConf
  80. }
  81. func NewService(cfg config.ServerCommonConf) (svr *Service, err error) {
  82. tlsConfig, err := transport.NewServerTLSConfig(
  83. cfg.TLSCertFile,
  84. cfg.TLSKeyFile,
  85. cfg.TLSTrustedCaFile)
  86. if err != nil {
  87. return
  88. }
  89. svr = &Service{
  90. ctlManager: NewControlManager(),
  91. pxyManager: proxy.NewManager(),
  92. pluginManager: plugin.NewManager(),
  93. rc: &controller.ResourceController{
  94. VisitorManager: visitor.NewManager(),
  95. TCPPortManager: ports.NewManager("tcp", cfg.ProxyBindAddr, cfg.AllowPorts),
  96. UDPPortManager: ports.NewManager("udp", cfg.ProxyBindAddr, cfg.AllowPorts),
  97. },
  98. httpVhostRouter: vhost.NewRouters(),
  99. authVerifier: auth.NewAuthVerifier(cfg.ServerConfig),
  100. tlsConfig: tlsConfig,
  101. cfg: cfg,
  102. }
  103. // Create tcpmux httpconnect multiplexer.
  104. if cfg.TCPMuxHTTPConnectPort > 0 {
  105. var l net.Listener
  106. address := net.JoinHostPort(cfg.ProxyBindAddr, strconv.Itoa(cfg.TCPMuxHTTPConnectPort))
  107. l, err = net.Listen("tcp", address)
  108. if err != nil {
  109. err = fmt.Errorf("Create server listener error, %v", err)
  110. return
  111. }
  112. svr.rc.TCPMuxHTTPConnectMuxer, err = tcpmux.NewHTTPConnectTCPMuxer(l, vhostReadWriteTimeout)
  113. if err != nil {
  114. err = fmt.Errorf("Create vhost tcpMuxer error, %v", err)
  115. return
  116. }
  117. log.Info("tcpmux httpconnect multiplexer listen on %s", address)
  118. }
  119. // Init all plugins
  120. plugin_names := make([]string, 0, len(cfg.HTTPPlugins))
  121. for n := range cfg.HTTPPlugins {
  122. plugin_names = append(plugin_names, n)
  123. }
  124. sort.Strings(plugin_names)
  125. for _, name := range plugin_names {
  126. svr.pluginManager.Register(plugin.NewHTTPPluginOptions(cfg.HTTPPlugins[name]))
  127. log.Info("plugin [%s] has been registered", name)
  128. }
  129. svr.rc.PluginManager = svr.pluginManager
  130. // Init group controller
  131. svr.rc.TCPGroupCtl = group.NewTCPGroupCtl(svr.rc.TCPPortManager)
  132. // Init HTTP group controller
  133. svr.rc.HTTPGroupCtl = group.NewHTTPGroupController(svr.httpVhostRouter)
  134. // Init TCP mux group controller
  135. svr.rc.TCPMuxGroupCtl = group.NewTCPMuxGroupCtl(svr.rc.TCPMuxHTTPConnectMuxer)
  136. // Init 404 not found page
  137. vhost.NotFoundPagePath = cfg.Custom404Page
  138. var (
  139. httpMuxOn bool
  140. httpsMuxOn bool
  141. )
  142. if cfg.BindAddr == cfg.ProxyBindAddr {
  143. if cfg.BindPort == cfg.VhostHTTPPort {
  144. httpMuxOn = true
  145. }
  146. if cfg.BindPort == cfg.VhostHTTPSPort {
  147. httpsMuxOn = true
  148. }
  149. }
  150. // Listen for accepting connections from client.
  151. address := net.JoinHostPort(cfg.BindAddr, strconv.Itoa(cfg.BindPort))
  152. ln, err := net.Listen("tcp", address)
  153. if err != nil {
  154. err = fmt.Errorf("Create server listener error, %v", err)
  155. return
  156. }
  157. svr.muxer = mux.NewMux(ln)
  158. go svr.muxer.Serve()
  159. ln = svr.muxer.DefaultListener()
  160. svr.listener = ln
  161. log.Info("frps tcp listen on %s", address)
  162. // Listen for accepting connections from client using kcp protocol.
  163. if cfg.KCPBindPort > 0 {
  164. address := net.JoinHostPort(cfg.BindAddr, strconv.Itoa(cfg.KCPBindPort))
  165. svr.kcpListener, err = frpNet.ListenKcp(address)
  166. if err != nil {
  167. err = fmt.Errorf("Listen on kcp address udp %s error: %v", address, err)
  168. return
  169. }
  170. log.Info("frps kcp listen on udp %s", address)
  171. }
  172. // Listen for accepting connections from client using websocket protocol.
  173. websocketPrefix := []byte("GET " + frpNet.FrpWebsocketPath)
  174. websocketLn := svr.muxer.Listen(0, uint32(len(websocketPrefix)), func(data []byte) bool {
  175. return bytes.Equal(data, websocketPrefix)
  176. })
  177. svr.websocketListener = frpNet.NewWebsocketListener(websocketLn)
  178. // Create http vhost muxer.
  179. if cfg.VhostHTTPPort > 0 {
  180. rp := vhost.NewHTTPReverseProxy(vhost.HTTPReverseProxyOptions{
  181. ResponseHeaderTimeoutS: cfg.VhostHTTPTimeout,
  182. }, svr.httpVhostRouter)
  183. svr.rc.HTTPReverseProxy = rp
  184. address := net.JoinHostPort(cfg.ProxyBindAddr, strconv.Itoa(cfg.VhostHTTPPort))
  185. server := &http.Server{
  186. Addr: address,
  187. Handler: rp,
  188. }
  189. var l net.Listener
  190. if httpMuxOn {
  191. l = svr.muxer.ListenHttp(1)
  192. } else {
  193. l, err = net.Listen("tcp", address)
  194. if err != nil {
  195. err = fmt.Errorf("Create vhost http listener error, %v", err)
  196. return
  197. }
  198. }
  199. go server.Serve(l)
  200. log.Info("http service listen on %s", address)
  201. }
  202. // Create https vhost muxer.
  203. if cfg.VhostHTTPSPort > 0 {
  204. var l net.Listener
  205. if httpsMuxOn {
  206. l = svr.muxer.ListenHttps(1)
  207. } else {
  208. address := net.JoinHostPort(cfg.ProxyBindAddr, strconv.Itoa(cfg.VhostHTTPSPort))
  209. l, err = net.Listen("tcp", address)
  210. if err != nil {
  211. err = fmt.Errorf("Create server listener error, %v", err)
  212. return
  213. }
  214. log.Info("https service listen on %s", address)
  215. }
  216. svr.rc.VhostHTTPSMuxer, err = vhost.NewHTTPSMuxer(l, vhostReadWriteTimeout)
  217. if err != nil {
  218. err = fmt.Errorf("Create vhost httpsMuxer error, %v", err)
  219. return
  220. }
  221. }
  222. // frp tls listener
  223. svr.tlsListener = svr.muxer.Listen(2, 1, func(data []byte) bool {
  224. // tls first byte can be 0x16 only when vhost https port is not same with bind port
  225. return int(data[0]) == frpNet.FRPTLSHeadByte || int(data[0]) == 0x16
  226. })
  227. // Create nat hole controller.
  228. if cfg.BindUDPPort > 0 {
  229. var nc *nathole.Controller
  230. address := net.JoinHostPort(cfg.BindAddr, strconv.Itoa(cfg.BindUDPPort))
  231. nc, err = nathole.NewController(address)
  232. if err != nil {
  233. err = fmt.Errorf("Create nat hole controller error, %v", err)
  234. return
  235. }
  236. svr.rc.NatHoleController = nc
  237. log.Info("nat hole udp service listen on %s", address)
  238. }
  239. var statsEnable bool
  240. // Create dashboard web server.
  241. if cfg.DashboardPort > 0 {
  242. // Init dashboard assets
  243. assets.Load(cfg.AssetsDir)
  244. address := net.JoinHostPort(cfg.DashboardAddr, strconv.Itoa(cfg.DashboardPort))
  245. err = svr.RunDashboardServer(address)
  246. if err != nil {
  247. err = fmt.Errorf("Create dashboard web server error, %v", err)
  248. return
  249. }
  250. log.Info("Dashboard listen on %s", address)
  251. statsEnable = true
  252. }
  253. if statsEnable {
  254. modelmetrics.EnableMem()
  255. if cfg.EnablePrometheus {
  256. modelmetrics.EnablePrometheus()
  257. }
  258. }
  259. return
  260. }
  261. func (svr *Service) Run() {
  262. if svr.rc.NatHoleController != nil {
  263. go svr.rc.NatHoleController.Run()
  264. }
  265. if svr.cfg.KCPBindPort > 0 {
  266. go svr.HandleListener(svr.kcpListener)
  267. }
  268. go svr.HandleListener(svr.websocketListener)
  269. go svr.HandleListener(svr.tlsListener)
  270. svr.HandleListener(svr.listener)
  271. }
  272. func (svr *Service) handleConnection(ctx context.Context, conn net.Conn) {
  273. xl := xlog.FromContextSafe(ctx)
  274. var (
  275. rawMsg msg.Message
  276. err error
  277. )
  278. conn.SetReadDeadline(time.Now().Add(connReadTimeout))
  279. if rawMsg, err = msg.ReadMsg(conn); err != nil {
  280. log.Trace("Failed to read message: %v", err)
  281. conn.Close()
  282. return
  283. }
  284. conn.SetReadDeadline(time.Time{})
  285. switch m := rawMsg.(type) {
  286. case *msg.Login:
  287. // server plugin hook
  288. content := &plugin.LoginContent{
  289. Login: *m,
  290. ClientAddress: conn.RemoteAddr().String(),
  291. }
  292. retContent, err := svr.pluginManager.Login(content)
  293. if err == nil {
  294. m = &retContent.Login
  295. err = svr.RegisterControl(conn, m)
  296. }
  297. // If login failed, send error message there.
  298. // Otherwise send success message in control's work goroutine.
  299. if err != nil {
  300. xl.Warn("register control error: %v", err)
  301. msg.WriteMsg(conn, &msg.LoginResp{
  302. Version: version.Full(),
  303. Error: util.GenerateResponseErrorString("register control error", err, svr.cfg.DetailedErrorsToClient),
  304. })
  305. conn.Close()
  306. }
  307. case *msg.NewWorkConn:
  308. if err := svr.RegisterWorkConn(conn, m); err != nil {
  309. conn.Close()
  310. }
  311. case *msg.NewVisitorConn:
  312. if err = svr.RegisterVisitorConn(conn, m); err != nil {
  313. xl.Warn("register visitor conn error: %v", err)
  314. msg.WriteMsg(conn, &msg.NewVisitorConnResp{
  315. ProxyName: m.ProxyName,
  316. Error: util.GenerateResponseErrorString("register visitor conn error", err, svr.cfg.DetailedErrorsToClient),
  317. })
  318. conn.Close()
  319. } else {
  320. msg.WriteMsg(conn, &msg.NewVisitorConnResp{
  321. ProxyName: m.ProxyName,
  322. Error: "",
  323. })
  324. }
  325. default:
  326. log.Warn("Error message type for the new connection [%s]", conn.RemoteAddr().String())
  327. conn.Close()
  328. }
  329. }
  330. func (svr *Service) HandleListener(l net.Listener) {
  331. // Listen for incoming connections from client.
  332. for {
  333. c, err := l.Accept()
  334. if err != nil {
  335. log.Warn("Listener for incoming connections from client closed")
  336. return
  337. }
  338. // inject xlog object into net.Conn context
  339. xl := xlog.New()
  340. ctx := context.Background()
  341. c = frpNet.NewContextConn(xlog.NewContext(ctx, xl), c)
  342. log.Trace("start check TLS connection...")
  343. originConn := c
  344. var isTLS, custom bool
  345. c, isTLS, custom, err = frpNet.CheckAndEnableTLSServerConnWithTimeout(c, svr.tlsConfig, svr.cfg.TLSOnly, connReadTimeout)
  346. if err != nil {
  347. log.Warn("CheckAndEnableTLSServerConnWithTimeout error: %v", err)
  348. originConn.Close()
  349. continue
  350. }
  351. log.Trace("check TLS connection success, isTLS: %v custom: %v", isTLS, custom)
  352. // Start a new goroutine to handle connection.
  353. go func(ctx context.Context, frpConn net.Conn) {
  354. if svr.cfg.TCPMux {
  355. fmuxCfg := fmux.DefaultConfig()
  356. fmuxCfg.KeepAliveInterval = time.Duration(svr.cfg.TCPMuxKeepaliveInterval) * time.Second
  357. fmuxCfg.LogOutput = io.Discard
  358. session, err := fmux.Server(frpConn, fmuxCfg)
  359. if err != nil {
  360. log.Warn("Failed to create mux connection: %v", err)
  361. frpConn.Close()
  362. return
  363. }
  364. for {
  365. stream, err := session.AcceptStream()
  366. if err != nil {
  367. log.Debug("Accept new mux stream error: %v", err)
  368. session.Close()
  369. return
  370. }
  371. go svr.handleConnection(ctx, stream)
  372. }
  373. } else {
  374. svr.handleConnection(ctx, frpConn)
  375. }
  376. }(ctx, c)
  377. }
  378. }
  379. func (svr *Service) RegisterControl(ctlConn net.Conn, loginMsg *msg.Login) (err error) {
  380. // If client's RunID is empty, it's a new client, we just create a new controller.
  381. // Otherwise, we check if there is one controller has the same run id. If so, we release previous controller and start new one.
  382. if loginMsg.RunID == "" {
  383. loginMsg.RunID, err = util.RandID()
  384. if err != nil {
  385. return
  386. }
  387. }
  388. ctx := frpNet.NewContextFromConn(ctlConn)
  389. xl := xlog.FromContextSafe(ctx)
  390. xl.AppendPrefix(loginMsg.RunID)
  391. ctx = xlog.NewContext(ctx, xl)
  392. xl.Info("client login info: ip [%s] version [%s] hostname [%s] os [%s] arch [%s]",
  393. ctlConn.RemoteAddr().String(), loginMsg.Version, loginMsg.Hostname, loginMsg.Os, loginMsg.Arch)
  394. // Check client version.
  395. if ok, msg := version.Compat(loginMsg.Version); !ok {
  396. err = fmt.Errorf("%s", msg)
  397. return
  398. }
  399. // Check auth.
  400. if err = svr.authVerifier.VerifyLogin(loginMsg); err != nil {
  401. return
  402. }
  403. ctl := NewControl(ctx, svr.rc, svr.pxyManager, svr.pluginManager, svr.authVerifier, ctlConn, loginMsg, svr.cfg)
  404. if oldCtl := svr.ctlManager.Add(loginMsg.RunID, ctl); oldCtl != nil {
  405. oldCtl.allShutdown.WaitDone()
  406. }
  407. ctl.Start()
  408. // for statistics
  409. metrics.Server.NewClient()
  410. go func() {
  411. // block until control closed
  412. ctl.WaitClosed()
  413. svr.ctlManager.Del(loginMsg.RunID, ctl)
  414. }()
  415. return
  416. }
  417. // RegisterWorkConn register a new work connection to control and proxies need it.
  418. func (svr *Service) RegisterWorkConn(workConn net.Conn, newMsg *msg.NewWorkConn) error {
  419. xl := frpNet.NewLogFromConn(workConn)
  420. ctl, exist := svr.ctlManager.GetByID(newMsg.RunID)
  421. if !exist {
  422. xl.Warn("No client control found for run id [%s]", newMsg.RunID)
  423. return fmt.Errorf("no client control found for run id [%s]", newMsg.RunID)
  424. }
  425. // server plugin hook
  426. content := &plugin.NewWorkConnContent{
  427. User: plugin.UserInfo{
  428. User: ctl.loginMsg.User,
  429. Metas: ctl.loginMsg.Metas,
  430. RunID: ctl.loginMsg.RunID,
  431. },
  432. NewWorkConn: *newMsg,
  433. }
  434. retContent, err := svr.pluginManager.NewWorkConn(content)
  435. if err == nil {
  436. newMsg = &retContent.NewWorkConn
  437. // Check auth.
  438. err = svr.authVerifier.VerifyNewWorkConn(newMsg)
  439. }
  440. if err != nil {
  441. xl.Warn("invalid NewWorkConn with run id [%s]", newMsg.RunID)
  442. msg.WriteMsg(workConn, &msg.StartWorkConn{
  443. Error: util.GenerateResponseErrorString("invalid NewWorkConn", err, ctl.serverCfg.DetailedErrorsToClient),
  444. })
  445. return fmt.Errorf("invalid NewWorkConn with run id [%s]", newMsg.RunID)
  446. }
  447. return ctl.RegisterWorkConn(workConn)
  448. }
  449. func (svr *Service) RegisterVisitorConn(visitorConn net.Conn, newMsg *msg.NewVisitorConn) error {
  450. return svr.rc.VisitorManager.NewConn(newMsg.ProxyName, visitorConn, newMsg.Timestamp, newMsg.SignKey,
  451. newMsg.UseEncryption, newMsg.UseCompression)
  452. }