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