proxy.go 16 KB

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