xtcp.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2019 fatedier, [email protected]
  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/frp/pkg/config"
  18. "github.com/fatedier/frp/pkg/msg"
  19. "github.com/fatedier/golib/errors"
  20. )
  21. type XTCPProxy struct {
  22. *BaseProxy
  23. cfg *config.XTCPProxyConf
  24. closeCh chan struct{}
  25. }
  26. func (pxy *XTCPProxy) Run() (remoteAddr string, err error) {
  27. xl := pxy.xl
  28. if pxy.rc.NatHoleController == nil {
  29. xl.Error("udp port for xtcp is not specified.")
  30. err = fmt.Errorf("xtcp is not supported in frps")
  31. return
  32. }
  33. sidCh := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk)
  34. go func() {
  35. for {
  36. select {
  37. case <-pxy.closeCh:
  38. break
  39. case sidRequest := <-sidCh:
  40. sr := sidRequest
  41. workConn, errRet := pxy.GetWorkConnFromPool(nil, nil)
  42. if errRet != nil {
  43. continue
  44. }
  45. m := &msg.NatHoleSid{
  46. Sid: sr.Sid,
  47. }
  48. errRet = msg.WriteMsg(workConn, m)
  49. if errRet != nil {
  50. xl.Warn("write nat hole sid package error, %v", errRet)
  51. workConn.Close()
  52. break
  53. }
  54. go func() {
  55. raw, errRet := msg.ReadMsg(workConn)
  56. if errRet != nil {
  57. xl.Warn("read nat hole client ok package error: %v", errRet)
  58. workConn.Close()
  59. return
  60. }
  61. if _, ok := raw.(*msg.NatHoleClientDetectOK); !ok {
  62. xl.Warn("read nat hole client ok package format error")
  63. workConn.Close()
  64. return
  65. }
  66. select {
  67. case sr.NotifyCh <- struct{}{}:
  68. default:
  69. }
  70. }()
  71. }
  72. }
  73. }()
  74. return
  75. }
  76. func (pxy *XTCPProxy) GetConf() config.ProxyConf {
  77. return pxy.cfg
  78. }
  79. func (pxy *XTCPProxy) Close() {
  80. pxy.BaseProxy.Close()
  81. pxy.rc.NatHoleController.CloseClient(pxy.GetName())
  82. errors.PanicToError(func() {
  83. close(pxy.closeCh)
  84. })
  85. }