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. "github.com/fatedier/frp/models/config"
  18. "github.com/fatedier/frp/models/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. if pxy.rc.NatHoleController == nil {
  28. pxy.Error("udp port for xtcp is not specified.")
  29. err = fmt.Errorf("xtcp is not supported in frps")
  30. return
  31. }
  32. sidCh := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Sk)
  33. go func() {
  34. for {
  35. select {
  36. case <-pxy.closeCh:
  37. break
  38. case sidRequest := <-sidCh:
  39. sr := sidRequest
  40. workConn, errRet := pxy.GetWorkConnFromPool(nil, nil)
  41. if errRet != nil {
  42. continue
  43. }
  44. m := &msg.NatHoleSid{
  45. Sid: sr.Sid,
  46. }
  47. errRet = msg.WriteMsg(workConn, m)
  48. if errRet != nil {
  49. pxy.Warn("write nat hole sid package error, %v", errRet)
  50. workConn.Close()
  51. break
  52. }
  53. go func() {
  54. raw, errRet := msg.ReadMsg(workConn)
  55. if errRet != nil {
  56. pxy.Warn("read nat hole client ok package error: %v", errRet)
  57. workConn.Close()
  58. return
  59. }
  60. if _, ok := raw.(*msg.NatHoleClientDetectOK); !ok {
  61. pxy.Warn("read nat hole client ok package format error")
  62. workConn.Close()
  63. return
  64. }
  65. select {
  66. case sr.NotifyCh <- struct{}{}:
  67. default:
  68. }
  69. }()
  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. }