xtcp.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. err = fmt.Errorf("xtcp is not supported in frps")
  31. return
  32. }
  33. allowUsers := pxy.cfg.AllowUsers
  34. // if allowUsers is empty, only allow same user from proxy
  35. if len(allowUsers) == 0 {
  36. allowUsers = []string{pxy.GetUserInfo().User}
  37. }
  38. sidCh := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk, allowUsers)
  39. go func() {
  40. for {
  41. select {
  42. case <-pxy.closeCh:
  43. return
  44. case sid := <-sidCh:
  45. workConn, errRet := pxy.GetWorkConnFromPool(nil, nil)
  46. if errRet != nil {
  47. continue
  48. }
  49. m := &msg.NatHoleSid{
  50. Sid: sid,
  51. }
  52. errRet = msg.WriteMsg(workConn, m)
  53. if errRet != nil {
  54. xl.Warn("write nat hole sid package error, %v", errRet)
  55. }
  56. workConn.Close()
  57. }
  58. }
  59. }()
  60. return
  61. }
  62. func (pxy *XTCPProxy) GetConf() config.ProxyConf {
  63. return pxy.cfg
  64. }
  65. func (pxy *XTCPProxy) GetLimiter() *rate.Limiter {
  66. return pxy.limiter
  67. }
  68. func (pxy *XTCPProxy) Close() {
  69. pxy.BaseProxy.Close()
  70. pxy.rc.NatHoleController.CloseClient(pxy.GetName())
  71. _ = errors.PanicToError(func() {
  72. close(pxy.closeCh)
  73. })
  74. }