xtcp.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. "reflect"
  18. "sync"
  19. v1 "github.com/fatedier/frp/pkg/config/v1"
  20. "github.com/fatedier/frp/pkg/msg"
  21. )
  22. func init() {
  23. RegisterProxyFactory(reflect.TypeOf(&v1.XTCPProxyConfig{}), NewXTCPProxy)
  24. }
  25. type XTCPProxy struct {
  26. *BaseProxy
  27. cfg *v1.XTCPProxyConfig
  28. closeCh chan struct{}
  29. closeOnce sync.Once
  30. }
  31. func NewXTCPProxy(baseProxy *BaseProxy) Proxy {
  32. unwrapped, ok := baseProxy.GetConfigurer().(*v1.XTCPProxyConfig)
  33. if !ok {
  34. return nil
  35. }
  36. return &XTCPProxy{
  37. BaseProxy: baseProxy,
  38. cfg: unwrapped,
  39. closeCh: make(chan struct{}),
  40. }
  41. }
  42. func (pxy *XTCPProxy) Run() (remoteAddr string, err error) {
  43. xl := pxy.xl
  44. if pxy.rc.NatHoleController == nil {
  45. err = fmt.Errorf("xtcp is not supported in frps")
  46. return
  47. }
  48. allowUsers := pxy.cfg.AllowUsers
  49. // if allowUsers is empty, only allow same user from proxy
  50. if len(allowUsers) == 0 {
  51. allowUsers = []string{pxy.GetUserInfo().User}
  52. }
  53. sidCh, err := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Secretkey, allowUsers)
  54. if err != nil {
  55. return "", err
  56. }
  57. go func() {
  58. for {
  59. select {
  60. case <-pxy.closeCh:
  61. return
  62. case sid := <-sidCh:
  63. workConn, errRet := pxy.GetWorkConnFromPool(nil, nil)
  64. if errRet != nil {
  65. continue
  66. }
  67. m := &msg.NatHoleSid{
  68. Sid: sid,
  69. }
  70. errRet = msg.WriteMsg(workConn, m)
  71. if errRet != nil {
  72. xl.Warnf("write nat hole sid package error, %v", errRet)
  73. }
  74. workConn.Close()
  75. }
  76. }
  77. }()
  78. return
  79. }
  80. func (pxy *XTCPProxy) Close() {
  81. pxy.closeOnce.Do(func() {
  82. pxy.BaseProxy.Close()
  83. pxy.rc.NatHoleController.CloseClient(pxy.GetName())
  84. close(pxy.closeCh)
  85. })
  86. }