| // |
| 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 | //go:build !frps |
| 16 |
| 17 | package client |
| 18 |
| 19 | import ( |
| 20 | "context" |
| 21 | "io" |
| 22 | "sync" |
| 23 |
| 24 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 25 | ) |
| 26 |
| 27 | func init() { |
| 28 | Register(v1.PluginVirtualNet, NewVirtualNetPlugin) |
| 29 | } |
| 30 |
| 31 | type VirtualNetPlugin struct { |
| 32 | pluginCtx PluginContext |
| 33 | opts *v1.VirtualNetPluginOptions |
| 34 | mu sync.Mutex |
| 35 | conns map[io.ReadWriteCloser]struct{} |
| 36 | } |
| 37 |
| 38 | func NewVirtualNetPlugin(pluginCtx PluginContext, options v1.ClientPluginOptions) (Plugin, error) { |
| 39 | opts := options.(*v1.VirtualNetPluginOptions) |
| 40 |
| 41 | p := &VirtualNetPlugin{ |
| 42 | pluginCtx: pluginCtx, |
| 43 | opts: opts, |
| 44 | } |
| 45 | return p, nil |
| 46 | } |
| 47 |
| 48 | func (p *VirtualNetPlugin) Handle(ctx context.Context, connInfo *ConnectionInfo) { |
| 49 | // Verify if virtual network controller is available |
| 50 | if p.pluginCtx.VnetController == nil { |
| 51 | return |
| 52 | } |
| 53 |
| 54 | // Add the connection before starting the read loop to avoid race condition |
| 55 | // where RemoveConn might be called before the connection is added. |
| 56 | p.mu.Lock() |
| 57 | if p.conns == nil { |
| 58 | p.conns = make(map[io.ReadWriteCloser]struct{}) |
| 59 | } |
| 60 | p.conns[connInfo.Conn] = struct{}{} |
| 61 | p.mu.Unlock() |
| 62 |
| 63 | // Register the connection with the controller and pass the cleanup function |
| 64 | p.pluginCtx.VnetController.StartServerConnReadLoop(ctx, connInfo.Conn, func() { |
| 65 | p.RemoveConn(connInfo.Conn) |
| 66 | }) |
| 67 | } |
| 68 |
| 69 | func (p *VirtualNetPlugin) RemoveConn(conn io.ReadWriteCloser) { |
| 70 | p.mu.Lock() |
| 71 | defer p.mu.Unlock() |
| 72 | // Check if the map exists, as Close might have set it to nil concurrently |
| 73 | if p.conns != nil { |
| 74 | delete(p.conns, conn) |
| 75 | } |
| 76 | } |
| 77 |
| 78 | func (p *VirtualNetPlugin) Name() string { |
| 79 | return v1.PluginVirtualNet |
| 80 | } |
| 81 |
| 82 | func (p *VirtualNetPlugin) Close() error { |
| 83 | p.mu.Lock() |
| 84 | defer p.mu.Unlock() |
| 85 |
| 86 | // Close any remaining connections |
| 87 | for conn := range p.conns { |
| 88 | _ = conn.Close() |
| 89 | } |
| 90 | p.conns = nil |
| 91 | return nil |
| 92 | } |