client.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2023 The frp Authors
  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 virtual
  15. import (
  16. "context"
  17. "net"
  18. "github.com/fatedier/frp/client"
  19. v1 "github.com/fatedier/frp/pkg/config/v1"
  20. "github.com/fatedier/frp/pkg/msg"
  21. utilnet "github.com/fatedier/frp/pkg/util/net"
  22. )
  23. type Client struct {
  24. l *utilnet.InternalListener
  25. svr *client.Service
  26. }
  27. func NewClient(cfg *v1.ClientCommonConfig) *Client {
  28. cfg.Complete()
  29. ln := utilnet.NewInternalListener()
  30. svr := client.NewService(cfg, nil, nil, "")
  31. svr.SetConnectorCreator(func(context.Context, *v1.ClientCommonConfig) client.Connector {
  32. return &pipeConnector{
  33. peerListener: ln,
  34. }
  35. })
  36. return &Client{
  37. l: ln,
  38. svr: svr,
  39. }
  40. }
  41. func (c *Client) PeerListener() net.Listener {
  42. return c.l
  43. }
  44. func (c *Client) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) {
  45. c.svr.SetInWorkConnCallback(cb)
  46. }
  47. func (c *Client) UpdateProxyConfigurer(proxyCfgs []v1.ProxyConfigurer) {
  48. _ = c.svr.ReloadConf(proxyCfgs, nil)
  49. }
  50. func (c *Client) Run(ctx context.Context) error {
  51. return c.svr.Run(ctx)
  52. }
  53. func (c *Client) Close() {
  54. c.l.Close()
  55. c.svr.Close()
  56. }
  57. type pipeConnector struct {
  58. peerListener *utilnet.InternalListener
  59. }
  60. func (pc *pipeConnector) Open() error {
  61. return nil
  62. }
  63. func (pc *pipeConnector) Connect() (net.Conn, error) {
  64. c1, c2 := net.Pipe()
  65. if err := pc.peerListener.PutConn(c1); err != nil {
  66. c1.Close()
  67. c2.Close()
  68. return nil, err
  69. }
  70. return c2, nil
  71. }
  72. func (pc *pipeConnector) Close() error {
  73. pc.peerListener.Close()
  74. return nil
  75. }