proxy.go 17 KB

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