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