1
0

xtcp.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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, err := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk, allowUsers)
  52. if err != nil {
  53. return "", err
  54. }
  55. go func() {
  56. for {
  57. select {
  58. case <-pxy.closeCh:
  59. return
  60. case sid := <-sidCh:
  61. workConn, errRet := pxy.GetWorkConnFromPool(nil, nil)
  62. if errRet != nil {
  63. continue
  64. }
  65. m := &msg.NatHoleSid{
  66. Sid: sid,
  67. }
  68. errRet = msg.WriteMsg(workConn, m)
  69. if errRet != nil {
  70. xl.Warn("write nat hole sid package error, %v", errRet)
  71. }
  72. workConn.Close()
  73. }
  74. }
  75. }()
  76. return
  77. }
  78. func (pxy *XTCPProxy) GetConf() config.ProxyConf {
  79. return pxy.cfg
  80. }
  81. func (pxy *XTCPProxy) Close() {
  82. pxy.BaseProxy.Close()
  83. pxy.rc.NatHoleController.CloseClient(pxy.GetName())
  84. _ = errors.PanicToError(func() {
  85. close(pxy.closeCh)
  86. })
  87. }