proxy.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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 proxy
  15. import (
  16. "bytes"
  17. "context"
  18. "io"
  19. "net"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. "github.com/fatedier/golib/errors"
  25. frpIo "github.com/fatedier/golib/io"
  26. libdial "github.com/fatedier/golib/net/dial"
  27. "github.com/fatedier/golib/pool"
  28. fmux "github.com/hashicorp/yamux"
  29. pp "github.com/pires/go-proxyproto"
  30. "golang.org/x/time/rate"
  31. "github.com/fatedier/frp/pkg/config"
  32. "github.com/fatedier/frp/pkg/msg"
  33. plugin "github.com/fatedier/frp/pkg/plugin/client"
  34. "github.com/fatedier/frp/pkg/proto/udp"
  35. "github.com/fatedier/frp/pkg/util/limit"
  36. frpNet "github.com/fatedier/frp/pkg/util/net"
  37. "github.com/fatedier/frp/pkg/util/xlog"
  38. )
  39. // Proxy defines how to handle work connections for different proxy type.
  40. type Proxy interface {
  41. Run() error
  42. // InWorkConn accept work connections registered to server.
  43. InWorkConn(net.Conn, *msg.StartWorkConn)
  44. Close()
  45. }
  46. func NewProxy(ctx context.Context, pxyConf config.ProxyConf, clientCfg config.ClientCommonConf, serverUDPPort int) (pxy Proxy) {
  47. var limiter *rate.Limiter
  48. limitBytes := pxyConf.GetBaseInfo().BandwidthLimit.Bytes()
  49. if limitBytes > 0 && pxyConf.GetBaseInfo().BandwidthLimitMode == config.BandwidthLimitModeClient {
  50. limiter = rate.NewLimiter(rate.Limit(float64(limitBytes)), int(limitBytes))
  51. }
  52. baseProxy := BaseProxy{
  53. clientCfg: clientCfg,
  54. serverUDPPort: serverUDPPort,
  55. limiter: limiter,
  56. xl: xlog.FromContextSafe(ctx),
  57. ctx: ctx,
  58. }
  59. switch cfg := pxyConf.(type) {
  60. case *config.TCPProxyConf:
  61. pxy = &TCPProxy{
  62. BaseProxy: &baseProxy,
  63. cfg: cfg,
  64. }
  65. case *config.TCPMuxProxyConf:
  66. pxy = &TCPMuxProxy{
  67. BaseProxy: &baseProxy,
  68. cfg: cfg,
  69. }
  70. case *config.UDPProxyConf:
  71. pxy = &UDPProxy{
  72. BaseProxy: &baseProxy,
  73. cfg: cfg,
  74. }
  75. case *config.HTTPProxyConf:
  76. pxy = &HTTPProxy{
  77. BaseProxy: &baseProxy,
  78. cfg: cfg,
  79. }
  80. case *config.HTTPSProxyConf:
  81. pxy = &HTTPSProxy{
  82. BaseProxy: &baseProxy,
  83. cfg: cfg,
  84. }
  85. case *config.STCPProxyConf:
  86. pxy = &STCPProxy{
  87. BaseProxy: &baseProxy,
  88. cfg: cfg,
  89. }
  90. case *config.XTCPProxyConf:
  91. pxy = &XTCPProxy{
  92. BaseProxy: &baseProxy,
  93. cfg: cfg,
  94. }
  95. case *config.SUDPProxyConf:
  96. pxy = &SUDPProxy{
  97. BaseProxy: &baseProxy,
  98. cfg: cfg,
  99. closeCh: make(chan struct{}),
  100. }
  101. }
  102. return
  103. }
  104. type BaseProxy struct {
  105. closed bool
  106. clientCfg config.ClientCommonConf
  107. serverUDPPort int
  108. limiter *rate.Limiter
  109. mu sync.RWMutex
  110. xl *xlog.Logger
  111. ctx context.Context
  112. }
  113. // TCP
  114. type TCPProxy struct {
  115. *BaseProxy
  116. cfg *config.TCPProxyConf
  117. proxyPlugin plugin.Plugin
  118. }
  119. func (pxy *TCPProxy) Run() (err error) {
  120. if pxy.cfg.Plugin != "" {
  121. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  122. if err != nil {
  123. return
  124. }
  125. }
  126. return
  127. }
  128. func (pxy *TCPProxy) Close() {
  129. if pxy.proxyPlugin != nil {
  130. pxy.proxyPlugin.Close()
  131. }
  132. }
  133. func (pxy *TCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  134. HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
  135. conn, []byte(pxy.clientCfg.Token), m)
  136. }
  137. // TCP Multiplexer
  138. type TCPMuxProxy struct {
  139. *BaseProxy
  140. cfg *config.TCPMuxProxyConf
  141. proxyPlugin plugin.Plugin
  142. }
  143. func (pxy *TCPMuxProxy) Run() (err error) {
  144. if pxy.cfg.Plugin != "" {
  145. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  146. if err != nil {
  147. return
  148. }
  149. }
  150. return
  151. }
  152. func (pxy *TCPMuxProxy) Close() {
  153. if pxy.proxyPlugin != nil {
  154. pxy.proxyPlugin.Close()
  155. }
  156. }
  157. func (pxy *TCPMuxProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  158. HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
  159. conn, []byte(pxy.clientCfg.Token), m)
  160. }
  161. // HTTP
  162. type HTTPProxy struct {
  163. *BaseProxy
  164. cfg *config.HTTPProxyConf
  165. proxyPlugin plugin.Plugin
  166. }
  167. func (pxy *HTTPProxy) Run() (err error) {
  168. if pxy.cfg.Plugin != "" {
  169. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  170. if err != nil {
  171. return
  172. }
  173. }
  174. return
  175. }
  176. func (pxy *HTTPProxy) Close() {
  177. if pxy.proxyPlugin != nil {
  178. pxy.proxyPlugin.Close()
  179. }
  180. }
  181. func (pxy *HTTPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  182. HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
  183. conn, []byte(pxy.clientCfg.Token), m)
  184. }
  185. // HTTPS
  186. type HTTPSProxy struct {
  187. *BaseProxy
  188. cfg *config.HTTPSProxyConf
  189. proxyPlugin plugin.Plugin
  190. }
  191. func (pxy *HTTPSProxy) Run() (err error) {
  192. if pxy.cfg.Plugin != "" {
  193. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  194. if err != nil {
  195. return
  196. }
  197. }
  198. return
  199. }
  200. func (pxy *HTTPSProxy) Close() {
  201. if pxy.proxyPlugin != nil {
  202. pxy.proxyPlugin.Close()
  203. }
  204. }
  205. func (pxy *HTTPSProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  206. HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
  207. conn, []byte(pxy.clientCfg.Token), m)
  208. }
  209. // STCP
  210. type STCPProxy struct {
  211. *BaseProxy
  212. cfg *config.STCPProxyConf
  213. proxyPlugin plugin.Plugin
  214. }
  215. func (pxy *STCPProxy) Run() (err error) {
  216. if pxy.cfg.Plugin != "" {
  217. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  218. if err != nil {
  219. return
  220. }
  221. }
  222. return
  223. }
  224. func (pxy *STCPProxy) Close() {
  225. if pxy.proxyPlugin != nil {
  226. pxy.proxyPlugin.Close()
  227. }
  228. }
  229. func (pxy *STCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  230. HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
  231. conn, []byte(pxy.clientCfg.Token), m)
  232. }
  233. // XTCP
  234. type XTCPProxy struct {
  235. *BaseProxy
  236. cfg *config.XTCPProxyConf
  237. proxyPlugin plugin.Plugin
  238. }
  239. func (pxy *XTCPProxy) Run() (err error) {
  240. if pxy.cfg.Plugin != "" {
  241. pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
  242. if err != nil {
  243. return
  244. }
  245. }
  246. return
  247. }
  248. func (pxy *XTCPProxy) Close() {
  249. if pxy.proxyPlugin != nil {
  250. pxy.proxyPlugin.Close()
  251. }
  252. }
  253. func (pxy *XTCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  254. xl := pxy.xl
  255. defer conn.Close()
  256. var natHoleSidMsg msg.NatHoleSid
  257. err := msg.ReadMsgInto(conn, &natHoleSidMsg)
  258. if err != nil {
  259. xl.Error("xtcp read from workConn error: %v", err)
  260. return
  261. }
  262. natHoleClientMsg := &msg.NatHoleClient{
  263. ProxyName: pxy.cfg.ProxyName,
  264. Sid: natHoleSidMsg.Sid,
  265. }
  266. raddr, _ := net.ResolveUDPAddr("udp",
  267. net.JoinHostPort(pxy.clientCfg.ServerAddr, strconv.Itoa(pxy.serverUDPPort)))
  268. clientConn, err := net.DialUDP("udp", nil, raddr)
  269. if err != nil {
  270. xl.Error("dial server udp addr error: %v", err)
  271. return
  272. }
  273. defer clientConn.Close()
  274. err = msg.WriteMsg(clientConn, natHoleClientMsg)
  275. if err != nil {
  276. xl.Error("send natHoleClientMsg to server error: %v", err)
  277. return
  278. }
  279. // Wait for client address at most 5 seconds.
  280. var natHoleRespMsg msg.NatHoleResp
  281. _ = clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
  282. buf := pool.GetBuf(1024)
  283. n, err := clientConn.Read(buf)
  284. if err != nil {
  285. xl.Error("get natHoleRespMsg error: %v", err)
  286. return
  287. }
  288. err = msg.ReadMsgInto(bytes.NewReader(buf[:n]), &natHoleRespMsg)
  289. if err != nil {
  290. xl.Error("get natHoleRespMsg error: %v", err)
  291. return
  292. }
  293. _ = clientConn.SetReadDeadline(time.Time{})
  294. _ = clientConn.Close()
  295. if natHoleRespMsg.Error != "" {
  296. xl.Error("natHoleRespMsg get error info: %s", natHoleRespMsg.Error)
  297. return
  298. }
  299. xl.Trace("get natHoleRespMsg, sid [%s], client address [%s] visitor address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr, natHoleRespMsg.VisitorAddr)
  300. // Send detect message
  301. host, portStr, err := net.SplitHostPort(natHoleRespMsg.VisitorAddr)
  302. if err != nil {
  303. xl.Error("get NatHoleResp visitor address [%s] error: %v", natHoleRespMsg.VisitorAddr, err)
  304. }
  305. laddr, _ := net.ResolveUDPAddr("udp", clientConn.LocalAddr().String())
  306. port, err := strconv.ParseInt(portStr, 10, 64)
  307. if err != nil {
  308. xl.Error("get natHoleResp visitor address error: %v", natHoleRespMsg.VisitorAddr)
  309. return
  310. }
  311. _ = pxy.sendDetectMsg(host, int(port), laddr, []byte(natHoleRespMsg.Sid))
  312. xl.Trace("send all detect msg done")
  313. if err := msg.WriteMsg(conn, &msg.NatHoleClientDetectOK{}); err != nil {
  314. xl.Error("write message error: %v", err)
  315. return
  316. }
  317. // Listen for clientConn's address and wait for visitor connection
  318. lConn, err := net.ListenUDP("udp", laddr)
  319. if err != nil {
  320. xl.Error("listen on visitorConn's local address error: %v", err)
  321. return
  322. }
  323. defer lConn.Close()
  324. _ = lConn.SetReadDeadline(time.Now().Add(8 * time.Second))
  325. sidBuf := pool.GetBuf(1024)
  326. var uAddr *net.UDPAddr
  327. n, uAddr, err = lConn.ReadFromUDP(sidBuf)
  328. if err != nil {
  329. xl.Warn("get sid from visitor error: %v", err)
  330. return
  331. }
  332. _ = lConn.SetReadDeadline(time.Time{})
  333. if string(sidBuf[:n]) != natHoleRespMsg.Sid {
  334. xl.Warn("incorrect sid from visitor")
  335. return
  336. }
  337. pool.PutBuf(sidBuf)
  338. xl.Info("nat hole connection make success, sid [%s]", natHoleRespMsg.Sid)
  339. if _, err := lConn.WriteToUDP(sidBuf[:n], uAddr); err != nil {
  340. xl.Error("write uaddr error: %v", err)
  341. return
  342. }
  343. kcpConn, err := frpNet.NewKCPConnFromUDP(lConn, false, uAddr.String())
  344. if err != nil {
  345. xl.Error("create kcp connection from udp connection error: %v", err)
  346. return
  347. }
  348. fmuxCfg := fmux.DefaultConfig()
  349. fmuxCfg.KeepAliveInterval = 5 * time.Second
  350. fmuxCfg.LogOutput = io.Discard
  351. sess, err := fmux.Server(kcpConn, fmuxCfg)
  352. if err != nil {
  353. xl.Error("create yamux server from kcp connection error: %v", err)
  354. return
  355. }
  356. defer sess.Close()
  357. muxConn, err := sess.Accept()
  358. if err != nil {
  359. xl.Error("accept for yamux connection error: %v", err)
  360. return
  361. }
  362. HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
  363. muxConn, []byte(pxy.cfg.Sk), m)
  364. }
  365. func (pxy *XTCPProxy) sendDetectMsg(addr string, port int, laddr *net.UDPAddr, content []byte) (err error) {
  366. daddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(addr, strconv.Itoa(port)))
  367. if err != nil {
  368. return err
  369. }
  370. tConn, err := net.DialUDP("udp", laddr, daddr)
  371. if err != nil {
  372. return err
  373. }
  374. // uConn := ipv4.NewConn(tConn)
  375. // uConn.SetTTL(3)
  376. if _, err := tConn.Write(content); err != nil {
  377. return err
  378. }
  379. return tConn.Close()
  380. }
  381. // UDP
  382. type UDPProxy struct {
  383. *BaseProxy
  384. cfg *config.UDPProxyConf
  385. localAddr *net.UDPAddr
  386. readCh chan *msg.UDPPacket
  387. // include msg.UDPPacket and msg.Ping
  388. sendCh chan msg.Message
  389. workConn net.Conn
  390. }
  391. func (pxy *UDPProxy) Run() (err error) {
  392. pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort)))
  393. if err != nil {
  394. return
  395. }
  396. return
  397. }
  398. func (pxy *UDPProxy) Close() {
  399. pxy.mu.Lock()
  400. defer pxy.mu.Unlock()
  401. if !pxy.closed {
  402. pxy.closed = true
  403. if pxy.workConn != nil {
  404. pxy.workConn.Close()
  405. }
  406. if pxy.readCh != nil {
  407. close(pxy.readCh)
  408. }
  409. if pxy.sendCh != nil {
  410. close(pxy.sendCh)
  411. }
  412. }
  413. }
  414. func (pxy *UDPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  415. xl := pxy.xl
  416. xl.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
  417. // close resources releated with old workConn
  418. pxy.Close()
  419. var rwc io.ReadWriteCloser = conn
  420. var err error
  421. if pxy.limiter != nil {
  422. rwc = frpIo.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error {
  423. return conn.Close()
  424. })
  425. }
  426. if pxy.cfg.UseEncryption {
  427. rwc, err = frpIo.WithEncryption(rwc, []byte(pxy.clientCfg.Token))
  428. if err != nil {
  429. conn.Close()
  430. xl.Error("create encryption stream error: %v", err)
  431. return
  432. }
  433. }
  434. if pxy.cfg.UseCompression {
  435. rwc = frpIo.WithCompression(rwc)
  436. }
  437. conn = frpNet.WrapReadWriteCloserToConn(rwc, conn)
  438. pxy.mu.Lock()
  439. pxy.workConn = conn
  440. pxy.readCh = make(chan *msg.UDPPacket, 1024)
  441. pxy.sendCh = make(chan msg.Message, 1024)
  442. pxy.closed = false
  443. pxy.mu.Unlock()
  444. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
  445. for {
  446. var udpMsg msg.UDPPacket
  447. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  448. xl.Warn("read from workConn for udp error: %v", errRet)
  449. return
  450. }
  451. if errRet := errors.PanicToError(func() {
  452. xl.Trace("get udp package from workConn: %s", udpMsg.Content)
  453. readCh <- &udpMsg
  454. }); errRet != nil {
  455. xl.Info("reader goroutine for udp work connection closed: %v", errRet)
  456. return
  457. }
  458. }
  459. }
  460. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  461. defer func() {
  462. xl.Info("writer goroutine for udp work connection closed")
  463. }()
  464. var errRet error
  465. for rawMsg := range sendCh {
  466. switch m := rawMsg.(type) {
  467. case *msg.UDPPacket:
  468. xl.Trace("send udp package to workConn: %s", m.Content)
  469. case *msg.Ping:
  470. xl.Trace("send ping message to udp workConn")
  471. }
  472. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  473. xl.Error("udp work write error: %v", errRet)
  474. return
  475. }
  476. }
  477. }
  478. heartbeatFn := func(sendCh chan msg.Message) {
  479. var errRet error
  480. for {
  481. time.Sleep(time.Duration(30) * time.Second)
  482. if errRet = errors.PanicToError(func() {
  483. sendCh <- &msg.Ping{}
  484. }); errRet != nil {
  485. xl.Trace("heartbeat goroutine for udp work connection closed")
  486. break
  487. }
  488. }
  489. }
  490. go workConnSenderFn(pxy.workConn, pxy.sendCh)
  491. go workConnReaderFn(pxy.workConn, pxy.readCh)
  492. go heartbeatFn(pxy.sendCh)
  493. udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh, int(pxy.clientCfg.UDPPacketSize))
  494. }
  495. type SUDPProxy struct {
  496. *BaseProxy
  497. cfg *config.SUDPProxyConf
  498. localAddr *net.UDPAddr
  499. closeCh chan struct{}
  500. }
  501. func (pxy *SUDPProxy) Run() (err error) {
  502. pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort)))
  503. if err != nil {
  504. return
  505. }
  506. return
  507. }
  508. func (pxy *SUDPProxy) Close() {
  509. pxy.mu.Lock()
  510. defer pxy.mu.Unlock()
  511. select {
  512. case <-pxy.closeCh:
  513. return
  514. default:
  515. close(pxy.closeCh)
  516. }
  517. }
  518. func (pxy *SUDPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
  519. xl := pxy.xl
  520. xl.Info("incoming a new work connection for sudp proxy, %s", conn.RemoteAddr().String())
  521. var rwc io.ReadWriteCloser = conn
  522. var err error
  523. if pxy.limiter != nil {
  524. rwc = frpIo.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error {
  525. return conn.Close()
  526. })
  527. }
  528. if pxy.cfg.UseEncryption {
  529. rwc, err = frpIo.WithEncryption(rwc, []byte(pxy.clientCfg.Token))
  530. if err != nil {
  531. conn.Close()
  532. xl.Error("create encryption stream error: %v", err)
  533. return
  534. }
  535. }
  536. if pxy.cfg.UseCompression {
  537. rwc = frpIo.WithCompression(rwc)
  538. }
  539. conn = frpNet.WrapReadWriteCloserToConn(rwc, conn)
  540. workConn := conn
  541. readCh := make(chan *msg.UDPPacket, 1024)
  542. sendCh := make(chan msg.Message, 1024)
  543. isClose := false
  544. mu := &sync.Mutex{}
  545. closeFn := func() {
  546. mu.Lock()
  547. defer mu.Unlock()
  548. if isClose {
  549. return
  550. }
  551. isClose = true
  552. if workConn != nil {
  553. workConn.Close()
  554. }
  555. close(readCh)
  556. close(sendCh)
  557. }
  558. // udp service <- frpc <- frps <- frpc visitor <- user
  559. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
  560. defer closeFn()
  561. for {
  562. // first to check sudp proxy is closed or not
  563. select {
  564. case <-pxy.closeCh:
  565. xl.Trace("frpc sudp proxy is closed")
  566. return
  567. default:
  568. }
  569. var udpMsg msg.UDPPacket
  570. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  571. xl.Warn("read from workConn for sudp error: %v", errRet)
  572. return
  573. }
  574. if errRet := errors.PanicToError(func() {
  575. readCh <- &udpMsg
  576. }); errRet != nil {
  577. xl.Warn("reader goroutine for sudp work connection closed: %v", errRet)
  578. return
  579. }
  580. }
  581. }
  582. // udp service -> frpc -> frps -> frpc visitor -> user
  583. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  584. defer func() {
  585. closeFn()
  586. xl.Info("writer goroutine for sudp work connection closed")
  587. }()
  588. var errRet error
  589. for rawMsg := range sendCh {
  590. switch m := rawMsg.(type) {
  591. case *msg.UDPPacket:
  592. xl.Trace("frpc send udp package to frpc visitor, [udp local: %v, remote: %v], [tcp work conn local: %v, remote: %v]",
  593. m.LocalAddr.String(), m.RemoteAddr.String(), conn.LocalAddr().String(), conn.RemoteAddr().String())
  594. case *msg.Ping:
  595. xl.Trace("frpc send ping message to frpc visitor")
  596. }
  597. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  598. xl.Error("sudp work write error: %v", errRet)
  599. return
  600. }
  601. }
  602. }
  603. heartbeatFn := func(sendCh chan msg.Message) {
  604. ticker := time.NewTicker(30 * time.Second)
  605. defer func() {
  606. ticker.Stop()
  607. closeFn()
  608. }()
  609. var errRet error
  610. for {
  611. select {
  612. case <-ticker.C:
  613. if errRet = errors.PanicToError(func() {
  614. sendCh <- &msg.Ping{}
  615. }); errRet != nil {
  616. xl.Warn("heartbeat goroutine for sudp work connection closed")
  617. return
  618. }
  619. case <-pxy.closeCh:
  620. xl.Trace("frpc sudp proxy is closed")
  621. return
  622. }
  623. }
  624. }
  625. go workConnSenderFn(workConn, sendCh)
  626. go workConnReaderFn(workConn, readCh)
  627. go heartbeatFn(sendCh)
  628. udp.Forwarder(pxy.localAddr, readCh, sendCh, int(pxy.clientCfg.UDPPacketSize))
  629. }
  630. // Common handler for tcp work connections.
  631. func HandleTCPWorkConnection(ctx context.Context, localInfo *config.LocalSvrConf, proxyPlugin plugin.Plugin,
  632. baseInfo *config.BaseProxyConf, limiter *rate.Limiter, workConn net.Conn, encKey []byte, m *msg.StartWorkConn,
  633. ) {
  634. xl := xlog.FromContextSafe(ctx)
  635. var (
  636. remote io.ReadWriteCloser
  637. err error
  638. )
  639. remote = workConn
  640. if limiter != nil {
  641. remote = frpIo.WrapReadWriteCloser(limit.NewReader(workConn, limiter), limit.NewWriter(workConn, limiter), func() error {
  642. return workConn.Close()
  643. })
  644. }
  645. xl.Trace("handle tcp work connection, use_encryption: %t, use_compression: %t",
  646. baseInfo.UseEncryption, baseInfo.UseCompression)
  647. if baseInfo.UseEncryption {
  648. remote, err = frpIo.WithEncryption(remote, encKey)
  649. if err != nil {
  650. workConn.Close()
  651. xl.Error("create encryption stream error: %v", err)
  652. return
  653. }
  654. }
  655. if baseInfo.UseCompression {
  656. remote = frpIo.WithCompression(remote)
  657. }
  658. // check if we need to send proxy protocol info
  659. var extraInfo []byte
  660. if baseInfo.ProxyProtocolVersion != "" {
  661. if m.SrcAddr != "" && m.SrcPort != 0 {
  662. if m.DstAddr == "" {
  663. m.DstAddr = "127.0.0.1"
  664. }
  665. srcAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.SrcAddr, strconv.Itoa(int(m.SrcPort))))
  666. dstAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.DstAddr, strconv.Itoa(int(m.DstPort))))
  667. h := &pp.Header{
  668. Command: pp.PROXY,
  669. SourceAddr: srcAddr,
  670. DestinationAddr: dstAddr,
  671. }
  672. if strings.Contains(m.SrcAddr, ".") {
  673. h.TransportProtocol = pp.TCPv4
  674. } else {
  675. h.TransportProtocol = pp.TCPv6
  676. }
  677. if baseInfo.ProxyProtocolVersion == "v1" {
  678. h.Version = 1
  679. } else if baseInfo.ProxyProtocolVersion == "v2" {
  680. h.Version = 2
  681. }
  682. buf := bytes.NewBuffer(nil)
  683. _, _ = h.WriteTo(buf)
  684. extraInfo = buf.Bytes()
  685. }
  686. }
  687. if proxyPlugin != nil {
  688. // if plugin is set, let plugin handle connections first
  689. xl.Debug("handle by plugin: %s", proxyPlugin.Name())
  690. proxyPlugin.Handle(remote, workConn, extraInfo)
  691. xl.Debug("handle by plugin finished")
  692. return
  693. }
  694. localConn, err := libdial.Dial(
  695. net.JoinHostPort(localInfo.LocalIP, strconv.Itoa(localInfo.LocalPort)),
  696. libdial.WithTimeout(10*time.Second),
  697. )
  698. if err != nil {
  699. workConn.Close()
  700. xl.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIP, localInfo.LocalPort, err)
  701. return
  702. }
  703. xl.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
  704. localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  705. if len(extraInfo) > 0 {
  706. if _, err := localConn.Write(extraInfo); err != nil {
  707. workConn.Close()
  708. xl.Error("write extraInfo to local conn error: %v", err)
  709. return
  710. }
  711. }
  712. frpIo.Join(localConn, remote)
  713. xl.Debug("join connections closed")
  714. }