xtcp.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. 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. }
  30. func NewXTCPProxy(baseProxy *BaseProxy) Proxy {
  31. unwrapped, ok := baseProxy.GetConfigurer().(*v1.XTCPProxyConfig)
  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.Secretkey, 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.Warnf("write nat hole sid package error, %v", errRet)
  71. }
  72. workConn.Close()
  73. }
  74. }
  75. }()
  76. return
  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. }