proxy.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. "context"
  17. "fmt"
  18. "io"
  19. "net"
  20. "sync"
  21. "time"
  22. "github.com/fatedier/frp/models/config"
  23. "github.com/fatedier/frp/models/msg"
  24. "github.com/fatedier/frp/models/proto/udp"
  25. "github.com/fatedier/frp/utils/errors"
  26. frpIo "github.com/fatedier/frp/utils/io"
  27. "github.com/fatedier/frp/utils/log"
  28. frpNet "github.com/fatedier/frp/utils/net"
  29. "github.com/fatedier/frp/utils/vhost"
  30. )
  31. type Proxy interface {
  32. Run() error
  33. GetControl() *Control
  34. GetName() string
  35. GetConf() config.ProxyConf
  36. GetWorkConnFromPool() (workConn frpNet.Conn, err error)
  37. Close()
  38. log.Logger
  39. }
  40. type BaseProxy struct {
  41. name string
  42. ctl *Control
  43. listeners []frpNet.Listener
  44. mu sync.RWMutex
  45. log.Logger
  46. }
  47. func (pxy *BaseProxy) GetName() string {
  48. return pxy.name
  49. }
  50. func (pxy *BaseProxy) GetControl() *Control {
  51. return pxy.ctl
  52. }
  53. func (pxy *BaseProxy) Close() {
  54. pxy.Info("proxy closing")
  55. for _, l := range pxy.listeners {
  56. l.Close()
  57. }
  58. }
  59. func (pxy *BaseProxy) GetWorkConnFromPool() (workConn frpNet.Conn, err error) {
  60. ctl := pxy.GetControl()
  61. // try all connections from the pool
  62. for i := 0; i < ctl.poolCount+1; i++ {
  63. if workConn, err = ctl.GetWorkConn(); err != nil {
  64. pxy.Warn("failed to get work connection: %v", err)
  65. return
  66. }
  67. pxy.Info("get a new work connection: [%s]", workConn.RemoteAddr().String())
  68. workConn.AddLogPrefix(pxy.GetName())
  69. err := msg.WriteMsg(workConn, &msg.StartWorkConn{
  70. ProxyName: pxy.GetName(),
  71. })
  72. if err != nil {
  73. workConn.Warn("failed to send message to work connection from pool: %v, times: %d", err, i)
  74. workConn.Close()
  75. } else {
  76. break
  77. }
  78. }
  79. if err != nil {
  80. pxy.Error("try to get work connection failed in the end")
  81. return
  82. }
  83. return
  84. }
  85. // startListenHandler start a goroutine handler for each listener.
  86. // p: p will just be passed to handler(Proxy, frpNet.Conn).
  87. // handler: each proxy type can set different handler function to deal with connections accepted from listeners.
  88. func (pxy *BaseProxy) startListenHandler(p Proxy, handler func(Proxy, frpNet.Conn)) {
  89. for _, listener := range pxy.listeners {
  90. go func(l frpNet.Listener) {
  91. for {
  92. // block
  93. // if listener is closed, err returned
  94. c, err := l.Accept()
  95. if err != nil {
  96. pxy.Info("listener is closed")
  97. return
  98. }
  99. pxy.Debug("get a user connection [%s]", c.RemoteAddr().String())
  100. go handler(p, c)
  101. }
  102. }(listener)
  103. }
  104. }
  105. func NewProxy(ctl *Control, pxyConf config.ProxyConf) (pxy Proxy, err error) {
  106. basePxy := BaseProxy{
  107. name: pxyConf.GetName(),
  108. ctl: ctl,
  109. listeners: make([]frpNet.Listener, 0),
  110. Logger: log.NewPrefixLogger(ctl.runId),
  111. }
  112. switch cfg := pxyConf.(type) {
  113. case *config.TcpProxyConf:
  114. pxy = &TcpProxy{
  115. BaseProxy: basePxy,
  116. cfg: cfg,
  117. }
  118. case *config.HttpProxyConf:
  119. pxy = &HttpProxy{
  120. BaseProxy: basePxy,
  121. cfg: cfg,
  122. }
  123. case *config.HttpsProxyConf:
  124. pxy = &HttpsProxy{
  125. BaseProxy: basePxy,
  126. cfg: cfg,
  127. }
  128. case *config.UdpProxyConf:
  129. pxy = &UdpProxy{
  130. BaseProxy: basePxy,
  131. cfg: cfg,
  132. }
  133. case *config.StcpProxyConf:
  134. pxy = &StcpProxy{
  135. BaseProxy: basePxy,
  136. cfg: cfg,
  137. }
  138. case *config.XtcpProxyConf:
  139. pxy = &XtcpProxy{
  140. BaseProxy: basePxy,
  141. cfg: cfg,
  142. }
  143. default:
  144. return pxy, fmt.Errorf("proxy type not support")
  145. }
  146. pxy.AddLogPrefix(pxy.GetName())
  147. return
  148. }
  149. type TcpProxy struct {
  150. BaseProxy
  151. cfg *config.TcpProxyConf
  152. }
  153. func (pxy *TcpProxy) Run() error {
  154. listener, err := frpNet.ListenTcp(config.ServerCommonCfg.ProxyBindAddr, pxy.cfg.RemotePort)
  155. if err != nil {
  156. return err
  157. }
  158. listener.AddLogPrefix(pxy.name)
  159. pxy.listeners = append(pxy.listeners, listener)
  160. pxy.Info("tcp proxy listen port [%d]", pxy.cfg.RemotePort)
  161. pxy.startListenHandler(pxy, HandleUserTcpConnection)
  162. return nil
  163. }
  164. func (pxy *TcpProxy) GetConf() config.ProxyConf {
  165. return pxy.cfg
  166. }
  167. func (pxy *TcpProxy) Close() {
  168. pxy.BaseProxy.Close()
  169. }
  170. type HttpProxy struct {
  171. BaseProxy
  172. cfg *config.HttpProxyConf
  173. closeFuncs []func()
  174. }
  175. func (pxy *HttpProxy) Run() (err error) {
  176. routeConfig := &vhost.VhostRouteConfig{
  177. RewriteHost: pxy.cfg.HostHeaderRewrite,
  178. Username: pxy.cfg.HttpUser,
  179. Password: pxy.cfg.HttpPwd,
  180. }
  181. locations := pxy.cfg.Locations
  182. if len(locations) == 0 {
  183. locations = []string{""}
  184. }
  185. for _, domain := range pxy.cfg.CustomDomains {
  186. routeConfig.Domain = domain
  187. for _, location := range locations {
  188. routeConfig.Location = location
  189. err := pxy.ctl.svr.httpReverseProxy.Register(routeConfig.Domain, routeConfig.Location, routeConfig.RewriteHost, pxy.GetWorkConnFromPool)
  190. if err != nil {
  191. return err
  192. }
  193. tmpDomain := routeConfig.Domain
  194. tmpLocation := routeConfig.Location
  195. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  196. pxy.ctl.svr.httpReverseProxy.UnRegister(tmpDomain, tmpLocation)
  197. })
  198. pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
  199. }
  200. }
  201. if pxy.cfg.SubDomain != "" {
  202. routeConfig.Domain = pxy.cfg.SubDomain + "." + config.ServerCommonCfg.SubDomainHost
  203. for _, location := range locations {
  204. routeConfig.Location = location
  205. err := pxy.ctl.svr.httpReverseProxy.Register(routeConfig.Domain, routeConfig.Location, routeConfig.RewriteHost, pxy.GetWorkConnFromPool)
  206. if err != nil {
  207. return err
  208. }
  209. tmpDomain := routeConfig.Domain
  210. tmpLocation := routeConfig.Location
  211. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  212. pxy.ctl.svr.httpReverseProxy.UnRegister(tmpDomain, tmpLocation)
  213. })
  214. pxy.Info("http proxy listen for host [%s] location [%s]", routeConfig.Domain, routeConfig.Location)
  215. }
  216. }
  217. return
  218. }
  219. func (pxy *HttpProxy) GetConf() config.ProxyConf {
  220. return pxy.cfg
  221. }
  222. func (pxy *HttpProxy) Close() {
  223. pxy.BaseProxy.Close()
  224. for _, closeFn := range pxy.closeFuncs {
  225. closeFn()
  226. }
  227. }
  228. type HttpsProxy struct {
  229. BaseProxy
  230. cfg *config.HttpsProxyConf
  231. }
  232. func (pxy *HttpsProxy) Run() (err error) {
  233. routeConfig := &vhost.VhostRouteConfig{}
  234. for _, domain := range pxy.cfg.CustomDomains {
  235. routeConfig.Domain = domain
  236. l, err := pxy.ctl.svr.VhostHttpsMuxer.Listen(routeConfig)
  237. if err != nil {
  238. return err
  239. }
  240. l.AddLogPrefix(pxy.name)
  241. pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
  242. pxy.listeners = append(pxy.listeners, l)
  243. }
  244. if pxy.cfg.SubDomain != "" {
  245. routeConfig.Domain = pxy.cfg.SubDomain + "." + config.ServerCommonCfg.SubDomainHost
  246. l, err := pxy.ctl.svr.VhostHttpsMuxer.Listen(routeConfig)
  247. if err != nil {
  248. return err
  249. }
  250. l.AddLogPrefix(pxy.name)
  251. pxy.Info("https proxy listen for host [%s]", routeConfig.Domain)
  252. pxy.listeners = append(pxy.listeners, l)
  253. }
  254. pxy.startListenHandler(pxy, HandleUserTcpConnection)
  255. return
  256. }
  257. func (pxy *HttpsProxy) GetConf() config.ProxyConf {
  258. return pxy.cfg
  259. }
  260. func (pxy *HttpsProxy) Close() {
  261. pxy.BaseProxy.Close()
  262. }
  263. type StcpProxy struct {
  264. BaseProxy
  265. cfg *config.StcpProxyConf
  266. }
  267. func (pxy *StcpProxy) Run() error {
  268. listener, err := pxy.ctl.svr.visitorManager.Listen(pxy.GetName(), pxy.cfg.Sk)
  269. if err != nil {
  270. return err
  271. }
  272. listener.AddLogPrefix(pxy.name)
  273. pxy.listeners = append(pxy.listeners, listener)
  274. pxy.Info("stcp proxy custom listen success")
  275. pxy.startListenHandler(pxy, HandleUserTcpConnection)
  276. return nil
  277. }
  278. func (pxy *StcpProxy) GetConf() config.ProxyConf {
  279. return pxy.cfg
  280. }
  281. func (pxy *StcpProxy) Close() {
  282. pxy.BaseProxy.Close()
  283. pxy.ctl.svr.visitorManager.CloseListener(pxy.GetName())
  284. }
  285. type XtcpProxy struct {
  286. BaseProxy
  287. cfg *config.XtcpProxyConf
  288. closeCh chan struct{}
  289. }
  290. func (pxy *XtcpProxy) Run() error {
  291. if pxy.ctl.svr.natHoleController == nil {
  292. pxy.Error("udp port for xtcp is not specified.")
  293. return fmt.Errorf("xtcp is not supported in frps")
  294. }
  295. sidCh := pxy.ctl.svr.natHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk)
  296. go func() {
  297. for {
  298. select {
  299. case <-pxy.closeCh:
  300. break
  301. case sid := <-sidCh:
  302. workConn, err := pxy.GetWorkConnFromPool()
  303. if err != nil {
  304. continue
  305. }
  306. m := &msg.NatHoleSid{
  307. Sid: sid,
  308. }
  309. err = msg.WriteMsg(workConn, m)
  310. if err != nil {
  311. pxy.Warn("write nat hole sid package error, %v", err)
  312. }
  313. }
  314. }
  315. }()
  316. return nil
  317. }
  318. func (pxy *XtcpProxy) GetConf() config.ProxyConf {
  319. return pxy.cfg
  320. }
  321. func (pxy *XtcpProxy) Close() {
  322. pxy.BaseProxy.Close()
  323. pxy.ctl.svr.natHoleController.CloseClient(pxy.GetName())
  324. errors.PanicToError(func() {
  325. close(pxy.closeCh)
  326. })
  327. }
  328. type UdpProxy struct {
  329. BaseProxy
  330. cfg *config.UdpProxyConf
  331. // udpConn is the listener of udp packages
  332. udpConn *net.UDPConn
  333. // there are always only one workConn at the same time
  334. // get another one if it closed
  335. workConn net.Conn
  336. // sendCh is used for sending packages to workConn
  337. sendCh chan *msg.UdpPacket
  338. // readCh is used for reading packages from workConn
  339. readCh chan *msg.UdpPacket
  340. // checkCloseCh is used for watching if workConn is closed
  341. checkCloseCh chan int
  342. isClosed bool
  343. }
  344. func (pxy *UdpProxy) Run() (err error) {
  345. addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", config.ServerCommonCfg.ProxyBindAddr, pxy.cfg.RemotePort))
  346. if err != nil {
  347. return err
  348. }
  349. udpConn, err := net.ListenUDP("udp", addr)
  350. if err != nil {
  351. pxy.Warn("listen udp port error: %v", err)
  352. return err
  353. }
  354. pxy.Info("udp proxy listen port [%d]", pxy.cfg.RemotePort)
  355. pxy.udpConn = udpConn
  356. pxy.sendCh = make(chan *msg.UdpPacket, 1024)
  357. pxy.readCh = make(chan *msg.UdpPacket, 1024)
  358. pxy.checkCloseCh = make(chan int)
  359. // read message from workConn, if it returns any error, notify proxy to start a new workConn
  360. workConnReaderFn := func(conn net.Conn) {
  361. for {
  362. var (
  363. rawMsg msg.Message
  364. errRet error
  365. )
  366. pxy.Trace("loop waiting message from udp workConn")
  367. // client will send heartbeat in workConn for keeping alive
  368. conn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second))
  369. if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
  370. pxy.Warn("read from workConn for udp error: %v", errRet)
  371. conn.Close()
  372. // notify proxy to start a new work connection
  373. // ignore error here, it means the proxy is closed
  374. errors.PanicToError(func() {
  375. pxy.checkCloseCh <- 1
  376. })
  377. return
  378. }
  379. conn.SetReadDeadline(time.Time{})
  380. switch m := rawMsg.(type) {
  381. case *msg.Ping:
  382. pxy.Trace("udp work conn get ping message")
  383. continue
  384. case *msg.UdpPacket:
  385. if errRet := errors.PanicToError(func() {
  386. pxy.Trace("get udp message from workConn: %s", m.Content)
  387. pxy.readCh <- m
  388. StatsAddTrafficOut(pxy.GetName(), int64(len(m.Content)))
  389. }); errRet != nil {
  390. conn.Close()
  391. pxy.Info("reader goroutine for udp work connection closed")
  392. return
  393. }
  394. }
  395. }
  396. }
  397. // send message to workConn
  398. workConnSenderFn := func(conn net.Conn, ctx context.Context) {
  399. var errRet error
  400. for {
  401. select {
  402. case udpMsg, ok := <-pxy.sendCh:
  403. if !ok {
  404. pxy.Info("sender goroutine for udp work connection closed")
  405. return
  406. }
  407. if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
  408. pxy.Info("sender goroutine for udp work connection closed: %v", errRet)
  409. conn.Close()
  410. return
  411. } else {
  412. pxy.Trace("send message to udp workConn: %s", udpMsg.Content)
  413. StatsAddTrafficIn(pxy.GetName(), int64(len(udpMsg.Content)))
  414. continue
  415. }
  416. case <-ctx.Done():
  417. pxy.Info("sender goroutine for udp work connection closed")
  418. return
  419. }
  420. }
  421. }
  422. go func() {
  423. // Sleep a while for waiting control send the NewProxyResp to client.
  424. time.Sleep(500 * time.Millisecond)
  425. for {
  426. workConn, err := pxy.GetWorkConnFromPool()
  427. if err != nil {
  428. time.Sleep(1 * time.Second)
  429. // check if proxy is closed
  430. select {
  431. case _, ok := <-pxy.checkCloseCh:
  432. if !ok {
  433. return
  434. }
  435. default:
  436. }
  437. continue
  438. }
  439. // close the old workConn and replac it with a new one
  440. if pxy.workConn != nil {
  441. pxy.workConn.Close()
  442. }
  443. pxy.workConn = workConn
  444. ctx, cancel := context.WithCancel(context.Background())
  445. go workConnReaderFn(workConn)
  446. go workConnSenderFn(workConn, ctx)
  447. _, ok := <-pxy.checkCloseCh
  448. cancel()
  449. if !ok {
  450. return
  451. }
  452. }
  453. }()
  454. // Read from user connections and send wrapped udp message to sendCh (forwarded by workConn).
  455. // Client will transfor udp message to local udp service and waiting for response for a while.
  456. // Response will be wrapped to be forwarded by work connection to server.
  457. // Close readCh and sendCh at the end.
  458. go func() {
  459. udp.ForwardUserConn(udpConn, pxy.readCh, pxy.sendCh)
  460. pxy.Close()
  461. }()
  462. return nil
  463. }
  464. func (pxy *UdpProxy) GetConf() config.ProxyConf {
  465. return pxy.cfg
  466. }
  467. func (pxy *UdpProxy) Close() {
  468. pxy.mu.Lock()
  469. defer pxy.mu.Unlock()
  470. if !pxy.isClosed {
  471. pxy.isClosed = true
  472. pxy.BaseProxy.Close()
  473. if pxy.workConn != nil {
  474. pxy.workConn.Close()
  475. }
  476. pxy.udpConn.Close()
  477. // all channels only closed here
  478. close(pxy.checkCloseCh)
  479. close(pxy.readCh)
  480. close(pxy.sendCh)
  481. }
  482. }
  483. // HandleUserTcpConnection is used for incoming tcp user connections.
  484. // It can be used for tcp, http, https type.
  485. func HandleUserTcpConnection(pxy Proxy, userConn frpNet.Conn) {
  486. defer userConn.Close()
  487. // try all connections from the pool
  488. workConn, err := pxy.GetWorkConnFromPool()
  489. if err != nil {
  490. return
  491. }
  492. defer workConn.Close()
  493. var local io.ReadWriteCloser = workConn
  494. cfg := pxy.GetConf().GetBaseInfo()
  495. if cfg.UseEncryption {
  496. local, err = frpIo.WithEncryption(local, []byte(config.ServerCommonCfg.PrivilegeToken))
  497. if err != nil {
  498. pxy.Error("create encryption stream error: %v", err)
  499. return
  500. }
  501. }
  502. if cfg.UseCompression {
  503. local = frpIo.WithCompression(local)
  504. }
  505. pxy.Debug("join connections, workConn(l[%s] r[%s]) userConn(l[%s] r[%s])", workConn.LocalAddr().String(),
  506. workConn.RemoteAddr().String(), userConn.LocalAddr().String(), userConn.RemoteAddr().String())
  507. StatsOpenConnection(pxy.GetName())
  508. inCount, outCount := frpIo.Join(local, userConn)
  509. StatsCloseConnection(pxy.GetName())
  510. StatsAddTrafficIn(pxy.GetName(), inCount)
  511. StatsAddTrafficOut(pxy.GetName(), outCount)
  512. pxy.Debug("join connections closed")
  513. }