| // |
| 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 |
| 15 | package proxy |
| 16 |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "net" |
| 20 | "reflect" |
| 21 | "sync" |
| 22 |
| 23 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 24 | "github.com/fatedier/frp/pkg/msg" |
| 25 | ) |
| 26 |
| 27 | func init() { |
| 28 | RegisterProxyFactory(reflect.TypeFor[*v1.XTCPProxyConfig](), NewXTCPProxy) |
| 29 | } |
| 30 |
| 31 | type XTCPProxy struct { |
| 32 | *BaseProxy |
| 33 | cfg *v1.XTCPProxyConfig |
| 34 |
| 35 | closeCh chan struct{} |
| 36 | closeOnce sync.Once |
| 37 | } |
| 38 |
| 39 | func NewXTCPProxy(baseProxy *BaseProxy) Proxy { |
| 40 | unwrapped, ok := baseProxy.GetConfigurer().(*v1.XTCPProxyConfig) |
| 41 | if !ok { |
| 42 | return nil |
| 43 | } |
| 44 | return &XTCPProxy{ |
| 45 | BaseProxy: baseProxy, |
| 46 | cfg: unwrapped, |
| 47 | closeCh: make(chan struct{}), |
| 48 | } |
| 49 | } |
| 50 |
| 51 | func (pxy *XTCPProxy) Run() (remoteAddr string, err error) { |
| 52 | xl := pxy.xl |
| 53 |
| 54 | if pxy.rc.NatHoleController == nil { |
| 55 | err = fmt.Errorf("xtcp is not supported in frps") |
| 56 | return |
| 57 | } |
| 58 | allowUsers := pxy.cfg.AllowUsers |
| 59 | // if allowUsers is empty, only allow same user from proxy |
| 60 | if len(allowUsers) == 0 { |
| 61 | allowUsers = []string{pxy.GetUserInfo().User} |
| 62 | } |
| 63 | sidCh, err := pxy.rc.NatHoleController.ListenClient(pxy.GetName(), pxy.cfg.Secretkey, allowUsers) |
| 64 | if err != nil { |
| 65 | return "", err |
| 66 | } |
| 67 | go func() { |
| 68 | for { |
| 69 | select { |
| 70 | case <-pxy.closeCh: |
| 71 | return |
| 72 | case sid := <-sidCh: |
| 73 | workConn, errRet := pxy.GetWorkConnFromPool(nil, nil) |
| 74 | if errRet != nil { |
| 75 | continue |
| 76 | } |
| 77 | errRet = writeNatHoleSid(workConn, pxy.wireProtocol, sid) |
| 78 | if errRet != nil { |
| 79 | xl.Warnf("write nat hole sid package error, %v", errRet) |
| 80 | } |
| 81 | workConn.Close() |
| 82 | } |
| 83 | } |
| 84 | }() |
| 85 | return |
| 86 | } |
| 87 |
| 88 | func writeNatHoleSid(workConn net.Conn, wireProtocol string, sid string) error { |
| 89 | workMsgConn := msg.NewConn(workConn, msg.NewReadWriter(workConn, wireProtocol)) |
| 90 | return workMsgConn.WriteMsg(&msg.NatHoleSid{ |
| 91 | Sid: sid, |
| 92 | }) |
| 93 | } |
| 94 |
| 95 | func (pxy *XTCPProxy) Close() { |
| 96 | pxy.closeOnce.Do(func() { |
| 97 | pxy.BaseProxy.Close() |
| 98 | pxy.rc.NatHoleController.CloseClient(pxy.GetName()) |
| 99 | close(pxy.closeCh) |
| 100 | }) |
| 101 | } |