mirror of
https://github.com/v2rayA/v2rayA.git
synced 2026-11-20 23:02:25 +03:00
76 lines
2.2 KiB
Go
76 lines
2.2 KiB
Go
package plugin
|
|
|
|
import (
|
|
"fmt"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"github.com/v2rayA/v2rayA/pkg/util/log"
|
|
)
|
|
|
|
// Server interface
|
|
type Server interface {
|
|
// ListenAndServe sets up a listener and serve on it
|
|
ListenAndServe() error
|
|
ListenAddr() string
|
|
NodeName() string
|
|
Close() error
|
|
}
|
|
|
|
// ServerCreator is a function to create proxy servers
|
|
type ServerCreator func(s string, nodeName string, proxy Proxy) (Server, error)
|
|
|
|
var (
|
|
serverCreators = make(map[string]ServerCreator)
|
|
)
|
|
|
|
// RegisterServer is used to register a proxy server
|
|
func RegisterServer(name string, c ServerCreator) {
|
|
serverCreators[name] = c
|
|
}
|
|
|
|
// getAvailableServerSchemes returns a list of registered server schemes
|
|
func getAvailableServerSchemes() []string {
|
|
schemes := make([]string, 0, len(serverCreators))
|
|
for k := range serverCreators {
|
|
schemes = append(schemes, k)
|
|
}
|
|
return schemes
|
|
}
|
|
|
|
// ServerFromURL calls the registered creator to create proxy servers
|
|
// dialer is the default upstream dialer so cannot be nil, we can use Default when calling this function
|
|
func ServerFromURL(s string, nodeName string, p Proxy) (Server, error) {
|
|
if p == nil {
|
|
return nil, fmt.Errorf("ServerFromURL: dialer cannot be nil")
|
|
}
|
|
|
|
if !strings.Contains(s, "://") {
|
|
s = "socks5://" + s
|
|
log.Trace("[plugin] URL scheme missing, defaulting to socks5: %s", s)
|
|
}
|
|
|
|
u, err := url.Parse(s)
|
|
if err != nil {
|
|
log.Warn("[plugin] parse server URL '%s' failed: %v", s, err)
|
|
return nil, fmt.Errorf("parse URL: %w", err)
|
|
}
|
|
|
|
scheme := strings.ToLower(u.Scheme)
|
|
c, ok := serverCreators[scheme]
|
|
if !ok {
|
|
log.Warn("[plugin] unknown server scheme '%s' in URL: %s. Available schemes: %v", u.Scheme, s, getAvailableServerSchemes())
|
|
return nil, fmt.Errorf("unknown server scheme '%s'", u.Scheme)
|
|
}
|
|
|
|
log.Trace("[plugin] creating server for scheme '%s' from URL: %s (node: %s)", scheme, s, nodeName)
|
|
result, err := c(s, nodeName, p)
|
|
if err != nil {
|
|
log.Warn("[plugin] failed to create server for scheme '%s' (node: %s): %v", scheme, nodeName, err)
|
|
return nil, fmt.Errorf("create %s server: %w", scheme, err)
|
|
}
|
|
|
|
log.Info("[plugin] successfully created server for scheme '%s' at %s (node: %s)", scheme, result.ListenAddr(), nodeName)
|
|
return result, nil
|
|
}
|