plugin.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2025 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 visitor
  15. import (
  16. "context"
  17. "fmt"
  18. "net"
  19. v1 "github.com/fatedier/frp/pkg/config/v1"
  20. "github.com/fatedier/frp/pkg/vnet"
  21. )
  22. // PluginContext provides the necessary context and callbacks for visitor plugins.
  23. type PluginContext struct {
  24. // Name is the unique identifier for this visitor, used for logging and routing.
  25. Name string
  26. // Ctx manages the plugin's lifecycle and carries the logger for structured logging.
  27. Ctx context.Context
  28. // VnetController manages TUN device routing. May be nil if virtual networking is disabled.
  29. VnetController *vnet.Controller
  30. // SendConnToVisitor sends a connection to the visitor's internal processing queue.
  31. // Does not return error; failures are handled by closing the connection.
  32. SendConnToVisitor func(net.Conn)
  33. }
  34. // Creators is used for create plugins to handle connections.
  35. var creators = make(map[string]CreatorFn)
  36. type CreatorFn func(pluginCtx PluginContext, options v1.VisitorPluginOptions) (Plugin, error)
  37. func Register(name string, fn CreatorFn) {
  38. if _, exist := creators[name]; exist {
  39. panic(fmt.Sprintf("plugin [%s] is already registered", name))
  40. }
  41. creators[name] = fn
  42. }
  43. func Create(pluginName string, pluginCtx PluginContext, options v1.VisitorPluginOptions) (p Plugin, err error) {
  44. if fn, ok := creators[pluginName]; ok {
  45. p, err = fn(pluginCtx, options)
  46. } else {
  47. err = fmt.Errorf("plugin [%s] is not registered", pluginName)
  48. }
  49. return
  50. }
  51. type Plugin interface {
  52. Name() string
  53. Start()
  54. Close() error
  55. }