feat: support customized plugin manager

This commit is contained in:
mzz2017 committed 2022-08-03 23:12:29 +08:00
1 parent 4ddc89c5de
commit ba1feb34b3
16 files changed
+384 -41

No files matched your search

+9
View File
@@ -245,3 +245,12 @@ func HomeExpand(path string) (string, error) {
}
return filepath.Join(usr.HomeDir, path[1:]), nil
}
func HasAnyPrefix(s string, prefix []string) bool {
for _, p := range prefix {
if strings.HasPrefix(s, p) {
return true
}
}
return false
}
+1
View File
@@ -20,6 +20,7 @@ type Params struct {
V2rayAssetsDirectory string `id:"v2ray-assetsdir" desc:"v2ray-core assets directory for searching and downloading files like geoip.dat. This will override environment V2RAY_LOCATION_ASSET and XRAY_LOCATION_ASSET."`
TransparentHook string `id:"transparent-hook" desc:"the executable file to run in the transparent proxy life-cycle. v2rayA will pass in the --transparent-type (tproxy, redirect) and --stage (pre-start, post-start, pre-stop, post-stop) arguments."`
CoreHook string `id:"core-hook" desc:"the executable file to run in the v2ray-core life-cycle. v2rayA will pass in the --stage (pre-start, post-start, pre-stop, post-stop) argument."`
PluginManager string `id:"plugin-manager" desc:"the executable file to run in the v2ray-core life-cycle. v2rayA will pass in the --stage (pre-start, post-start, pre-stop, post-stop) argument."`
WebDir string `id:"webdir" desc:"v2rayA web files directory. use embedded files if not specify."`
IPV6Support string `id:"ipv6-support" default:"auto" desc:"Optional values: auto, on, off. Make sure your IPv6 network works fine before you turn it on."`
PassCheckRoot bool `desc:"Skip privilege checking. Use it only when you cannot start v2raya but confirm you have root privilege"`
+1 -1
View File
@@ -126,7 +126,7 @@ func (h *HTTP) ExportToURL() string {
return u.String()
}
func (h *HTTP) NeedPlugin() bool {
func (h *HTTP) NeedPluginPort() bool {
return false
}
+142
View File
@@ -0,0 +1,142 @@
package serverObj
import (
"fmt"
"github.com/v2rayA/v2rayA/common"
"github.com/v2rayA/v2rayA/pkg/util/log"
"net"
"net/url"
"regexp"
"strconv"
"strings"
)
func init() {
FromLinkRegister("ping-tunnel", NewPingTunnel)
EmptyRegister("ping-tunnel", func() (ServerObj, error) {
return new(PingTunnel), nil
})
FromLinkRegister("pingtunnel", NewPingTunnel)
EmptyRegister("pingtunnel", func() (ServerObj, error) {
return new(PingTunnel), nil
})
}
type PingTunnel struct {
Name string `json:"name"`
Server string `json:"server"`
Password string `json:"password"`
Protocol string `json:"protocol"`
}
func NewPingTunnel(link string) (ServerObj, error) {
if strings.HasPrefix(link, "pingtunnel://") {
return ParsePingTunnelURL1(link)
} else if strings.HasPrefix(link, "ping-tunnel://") {
return ParsePingTunnelURL2(link)
}
return nil, InvalidParameterErr
}
func ParsePingTunnelURL1(u string) (data *PingTunnel, err error) {
u = strings.TrimPrefix(u, "pingtunnel://")
u, err = common.Base64StdDecode(u)
if err != nil {
log.Warn("ParsePingTunnelURL1: %v", u)
err = fmt.Errorf("ParsePingTunnelURL1: %w", err)
return
}
arr := strings.Split(u, "#")
var ps string
if len(arr) == 2 {
ps, _ = url.QueryUnescape(arr[1])
}
u = arr[0]
re := regexp.MustCompile(`(.+):(.+)`)
subMatch := re.FindStringSubmatch(u)
if len(subMatch) < 3 {
return nil, fmt.Errorf("wrong format of pingtunnel")
}
passwd, err := common.Base64URLDecode(subMatch[2])
if err != nil {
log.Warn("ParsePingTunnelURL1: %v", subMatch[2])
err = fmt.Errorf("ParsePingTunnelURL1: %w", err)
return
}
data = &PingTunnel{
Name: ps,
Server: subMatch[1],
Password: passwd,
Protocol: "pingtunnel",
}
return data, nil
}
func ParsePingTunnelURL2(u string) (data *PingTunnel, err error) {
U, err := url.Parse(u)
if err != nil {
return
}
data = &PingTunnel{
Name: U.Fragment,
Server: U.Host,
Password: U.User.String(),
Protocol: "pingtunnel",
}
return data, nil
}
func (p *PingTunnel) Configuration(info PriorInfo) (c Configuration, err error) {
U := url.URL{
Scheme: "ping-tunnel",
Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(info.PluginPort)),
RawQuery: url.Values{
"password": []string{p.Password},
"server": []string{p.Server},
}.Encode(),
}
return Configuration{
CoreOutbound: info.PluginObj(),
PluginChain: U.String(),
UDPSupport: false,
}, nil
}
func (p *PingTunnel) ExportToURL() string {
U := url.URL{
Scheme: "ping-tunnel",
User: url.User(p.Password),
Host: p.Server,
Fragment: p.Name,
}
return U.String()
}
func (p *PingTunnel) NeedPluginPort() bool {
return true
}
func (p *PingTunnel) ProtoToShow() string {
return p.Protocol
}
func (p *PingTunnel) GetProtocol() string {
return p.Protocol
}
func (p *PingTunnel) GetHostname() string {
return p.Server
}
func (p *PingTunnel) GetPort() int {
// PingTunnel Need No Port
return 0
}
func (p *PingTunnel) GetName() string {
return p.Name
}
func (p *PingTunnel) SetName(name string) {
p.Name = name
}
+125
View File
@@ -0,0 +1,125 @@
package serverObj
import (
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/coreObj"
"github.com/v2rayA/v2rayA/pkg/util/log"
"os/exec"
"strconv"
"strings"
)
var ErrUnsupportedPlugin = fmt.Errorf("unsupported plugin")
const PluginManagerScheme = "plugin-manager"
func init() {
FromLinkRegister(PluginManagerScheme, NewPlugin)
EmptyRegister(PluginManagerScheme, func() (ServerObj, error) {
return new(Plugin), nil
})
}
type Plugin struct {
Name string `json:"pm_name"`
Host string `json:"pm_add"`
Port string `json:"pm_port"`
ProtocolToShow string `json:"pm_protocol"`
Link string `json:"pm_link"`
Protocol string `json:"protocol"`
}
func NewPlugin(link string) (ServerObj, error) {
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
b, err := exec.Command(pm,
"--stage=parse",
fmt.Sprintf("--link=%v", link),
fmt.Sprintf("--v2raya-confdir=%v", conf.GetEnvironmentConfig().Config),
).CombinedOutput()
if err != nil {
log.Info("[PluginManager] failed to parse %v: %v", link, string(b))
return nil, err
}
nExpected := 4
fields := strings.SplitN(strings.TrimSpace(string(b)), ";", nExpected)
if len(fields) < nExpected {
return nil, fmt.Errorf("[PluginManager] insufficient return value: %v. Expected number: %v", fields, nExpected)
}
return &Plugin{
Name: fields[0],
Host: fields[1],
Port: fields[2],
ProtocolToShow: fields[3],
Link: link,
Protocol: PluginManagerScheme,
}, nil
}
return nil, ErrUnsupportedPlugin
}
func (v *Plugin) Configuration(info PriorInfo) (c Configuration, err error) {
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
b, err := exec.Command(pm,
"--stage=configuration",
fmt.Sprintf("--link=%v", v.Link),
fmt.Sprintf("--port=%v", info.PluginPort),
fmt.Sprintf("--v2raya-confdir=%v", conf.GetEnvironmentConfig().Config),
).CombinedOutput()
sOut := strings.TrimSpace(string(b))
if err != nil {
return Configuration{}, fmt.Errorf("[PluginManager] Error when Configuration: %w: %v", err, sOut)
}
var core coreObj.OutboundObject
if err := jsoniter.UnmarshalFromString(sOut, &core); err != nil {
return Configuration{}, fmt.Errorf("[PluginManager] Error when Configuration: failed to parse json output")
}
core.Tag = info.Tag
return Configuration{
CoreOutbound: core,
PluginChain: "",
UDPSupport: true,
PluginManagerServerLink: v.Link,
}, nil
} else {
return Configuration{}, ErrUnsupportedPlugin
}
}
func (v *Plugin) ExportToURL() string {
if v.Link == "" {
log.Warn("You may need to re-import the node for PluginManager to take effect")
}
return v.Link
}
func (v *Plugin) NeedPluginPort() bool {
return true
}
func (v *Plugin) ProtoToShow() string {
return v.ProtocolToShow + "(plugin)"
}
func (v *Plugin) GetProtocol() string {
return v.ProtocolToShow
}
func (v *Plugin) GetHostname() string {
return v.Host
}
func (v *Plugin) GetPort() int {
p, _ := strconv.Atoi(v.Port)
return p
}
func (v *Plugin) GetName() string {
return v.Name
}
func (v *Plugin) SetName(name string) {
v.Name = name
}
+15 -5
View File
@@ -2,6 +2,7 @@ package serverObj
import (
"fmt"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/coreObj"
"github.com/v2rayA/v2rayA/core/v2ray/where"
"net/url"
@@ -12,7 +13,7 @@ var InvalidParameterErr = fmt.Errorf("invalid parameters")
type ServerObj interface {
Configuration(info PriorInfo) (c Configuration, err error)
ExportToURL() string
NeedPlugin() bool
NeedPluginPort() bool
ProtoToShow() string
GetProtocol() string
GetHostname() string
@@ -22,10 +23,11 @@ type ServerObj interface {
}
type Configuration struct {
CoreOutbound coreObj.OutboundObject
ExtraOutbounds []coreObj.OutboundObject
PluginChain string // The first is a server plugin, and the others are client plugins. Split by ",".
UDPSupport bool
CoreOutbound coreObj.OutboundObject
ExtraOutbounds []coreObj.OutboundObject
PluginChain string // The first is a server plugin, and the others are client plugins. Split by ",".
UDPSupport bool
PluginManagerServerLink string
}
type PriorInfo struct {
@@ -64,6 +66,10 @@ func EmptyRegister(name string, creator EmptyCreator) {
func New(name string) (ServerObj, error) {
if creator, ok := emptyCreators[name]; ok {
return creator()
} else if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
// we do not support to override build-in protocols
creator := emptyCreators[PluginManagerScheme]
return creator()
} else {
return nil, fmt.Errorf("unsupported link type: %v", name)
}
@@ -71,6 +77,10 @@ func New(name string) (ServerObj, error) {
func NewFromLink(name string, link string) (ServerObj, error) {
if creator, ok := fromLinkCreators[name]; ok {
return creator(link)
} else if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
// we do not support to override build-in protocols
creator := fromLinkCreators[PluginManagerScheme]
return creator(link)
} else {
return nil, fmt.Errorf("unsupported link type: %v", name)
}
+1 -1
View File
@@ -229,7 +229,7 @@ func (s *Shadowsocks) ExportToURL() string {
return u.String()
}
func (s *Shadowsocks) NeedPlugin() bool {
func (s *Shadowsocks) NeedPluginPort() bool {
return len(s.Plugin.Name) > 0
}
+1 -1
View File
@@ -149,7 +149,7 @@ func (s *ShadowsocksR) ExportToURL() string {
)), "="))
}
func (s *ShadowsocksR) NeedPlugin() bool {
func (s *ShadowsocksR) NeedPluginPort() bool {
return true
}
+1 -1
View File
@@ -100,7 +100,7 @@ func (h *SOCKS) ExportToURL() string {
return u.String()
}
func (h *SOCKS) NeedPlugin() bool {
func (h *SOCKS) NeedPluginPort() bool {
return false
}
+1 -1
View File
@@ -180,7 +180,7 @@ func (t *Trojan) ExportToURL() string {
return u.String()
}
func (t *Trojan) NeedPlugin() bool {
func (t *Trojan) NeedPluginPort() bool {
return t.Protocol == "trojan-go"
}
+1 -1
View File
@@ -414,7 +414,7 @@ func (v *V2Ray) ExportToURL() string {
return ""
}
func (v *V2Ray) NeedPlugin() bool {
func (v *V2Ray) NeedPluginPort() bool {
return false
}
+33 -9
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"github.com/shirou/gopsutil/v3/mem"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/serverObj"
"github.com/v2rayA/v2rayA/core/v2ray/asset"
"github.com/v2rayA/v2rayA/core/v2ray/where"
@@ -27,7 +28,8 @@ type Process struct {
// mutex protect the proc
mutex sync.Mutex
proc *os.Process
procCancel func()
procCancel func() // cancel func for proc and pluginManagers
pluginManagers []*os.Process
template *Template
tag2WhichIndex map[string]int
}
@@ -53,6 +55,34 @@ func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (
return nil, fmt.Errorf("%v", err)
}
go tmpl.ServePlugins()
pCtx, cancel := context.WithCancel(context.Background())
defer func() {
if err != nil {
cancel()
}
}()
// start PluginManagers
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
for _, v := range tmpl.PluginManagerInfoList {
arguments := []string{
pm,
"--stage=run",
fmt.Sprintf("--link=%v", v.Link),
fmt.Sprintf("--port=%v", v.Port),
fmt.Sprintf("--v2raya-confdir=%v", conf.GetEnvironmentConfig().Config),
}
proc, err := RunWithLog(pCtx, pm, arguments, "", os.Environ())
if err != nil {
// clean
for _, pm := range process.pluginManagers {
_ = pm.Kill()
}
process.pluginManagers = nil
return nil, fmt.Errorf("executing PluginManager [state: run, link: %v]: %w", v.Link, err)
}
process.pluginManagers = append(process.pluginManagers, proc)
}
}
defer func() {
if err != nil {
_ = tmpl.Close()
@@ -61,18 +91,15 @@ func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (
if tmpl.API == nil {
log.Fatal("unexpected tmpl.API == nil")
}
ctx, cancel := context.WithCancel(context.Background())
process.procCancel = cancel
if err = prestart(); err != nil {
return nil, err
}
proc, err := StartCoreProcess(ctx)
proc, err := StartCoreProcess(pCtx)
if err != nil {
cancel()
return nil, err
}
if err = poststart(); err != nil {
cancel()
return nil, err
}
process.proc = proc
@@ -102,7 +129,6 @@ func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (
for _, plu := range tmpl.Plugins {
_, port, err := net.SplitHostPort(plu.ListenAddr())
if err != nil {
cancel()
return nil, err
}
portList = append(portList, port)
@@ -116,14 +142,12 @@ func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (
continue
}
if unexpectedExiting {
cancel()
if log.Log.GetLevel() > log.ParseLevel("info") {
log.Error("some critical information may lost due to your log level")
}
return nil, fmt.Errorf("unexpected exiting: check the log for more information")
}
if time.Since(startTime) > 15*time.Second {
cancel()
return nil, fmt.Errorf("timeout: check the log for more information")
}
time.Sleep(200 * time.Millisecond)
@@ -233,7 +257,7 @@ func StartCoreProcess(ctx context.Context) (*os.Process, error) {
func findAvailablePluginPorts(vms []serverObj.ServerObj) (pluginPortMap map[int]int, err error) {
pluginPortMap = make(map[int]int)
for i, v := range vms {
if !v.NeedPlugin() {
if !v.NeedPluginPort() {
continue
}
//find a port that not be occupied
+6
View File
@@ -158,6 +158,12 @@ func (m *CoreProcessManager) Stop(saveRunning bool) {
m.mu.Lock()
defer m.mu.Unlock()
m.stop(saveRunning)
if m.p != nil {
for _, pm := range m.p.pluginManagers {
_ = pm.Kill()
}
m.p.pluginManagers = nil
}
}
func (m *CoreProcessManager) stop(saveRunning bool) {
+33 -10
View File
@@ -47,13 +47,19 @@ type Template struct {
MultiObservatory *coreObj.MultiObservatory `json:"multiObservatory,omitempty"`
API *coreObj.APIObject `json:"api,omitempty"`
Variant where.Variant `json:"-"`
CoreVersion string `json:"-"`
Plugins []plugin.Server `json:"-"`
OutboundTags []string `json:"-"`
ApiCloses []func() `json:"-"`
ApiPort int `json:"-"`
Setting *configure.Setting `json:"-"`
Variant where.Variant `json:"-"`
CoreVersion string `json:"-"`
Plugins []plugin.Server `json:"-"`
OutboundTags []string `json:"-"`
ApiCloses []func() `json:"-"`
ApiPort int `json:"-"`
Setting *configure.Setting `json:"-"`
PluginManagerInfoList []PluginManagerInfo `json:"-"`
}
type PluginManagerInfo struct {
Link string
Port int
}
func (t *Template) Close() error {
@@ -1226,9 +1232,9 @@ func (t *Template) resolveOutbounds(
usedByBalancer bool
balancerPluginPort int
)
// a vmessInfo(server template) may is used by multiple serverInfos(a connected server)
// an vmessInfo(server template) may be used by multiple serverInfos(a connected server)
// outbound name is not just v2ray outbound tag, it may is a balancer
// outbound name is not just v2ray outbound tag, it may be a balancer
type balancer struct {
name string
serverInfo *serverInfo
@@ -1258,6 +1264,12 @@ func (t *Template) resolveOutbounds(
return nil, nil, err
}
extraOutbounds = append(extraOutbounds, c.ExtraOutbounds...)
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: sInfo.PluginPort,
})
}
var s plugin.Server
if len(c.PluginChain) > 0 {
s, err = plugin.ServerFromChain(c.PluginChain)
@@ -1291,7 +1303,12 @@ func (t *Template) resolveOutbounds(
for _, v := range balancers {
c.CoreOutbound.Balancers = append(c.CoreOutbound.Balancers, v.name)
}
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: balancerPluginPort,
})
}
// we use the lowest serverInfo index as the order weight of the balancer outbound
weight := -1
for _, v := range balancers {
@@ -1742,6 +1759,12 @@ func (t *Template) InsertMappingOutbound(o serverObj.ServerObj, inboundPort stri
t.Plugins = append(t.Plugins, server)
}
}
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: pluginPort,
})
}
var mark = 0x80
t.checkAndSetMark(&c.CoreOutbound, mark)
t.Outbounds = append(t.Outbounds, c.CoreOutbound)
+13 -10
View File
@@ -2,6 +2,7 @@ package service
import (
"fmt"
"github.com/v2rayA/v2rayA/conf"
url2 "net/url"
"strings"
"time"
@@ -15,6 +16,15 @@ import (
"github.com/v2rayA/v2rayA/db/configure"
)
func PluginManagerValidateLink(url string) bool {
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
_, err := serverObj.NewFromLink(serverObj.PluginManagerScheme, url)
return err == nil
} else {
return false
}
}
func Import(url string, which *configure.Which) (err error) {
//log.Trace(url)
resolv.CheckResolvConf()
@@ -29,16 +39,9 @@ func Import(url string, which *configure.Which) (err error) {
}
return err
}
if strings.HasPrefix(url, "vmess://") ||
strings.HasPrefix(url, "vless://") ||
strings.HasPrefix(url, "ss://") ||
strings.HasPrefix(url, "ssr://") ||
strings.HasPrefix(url, "trojan://") ||
strings.HasPrefix(url, "trojan-go://") ||
strings.HasPrefix(url, "http-proxy://") ||
strings.HasPrefix(url, "https-proxy://") ||
strings.HasPrefix(url, "socks5://") ||
strings.HasPrefix(url, "http2://") {
supportedPrefix := []string{"vmess://", "vless://", "ss://", "ssr://", "trojan://", "trojan-go://", "http-proxy://",
"https-proxy://", "socks5://", "http2://"}
if PluginManagerValidateLink(url) || common.HasAnyPrefix(url, supportedPrefix) {
var obj serverObj.ServerObj
obj, err = ResolveURL(url)
if err != nil {
+1 -1
View File
@@ -153,7 +153,7 @@ func TestHttpLatency(which []*configure.Which, timeout time.Duration, maxParalle
}
v2rayInboundPort := strconv.Itoa(port)
pluginPort := 0
if v.NeedPlugin() {
if v.NeedPluginPort() {
// find a port for the plugin
for {
l, err := net.Listen("tcp", "127.0.0.1:0")