1
0

xtcp.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2019 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. "fmt"
  17. "github.com/fatedier/golib/errors"
  18. "golang.org/x/time/rate"
  19. "github.com/fatedier/frp/pkg/config"
  20. "github.com/fatedier/frp/pkg/msg"
  21. )
  22. type XTCPProxy struct {
  23. *BaseProxy
  24. cfg *config.XTCPProxyConf
  25. closeCh chan struct{}
  26. }
  27. func (pxy *XTCPProxy) Run() (remoteAddr string, err error) {
  28. xl := pxy.xl
  29. if pxy.rc.NatHoleController == nil {
  30. xl.Error("udp port for xtcp is not specified.")
  31. err = fmt.Errorf("xtcp is not supported in frps")
  32. return
  33. }
  34. sidCh := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk)
  35. go func() {
  36. for {
  37. select {
  38. case <-pxy.closeCh:
  39. break
  40. case sidRequest := <-sidCh:
  41. sr := sidRequest
  42. workConn, errRet := pxy.GetWorkConnFromPool(nil, nil)
  43. if errRet != nil {
  44. continue
  45. }
  46. m := &msg.NatHoleSid{
  47. Sid: sr.Sid,
  48. }
  49. errRet = msg.WriteMsg(workConn, m)
  50. if errRet != nil {
  51. xl.Warn("write nat hole sid package error, %v", errRet)
  52. workConn.Close()
  53. break
  54. }
  55. go func() {
  56. raw, errRet := msg.ReadMsg(workConn)
  57. if errRet != nil {
  58. xl.Warn("read nat hole client ok package error: %v", errRet)
  59. workConn.Close()
  60. return
  61. }
  62. if _, ok := raw.(*msg.NatHoleClientDetectOK); !ok {
  63. xl.Warn("read nat hole client ok package format error")
  64. workConn.Close()
  65. return
  66. }
  67. select {
  68. case sr.NotifyCh <- struct{}{}:
  69. default:
  70. }
  71. }()
  72. }
  73. }
  74. }()
  75. return
  76. }
  77. func (pxy *XTCPProxy) GetConf() config.ProxyConf {
  78. return pxy.cfg
  79. }
  80. func (pxy *XTCPProxy) GetLimiter() *rate.Limiter {
  81. return pxy.limiter
  82. }
  83. func (pxy *XTCPProxy) Close() {
  84. pxy.BaseProxy.Close()
  85. pxy.rc.NatHoleController.CloseClient(pxy.GetName())
  86. _ = errors.PanicToError(func() {
  87. close(pxy.closeCh)
  88. })
  89. }