This commit is contained in:
yuzuki999
2022-06-02 01:35:41 +08:00
commit 358b5888b4
76 changed files with 47129 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
package controller
type Config struct {
ListenIP string `mapstructure:"ListenIP"`
SendIP string `mapstructure:"SendIP"`
UpdatePeriodic int `mapstructure:"UpdatePeriodic"`
CertConfig *CertConfig `mapstructure:"CertConfig"`
EnableDNS bool `mapstructure:"EnableDNS"`
DNSType string `mapstructure:"DNSType"`
DisableUploadTraffic bool `mapstructure:"DisableUploadTraffic"`
DisableGetRule bool `mapstructure:"DisableGetRule"`
EnableProxyProtocol bool `mapstructure:"EnableProxyProtocol"`
EnableFallback bool `mapstructure:"EnableFallback"`
DisableIVCheck bool `mapstructure:"DisableIVCheck"`
DisableSniffing bool `mapstructure:"DisableSniffing"`
FallBackConfigs []*FallBackConfig `mapstructure:"FallBackConfigs"`
}
type CertConfig struct {
CertMode string `mapstructure:"CertMode"` // none, file, http, dns
RejectUnknownSni bool `mapstructure:"RejectUnknownSni"`
CertDomain string `mapstructure:"CertDomain"`
CertFile string `mapstructure:"CertFile"`
KeyFile string `mapstructure:"KeyFile"`
Provider string `mapstructure:"Provider"` // alidns, cloudflare, gandi, godaddy....
Email string `mapstructure:"Email"`
DNSEnv map[string]string `mapstructure:"DNSEnv"`
}
type FallBackConfig struct {
SNI string `mapstructure:"SNI"`
Alpn string `mapstructure:"Alpn"`
Path string `mapstructure:"Path"`
Dest string `mapstructure:"Dest"`
ProxyProtocolVer uint64 `mapstructure:"ProxyProtocolVer"`
}

View File

@@ -0,0 +1,164 @@
package controller
import (
"context"
"fmt"
"github.com/Yuzuki616/V2bX/api"
"github.com/Yuzuki616/V2bX/app/mydispatcher"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/inbound"
"github.com/xtls/xray-core/features/outbound"
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/features/stats"
"github.com/xtls/xray-core/proxy"
)
func (c *Controller) removeInbound(tag string) error {
inboundManager := c.server.GetFeature(inbound.ManagerType()).(inbound.Manager)
err := inboundManager.RemoveHandler(context.Background(), tag)
return err
}
func (c *Controller) removeOutbound(tag string) error {
outboundManager := c.server.GetFeature(outbound.ManagerType()).(outbound.Manager)
err := outboundManager.RemoveHandler(context.Background(), tag)
return err
}
func (c *Controller) addInbound(config *core.InboundHandlerConfig) error {
inboundManager := c.server.GetFeature(inbound.ManagerType()).(inbound.Manager)
rawHandler, err := core.CreateObject(c.server, config)
if err != nil {
return err
}
handler, ok := rawHandler.(inbound.Handler)
if !ok {
return fmt.Errorf("not an InboundHandler: %s", err)
}
if err := inboundManager.AddHandler(context.Background(), handler); err != nil {
return err
}
return nil
}
func (c *Controller) addOutbound(config *core.OutboundHandlerConfig) error {
outboundManager := c.server.GetFeature(outbound.ManagerType()).(outbound.Manager)
rawHandler, err := core.CreateObject(c.server, config)
if err != nil {
return err
}
handler, ok := rawHandler.(outbound.Handler)
if !ok {
return fmt.Errorf("not an InboundHandler: %s", err)
}
if err := outboundManager.AddHandler(context.Background(), handler); err != nil {
return err
}
return nil
}
func (c *Controller) addUsers(users []*protocol.User, tag string) error {
inboundManager := c.server.GetFeature(inbound.ManagerType()).(inbound.Manager)
handler, err := inboundManager.GetHandler(context.Background(), tag)
if err != nil {
return fmt.Errorf("No such inbound tag: %s", err)
}
inboundInstance, ok := handler.(proxy.GetInbound)
if !ok {
return fmt.Errorf("handler %s is not implement proxy.GetInbound", tag)
}
userManager, ok := inboundInstance.GetInbound().(proxy.UserManager)
if !ok {
return fmt.Errorf("handler %s is not implement proxy.UserManager", err)
}
for _, item := range users {
mUser, err := item.ToMemoryUser()
if err != nil {
return err
}
err = userManager.AddUser(context.Background(), mUser)
if err != nil {
return err
}
}
return nil
}
func (c *Controller) removeUsers(users []string, tag string) error {
inboundManager := c.server.GetFeature(inbound.ManagerType()).(inbound.Manager)
handler, err := inboundManager.GetHandler(context.Background(), tag)
if err != nil {
return fmt.Errorf("No such inbound tag: %s", err)
}
inboundInstance, ok := handler.(proxy.GetInbound)
if !ok {
return fmt.Errorf("handler %s is not implement proxy.GetInbound", tag)
}
userManager, ok := inboundInstance.GetInbound().(proxy.UserManager)
if !ok {
return fmt.Errorf("handler %s is not implement proxy.UserManager", err)
}
for _, email := range users {
err = userManager.RemoveUser(context.Background(), email)
if err != nil {
return err
}
}
return nil
}
func (c *Controller) getTraffic(email string) (up int64, down int64) {
upName := "user>>>" + email + ">>>traffic>>>uplink"
downName := "user>>>" + email + ">>>traffic>>>downlink"
statsManager := c.server.GetFeature(stats.ManagerType()).(stats.Manager)
upCounter := statsManager.GetCounter(upName)
downCounter := statsManager.GetCounter(downName)
if upCounter != nil {
up = upCounter.Value()
upCounter.Set(0)
}
if downCounter != nil {
down = downCounter.Value()
downCounter.Set(0)
}
return up, down
}
func (c *Controller) AddInboundLimiter(tag string, nodeSpeedLimit uint64, userList *[]api.UserInfo) error {
dispather := c.server.GetFeature(routing.DispatcherType()).(*mydispatcher.DefaultDispatcher)
err := dispather.Limiter.AddInboundLimiter(tag, nodeSpeedLimit, userList)
return err
}
func (c *Controller) UpdateInboundLimiter(tag string, updatedUserList *[]api.UserInfo) error {
dispather := c.server.GetFeature(routing.DispatcherType()).(*mydispatcher.DefaultDispatcher)
err := dispather.Limiter.UpdateInboundLimiter(tag, updatedUserList)
return err
}
func (c *Controller) DeleteInboundLimiter(tag string) error {
dispather := c.server.GetFeature(routing.DispatcherType()).(*mydispatcher.DefaultDispatcher)
err := dispather.Limiter.DeleteInboundLimiter(tag)
return err
}
func (c *Controller) GetOnlineDevice(tag string) (*[]api.OnlineUser, error) {
dispather := c.server.GetFeature(routing.DispatcherType()).(*mydispatcher.DefaultDispatcher)
return dispather.Limiter.GetOnlineDevice(tag)
}
func (c *Controller) UpdateRule(tag string, newRuleList []api.DetectRule) error {
dispather := c.server.GetFeature(routing.DispatcherType()).(*mydispatcher.DefaultDispatcher)
err := dispather.RuleManager.UpdateRule(tag, newRuleList)
return err
}
func (c *Controller) GetDetectResult(tag string) (*[]api.DetectResult, error) {
dispather := c.server.GetFeature(routing.DispatcherType()).(*mydispatcher.DefaultDispatcher)
return dispather.RuleManager.GetDetectResult(tag)
}

View File

@@ -0,0 +1,357 @@
package controller
import (
"fmt"
"log"
"math"
"reflect"
"time"
"github.com/Yuzuki616/V2bX/api"
"github.com/Yuzuki616/V2bX/common/legocmd"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/core"
)
type Controller struct {
server *core.Instance
config *Config
clientInfo api.ClientInfo
apiClient api.API
nodeInfo *api.NodeInfo
Tag string
userList *[]api.UserInfo
nodeInfoMonitorPeriodic *task.Periodic
userReportPeriodic *task.Periodic
panelType string
}
// New return a Controller service with default parameters.
func New(server *core.Instance, api api.API, config *Config) *Controller {
controller := &Controller{
server: server,
config: config,
apiClient: api,
}
return controller
}
// Start implement the Start() function of the service interface
func (c *Controller) Start() error {
c.clientInfo = c.apiClient.Describe()
// First fetch Node Info
newNodeInfo, err := c.apiClient.GetNodeInfo()
if err != nil {
return err
}
c.nodeInfo = newNodeInfo
c.Tag = c.buildNodeTag()
// Add new tag
err = c.addNewTag(newNodeInfo)
if err != nil {
log.Panic(err)
return err
}
// Update user
userInfo, err := c.apiClient.GetUserList()
if err != nil {
return err
}
err = c.addNewUser(userInfo, newNodeInfo)
if err != nil {
return err
}
//sync controller userList
c.userList = userInfo
// Add Rule Manager
if !c.config.DisableGetRule {
if ruleList, err := c.apiClient.GetNodeRule(); err != nil {
log.Printf("Get rule list filed: %s", err)
} else if len(*ruleList) > 0 {
if err := c.UpdateRule(c.Tag, *ruleList); err != nil {
log.Print(err)
}
}
}
c.nodeInfoMonitorPeriodic = &task.Periodic{
Interval: time.Duration(c.config.UpdatePeriodic) * time.Second,
Execute: c.nodeInfoMonitor,
}
c.userReportPeriodic = &task.Periodic{
Interval: time.Duration(c.config.UpdatePeriodic) * time.Second,
Execute: c.userInfoMonitor,
}
log.Printf("[%s: %d] Start monitor node status", c.nodeInfo.NodeType, c.nodeInfo.NodeId)
// delay to start nodeInfoMonitor
go func() {
time.Sleep(time.Duration(c.config.UpdatePeriodic) * time.Second)
_ = c.nodeInfoMonitorPeriodic.Start()
}()
log.Printf("[%s: %d] Start report node status", c.nodeInfo.NodeType, c.nodeInfo.NodeId)
// delay to start userReport
go func() {
time.Sleep(time.Duration(c.config.UpdatePeriodic) * time.Second)
_ = c.userReportPeriodic.Start()
}()
return nil
}
// Close implement the Close() function of the service interface
func (c *Controller) Close() error {
if c.nodeInfoMonitorPeriodic != nil {
err := c.nodeInfoMonitorPeriodic.Close()
if err != nil {
log.Panicf("node info periodic close failed: %s", err)
}
}
if c.nodeInfoMonitorPeriodic != nil {
err := c.userReportPeriodic.Close()
if err != nil {
log.Panicf("user report periodic close failed: %s", err)
}
}
return nil
}
func (c *Controller) nodeInfoMonitor() (err error) {
// First fetch Node Info
newNodeInfo, err := c.apiClient.GetNodeInfo()
if err != nil {
log.Print(err)
return nil
}
// Update User
newUserInfo, err := c.apiClient.GetUserList()
if err != nil {
log.Print(err)
return nil
}
var nodeInfoChanged = false
// If nodeInfo changed
if !reflect.DeepEqual(c.nodeInfo, newNodeInfo) {
// Remove old tag
oldtag := c.Tag
err := c.removeOldTag(oldtag)
if err != nil {
log.Print(err)
return nil
}
if c.nodeInfo.NodeType == "Shadowsocks-Plugin" {
err = c.removeOldTag(fmt.Sprintf("dokodemo-door_%s+1", c.Tag))
}
if err != nil {
log.Print(err)
return nil
}
// Add new tag
c.nodeInfo = newNodeInfo
c.Tag = c.buildNodeTag()
err = c.addNewTag(newNodeInfo)
if err != nil {
log.Print(err)
return nil
}
nodeInfoChanged = true
// Remove Old limiter
if err = c.DeleteInboundLimiter(oldtag); err != nil {
log.Print(err)
return nil
}
}
// Check Rule
if !c.config.DisableGetRule {
if ruleList, err := c.apiClient.GetNodeRule(); err != nil {
log.Printf("Get rule list filed: %s", err)
} else if len(*ruleList) > 0 {
if err := c.UpdateRule(c.Tag, *ruleList); err != nil {
log.Print(err)
}
}
}
// Check Cert
if c.nodeInfo.V2ray.Inbounds[0].StreamSetting.Security == "tls" && (c.config.CertConfig.CertMode == "dns" || c.config.CertConfig.CertMode == "http") {
lego, err := legocmd.New()
if err != nil {
log.Print(err)
}
// Xray-core supports the OcspStapling certification hot renew
_, _, err = lego.RenewCert(c.config.CertConfig.CertDomain, c.config.CertConfig.Email, c.config.CertConfig.CertMode, c.config.CertConfig.Provider, c.config.CertConfig.DNSEnv)
if err != nil {
log.Print(err)
}
}
if nodeInfoChanged {
err = c.addNewUser(newUserInfo, newNodeInfo)
if err != nil {
log.Print(err)
return nil
}
} else {
deleted, added := compareUserList(c.userList, newUserInfo)
if len(deleted) > 0 {
deletedEmail := make([]string, len(deleted))
for i, u := range deleted {
deletedEmail[i] = fmt.Sprintf("%s|%d|%d", c.Tag, c.nodeInfo.NodeId, u.UID)
}
err := c.removeUsers(deletedEmail, c.Tag)
if err != nil {
log.Print(err)
}
}
if len(added) > 0 {
err = c.addNewUser(&added, c.nodeInfo)
if err != nil {
log.Print(err)
}
// Update Limiter
if err := c.UpdateInboundLimiter(c.Tag, &added); err != nil {
log.Print(err)
}
}
log.Printf("[%s: %d] %d user deleted, %d user added", c.nodeInfo.NodeType, c.nodeInfo.NodeId,
len(deleted), len(added))
}
c.userList = newUserInfo
return nil
}
func (c *Controller) removeOldTag(oldtag string) (err error) {
err = c.removeInbound(oldtag)
if err != nil {
return err
}
err = c.removeOutbound(oldtag)
if err != nil {
return err
}
return nil
}
func (c *Controller) addNewTag(newNodeInfo *api.NodeInfo) (err error) {
inboundConfig, err := InboundBuilder(c.config, newNodeInfo, c.Tag)
if err != nil {
return err
}
err = c.addInbound(inboundConfig)
if err != nil {
return err
}
outBoundConfig, err := OutboundBuilder(c.config, newNodeInfo, c.Tag)
if err != nil {
return err
}
err = c.addOutbound(outBoundConfig)
if err != nil {
return err
}
return nil
}
func (c *Controller) addNewUser(userInfo *[]api.UserInfo, nodeInfo *api.NodeInfo) (err error) {
users := make([]*protocol.User, 0)
if nodeInfo.NodeType == "V2ray" {
if nodeInfo.EnableVless {
users = c.buildVlessUser(userInfo)
} else {
alterID := 0
alterID = (*userInfo)[0].V2rayUser.AlterId
if alterID >= 0 && alterID < math.MaxUint16 {
users = c.buildVmessUser(userInfo, uint16(alterID))
} else {
users = c.buildVmessUser(userInfo, 0)
return fmt.Errorf("AlterID should between 0 to 1<<16 - 1, set it to 0 for now")
}
}
} else if nodeInfo.NodeType == "Trojan" {
users = c.buildTrojanUser(userInfo)
} else if nodeInfo.NodeType == "Shadowsocks" {
users = c.buildSSUser(userInfo, nodeInfo.SS.CypherMethod)
} else {
return fmt.Errorf("unsupported node type: %s", nodeInfo.NodeType)
}
err = c.addUsers(users, c.Tag)
if err != nil {
return err
}
log.Printf("[%s: %d] Added %d new users", c.nodeInfo.NodeType, c.nodeInfo.NodeId, len(*userInfo))
return nil
}
func compareUserList(old, new *[]api.UserInfo) (deleted, added []api.UserInfo) {
tmp := map[int]int{}
for i := range *old {
tmp[(*old)[i].UID] = i
}
l := len(tmp)
for i := range *new {
tmp[(*new)[i].UID] = i
if l != len(tmp) {
tmp[(*new)[i].UID] = i
added = append(added, (*new)[i])
l++
} else {
delete(tmp, (*new)[i].UID)
l--
}
}
for i := range *old {
tmp[(*old)[i].UID] = i
if l == len(tmp) {
deleted = append(deleted, (*old)[i])
} else {
l++
}
}
return deleted, added
}
func (c *Controller) userInfoMonitor() (err error) {
// Get User traffic
userTraffic := make([]api.UserTraffic, 0)
for _, user := range *c.userList {
up, down := c.getTraffic(c.buildUserTag(&user))
if up > 0 || down > 0 {
userTraffic = append(userTraffic, api.UserTraffic{
UID: user.UID,
Email: user.V2rayUser.Email,
Upload: up,
Download: down})
}
}
if len(userTraffic) > 0 && !c.config.DisableUploadTraffic {
err = c.apiClient.ReportUserTraffic(&userTraffic)
if err != nil {
log.Print(err)
}
}
// Report Online info
if onlineDevice, err := c.GetOnlineDevice(c.Tag); err != nil {
log.Print(err)
} else {
log.Printf("[%s: %d] Report %d online users", c.nodeInfo.NodeType, c.nodeInfo.NodeId, len(*onlineDevice))
}
// Report Illegal user
if detectResult, err := c.GetDetectResult(c.Tag); err != nil {
log.Print(err)
} else {
log.Printf("[%s: %d] Report %d illegal behaviors", c.nodeInfo.NodeType, c.nodeInfo.NodeId, len(*detectResult))
}
return nil
}
func (c *Controller) buildNodeTag() string {
return fmt.Sprintf("%s_%s_%d", c.nodeInfo.NodeType, c.config.ListenIP, c.nodeInfo.NodeId)
}

View File

@@ -0,0 +1,82 @@
package controller_test
import (
"fmt"
"github.com/Yuzuki616/V2bX/api/v2board"
"github.com/xtls/xray-core/proxy/shadowsocks_2022"
"os"
"os/signal"
"runtime"
"syscall"
"testing"
"github.com/Yuzuki616/V2bX/api"
_ "github.com/Yuzuki616/V2bX/main/distro/all"
. "github.com/Yuzuki616/V2bX/service/controller"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/infra/conf"
)
func TestController(t *testing.T) {
serverConfig := &conf.Config{
Stats: &conf.StatsConfig{},
LogConfig: &conf.LogConfig{LogLevel: "debug"},
}
policyConfig := &conf.PolicyConfig{}
policyConfig.Levels = map[uint32]*conf.Policy{0: &conf.Policy{
StatsUserUplink: true,
StatsUserDownlink: true,
}}
serverConfig.Policy = policyConfig
config, _ := serverConfig.Build()
// config := &core.Config{
// App: []*serial.TypedMessage{
// serial.ToTypedMessage(&dispatcher.Config{}),
// serial.ToTypedMessage(&proxyman.InboundConfig{}),
// serial.ToTypedMessage(&proxyman.OutboundConfig{}),
// serial.ToTypedMessage(&stats.Config{}),
// }}
server, err := core.New(config)
defer server.Close()
if err != nil {
t.Errorf("failed to create instance: %s", err)
}
if err = server.Start(); err != nil {
t.Errorf("Failed to start instance: %s", err)
}
certConfig := &CertConfig{
CertMode: "http",
CertDomain: "test.ss.tk",
Provider: "alidns",
Email: "ss@ss.com",
}
controlerconfig := &Config{
UpdatePeriodic: 5,
CertConfig: certConfig,
}
apiConfig := &api.Config{
APIHost: "http://127.0.0.1:667",
Key: "123",
NodeID: 41,
NodeType: "V2ray",
}
apiclient := v2board.New(apiConfig)
c := New(server, apiclient, controlerconfig)
fmt.Println("Sleep 1s")
err = c.Start()
if err != nil {
t.Error(err)
}
//Explicitly triggering GC to remove garbage from config loading.
runtime.GC()
{
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, os.Kill, syscall.SIGTERM)
<-osSignals
}
test := shadowsocks_2022.MultiUserServerConfig{}
test.Network
}

View File

@@ -0,0 +1,255 @@
//Package generate the InbounderConfig used by add inbound
package controller
import (
"encoding/json"
"fmt"
"github.com/Yuzuki616/V2bX/api"
"github.com/Yuzuki616/V2bX/common/legocmd"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/uuid"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/infra/conf"
)
//InboundBuilder build Inbound config for different protocol
func InboundBuilder(config *Config, nodeInfo *api.NodeInfo, tag string) (*core.InboundHandlerConfig, error) {
var proxySetting interface{}
if nodeInfo.NodeType == "V2ray" {
if nodeInfo.EnableVless {
nodeInfo.V2ray.Inbounds[0].Protocol = "vless"
// Enable fallback
if config.EnableFallback {
fallbackConfigs, err := buildVlessFallbacks(config.FallBackConfigs)
if err == nil {
proxySetting = &conf.VLessInboundConfig{
Decryption: "none",
Fallbacks: fallbackConfigs,
}
} else {
return nil, err
}
} else {
proxySetting = &conf.VLessInboundConfig{
Decryption: "none",
}
}
} else {
nodeInfo.V2ray.Inbounds[0].Protocol = "vmess"
proxySetting = &conf.VMessInboundConfig{}
}
} else if nodeInfo.NodeType == "Trojan" {
nodeInfo.V2ray = &api.V2rayConfig{}
nodeInfo.V2ray.Inbounds = make([]conf.InboundDetourConfig, 1)
nodeInfo.V2ray.Inbounds[0].Protocol = "trojan"
// Enable fallback
if config.EnableFallback {
fallbackConfigs, err := buildTrojanFallbacks(config.FallBackConfigs)
if err == nil {
proxySetting = &conf.TrojanServerConfig{
Fallbacks: fallbackConfigs,
}
} else {
return nil, err
}
} else {
proxySetting = &conf.TrojanServerConfig{}
}
nodeInfo.V2ray.Inbounds[0].PortList = &conf.PortList{
Range: []conf.PortRange{{From: uint32(nodeInfo.Trojan.LocalPort), To: uint32(nodeInfo.Trojan.LocalPort)}},
}
t := conf.TransportProtocol(nodeInfo.SS.TransportProtocol)
nodeInfo.V2ray.Inbounds[0].StreamSetting = &conf.StreamConfig{Network: &t}
} else if nodeInfo.NodeType == "Shadowsocks" {
nodeInfo.V2ray = &api.V2rayConfig{}
nodeInfo.V2ray.Inbounds = make([]conf.InboundDetourConfig, 1)
nodeInfo.V2ray.Inbounds[0].Protocol = "shadowsocks"
proxySetting = &conf.ShadowsocksServerConfig{}
randomPasswd := uuid.New()
defaultSSuser := &conf.ShadowsocksUserConfig{
Cipher: "aes-128-gcm",
Password: randomPasswd.String(),
}
proxySetting, _ := proxySetting.(*conf.ShadowsocksServerConfig)
proxySetting.Users = append(proxySetting.Users, defaultSSuser)
proxySetting.NetworkList = &conf.NetworkList{"tcp", "udp"}
proxySetting.IVCheck = true
if config.DisableIVCheck {
proxySetting.IVCheck = false
}
nodeInfo.V2ray.Inbounds[0].PortList = &conf.PortList{
Range: []conf.PortRange{{From: uint32(nodeInfo.SS.Port), To: uint32(nodeInfo.SS.Port)}},
}
t := conf.TransportProtocol(nodeInfo.SS.TransportProtocol)
nodeInfo.V2ray.Inbounds[0].StreamSetting = &conf.StreamConfig{Network: &t}
} else if nodeInfo.NodeType == "dokodemo-door" {
nodeInfo.V2ray = &api.V2rayConfig{}
nodeInfo.V2ray.Inbounds = make([]conf.InboundDetourConfig, 1)
nodeInfo.V2ray.Inbounds[0].Protocol = "dokodemo-door"
proxySetting = struct {
Host string `json:"address"`
NetworkList []string `json:"network"`
}{
Host: "v1.mux.cool",
NetworkList: []string{"tcp", "udp"},
}
} else {
return nil, fmt.Errorf("unsupported node type: %s, Only support: V2ray, Trojan, Shadowsocks, and Shadowsocks-Plugin", nodeInfo.NodeType)
}
// Build Listen IP address
ipAddress := net.ParseAddress(config.ListenIP)
nodeInfo.V2ray.Inbounds[0].ListenOn = &conf.Address{Address: ipAddress}
// SniffingConfig
sniffingConfig := &conf.SniffingConfig{
Enabled: true,
DestOverride: &conf.StringList{"http", "tls"},
}
if config.DisableSniffing {
sniffingConfig.Enabled = false
}
nodeInfo.V2ray.Inbounds[0].SniffingConfig = sniffingConfig
var setting json.RawMessage
// Build Protocol and Protocol setting
setting, err := json.Marshal(proxySetting)
if err != nil {
return nil, fmt.Errorf("marshal proxy %s config fialed: %s", nodeInfo.NodeType, err)
}
if *nodeInfo.V2ray.Inbounds[0].StreamSetting.Network == "tcp" {
if nodeInfo.NodeType == "V2ray" {
nodeInfo.V2ray.Inbounds[0].StreamSetting.TCPSettings.AcceptProxyProtocol = config.EnableProxyProtocol
}
tcpSetting := &conf.TCPConfig{
AcceptProxyProtocol: config.EnableProxyProtocol,
}
nodeInfo.V2ray.Inbounds[0].StreamSetting.TCPSettings = tcpSetting
} else if *nodeInfo.V2ray.Inbounds[0].StreamSetting.Network == "websocket" {
nodeInfo.V2ray.Inbounds[0].StreamSetting.WSSettings.AcceptProxyProtocol = config.EnableProxyProtocol
}
// Build TLS and XTLS settings
if nodeInfo.EnableTls && config.CertConfig.CertMode != "none" {
nodeInfo.V2ray.Inbounds[0].StreamSetting.Security = nodeInfo.TLSType
certFile, keyFile, err := getCertFile(config.CertConfig)
if err != nil {
return nil, err
}
if nodeInfo.TLSType == "tls" {
tlsSettings := &conf.TLSConfig{
RejectUnknownSNI: config.CertConfig.RejectUnknownSni,
}
tlsSettings.Certs = append(tlsSettings.Certs, &conf.TLSCertConfig{CertFile: certFile, KeyFile: keyFile, OcspStapling: 3600})
nodeInfo.V2ray.Inbounds[0].StreamSetting.TLSSettings = tlsSettings
} else if nodeInfo.TLSType == "xtls" {
xtlsSettings := &conf.XTLSConfig{
RejectUnknownSNI: config.CertConfig.RejectUnknownSni,
}
xtlsSettings.Certs = append(xtlsSettings.Certs, &conf.XTLSCertConfig{
CertFile: certFile,
KeyFile: keyFile,
OcspStapling: 3600})
nodeInfo.V2ray.Inbounds[0].StreamSetting.XTLSSettings = xtlsSettings
}
}
// Support ProxyProtocol for any transport protocol
if *nodeInfo.V2ray.Inbounds[0].StreamSetting.Network != "tcp" &&
*nodeInfo.V2ray.Inbounds[0].StreamSetting.Network != "ws" &&
config.EnableProxyProtocol {
sockoptConfig := &conf.SocketConfig{
AcceptProxyProtocol: config.EnableProxyProtocol,
}
nodeInfo.V2ray.Inbounds[0].StreamSetting.SocketSettings = sockoptConfig
}
*nodeInfo.V2ray.Inbounds[0].Settings = setting
return nodeInfo.V2ray.Inbounds[0].Build()
}
func getCertFile(certConfig *CertConfig) (certFile string, keyFile string, err error) {
if certConfig.CertMode == "file" {
if certConfig.CertFile == "" || certConfig.KeyFile == "" {
return "", "", fmt.Errorf("cert file path or key file path not exist")
}
return certConfig.CertFile, certConfig.KeyFile, nil
} else if certConfig.CertMode == "dns" {
lego, err := legocmd.New()
if err != nil {
return "", "", err
}
certPath, keyPath, err := lego.DNSCert(certConfig.CertDomain, certConfig.Email, certConfig.Provider, certConfig.DNSEnv)
if err != nil {
return "", "", err
}
return certPath, keyPath, err
} else if certConfig.CertMode == "http" {
lego, err := legocmd.New()
if err != nil {
return "", "", err
}
certPath, keyPath, err := lego.HTTPCert(certConfig.CertDomain, certConfig.Email)
if err != nil {
return "", "", err
}
return certPath, keyPath, err
}
return "", "", fmt.Errorf("unsupported certmode: %s", certConfig.CertMode)
}
func buildVlessFallbacks(fallbackConfigs []*FallBackConfig) ([]*conf.VLessInboundFallback, error) {
if fallbackConfigs == nil {
return nil, fmt.Errorf("you must provide FallBackConfigs")
}
vlessFallBacks := make([]*conf.VLessInboundFallback, len(fallbackConfigs))
for i, c := range fallbackConfigs {
if c.Dest == "" {
return nil, fmt.Errorf("dest is required for fallback fialed")
}
var dest json.RawMessage
dest, err := json.Marshal(c.Dest)
if err != nil {
return nil, fmt.Errorf("marshal dest %s config fialed: %s", dest, err)
}
vlessFallBacks[i] = &conf.VLessInboundFallback{
Name: c.SNI,
Alpn: c.Alpn,
Path: c.Path,
Dest: dest,
Xver: c.ProxyProtocolVer,
}
}
return vlessFallBacks, nil
}
func buildTrojanFallbacks(fallbackConfigs []*FallBackConfig) ([]*conf.TrojanInboundFallback, error) {
if fallbackConfigs == nil {
return nil, fmt.Errorf("you must provide FallBackConfigs")
}
trojanFallBacks := make([]*conf.TrojanInboundFallback, len(fallbackConfigs))
for i, c := range fallbackConfigs {
if c.Dest == "" {
return nil, fmt.Errorf("dest is required for fallback fialed")
}
var dest json.RawMessage
dest, err := json.Marshal(c.Dest)
if err != nil {
return nil, fmt.Errorf("marshal dest %s config fialed: %s", dest, err)
}
trojanFallBacks[i] = &conf.TrojanInboundFallback{
Name: c.SNI,
Alpn: c.Alpn,
Path: c.Path,
Dest: dest,
Xver: c.ProxyProtocolVer,
}
}
return trojanFallBacks, nil
}

View File

@@ -0,0 +1,100 @@
package controller_test
import (
"testing"
"github.com/Yuzuki616/V2bX/api"
. "github.com/Yuzuki616/V2bX/service/controller"
)
func TestBuildV2ray(t *testing.T) {
nodeInfo := &api.NodeInfo{
NodeType: "V2ray",
NodeID: 1,
Port: 1145,
SpeedLimit: 0,
AlterID: 2,
TransportProtocol: "ws",
Host: "test.test.tk",
Path: "v2ray",
EnableTLS: false,
TLSType: "tls",
}
certConfig := &CertConfig{
CertMode: "http",
CertDomain: "test.test.tk",
Provider: "alidns",
Email: "test@gmail.com",
}
config := &Config{
CertConfig: certConfig,
}
_, err := InboundBuilder(config, nodeInfo)
if err != nil {
t.Error(err)
}
}
func TestBuildTrojan(t *testing.T) {
nodeInfo := &api.NodeInfo{
NodeType: "Trojan",
NodeID: 1,
Port: 1145,
SpeedLimit: 0,
AlterID: 2,
TransportProtocol: "tcp",
Host: "trojan.test.tk",
Path: "v2ray",
EnableTLS: false,
TLSType: "tls",
}
DNSEnv := make(map[string]string)
DNSEnv["ALICLOUD_ACCESS_KEY"] = "aaa"
DNSEnv["ALICLOUD_SECRET_KEY"] = "bbb"
certConfig := &CertConfig{
CertMode: "dns",
CertDomain: "trojan.test.tk",
Provider: "alidns",
Email: "test@gmail.com",
DNSEnv: DNSEnv,
}
config := &Config{
CertConfig: certConfig,
}
_, err := InboundBuilder(config, nodeInfo)
if err != nil {
t.Error(err)
}
}
func TestBuildSS(t *testing.T) {
nodeInfo := &api.NodeInfo{
NodeType: "Shadowsocks",
NodeID: 1,
Port: 1145,
SpeedLimit: 0,
AlterID: 2,
TransportProtocol: "tcp",
Host: "test.test.tk",
Path: "v2ray",
EnableTLS: false,
TLSType: "tls",
}
DNSEnv := make(map[string]string)
DNSEnv["ALICLOUD_ACCESS_KEY"] = "aaa"
DNSEnv["ALICLOUD_SECRET_KEY"] = "bbb"
certConfig := &CertConfig{
CertMode: "dns",
CertDomain: "trojan.test.tk",
Provider: "alidns",
Email: "test@me.com",
DNSEnv: DNSEnv,
}
config := &Config{
CertConfig: certConfig,
}
_, err := InboundBuilder(config, nodeInfo)
if err != nil {
t.Error(err)
}
}

View File

@@ -0,0 +1,48 @@
package controller
import (
"encoding/json"
"fmt"
"github.com/Yuzuki616/V2bX/api"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/infra/conf"
)
//OutboundBuilder build freedom outbund config for addoutbound
func OutboundBuilder(config *Config, nodeInfo *api.NodeInfo, tag string) (*core.OutboundHandlerConfig, error) {
outboundDetourConfig := &conf.OutboundDetourConfig{}
outboundDetourConfig.Protocol = "freedom"
outboundDetourConfig.Tag = tag
// Build Send IP address
if config.SendIP != "" {
ipAddress := net.ParseAddress(config.SendIP)
outboundDetourConfig.SendThrough = &conf.Address{ipAddress}
}
// Freedom Protocol setting
var domainStrategy string = "Asis"
if config.EnableDNS {
if config.DNSType != "" {
domainStrategy = config.DNSType
} else {
domainStrategy = "UseIP"
}
}
proxySetting := &conf.FreedomConfig{
DomainStrategy: domainStrategy,
}
// Used for Shadowsocks-Plugin
if nodeInfo.NodeType == "dokodemo-door" {
proxySetting.Redirect = fmt.Sprintf("127.0.0.1:%d", nodeInfo.V2ray.Inbounds[0].PortList.Range[0].From-1)
}
var setting json.RawMessage
setting, err := json.Marshal(proxySetting)
if err != nil {
return nil, fmt.Errorf("Marshal proxy %s config fialed: %s", nodeInfo.NodeType, err)
}
outboundDetourConfig.Settings = &setting
return outboundDetourConfig.Build()
}

View File

@@ -0,0 +1,126 @@
package controller
import (
"fmt"
"strings"
"github.com/Yuzuki616/V2bX/api"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/infra/conf"
"github.com/xtls/xray-core/proxy/shadowsocks"
"github.com/xtls/xray-core/proxy/trojan"
"github.com/xtls/xray-core/proxy/vless"
)
var AEADMethod = []shadowsocks.CipherType{shadowsocks.CipherType_AES_128_GCM, shadowsocks.CipherType_AES_256_GCM, shadowsocks.CipherType_CHACHA20_POLY1305, shadowsocks.CipherType_XCHACHA20_POLY1305}
func (c *Controller) buildVmessUser(userInfo *[]api.UserInfo, serverAlterID uint16) (users []*protocol.User) {
users = make([]*protocol.User, len(*userInfo))
for i, user := range *userInfo {
vmessAccount := &conf.VMessAccount{
ID: user.V2rayUser.Uuid,
AlterIds: serverAlterID,
Security: "auto",
}
users[i] = &protocol.User{
Level: 0,
Email: c.buildUserTag(&user), // Email: InboundTag|email|uid
Account: serial.ToTypedMessage(vmessAccount.Build()),
}
}
return users
}
func (c *Controller) buildVlessUser(userInfo *[]api.UserInfo) (users []*protocol.User) {
users = make([]*protocol.User, len(*userInfo))
for i, user := range *userInfo {
vlessAccount := &vless.Account{
Id: user.V2rayUser.Uuid,
Flow: "xtls-rprx-direct",
}
users[i] = &protocol.User{
Level: 0,
Email: c.buildUserTag(&user),
Account: serial.ToTypedMessage(vlessAccount),
}
}
return users
}
func (c *Controller) buildTrojanUser(userInfo *[]api.UserInfo) (users []*protocol.User) {
users = make([]*protocol.User, len(*userInfo))
for i, user := range *userInfo {
trojanAccount := &trojan.Account{
Password: user.V2rayUser.Uuid,
Flow: "xtls-rprx-direct",
}
users[i] = &protocol.User{
Level: 0,
Email: c.buildUserTag(&user),
Account: serial.ToTypedMessage(trojanAccount),
}
}
return users
}
func cipherFromString(c string) shadowsocks.CipherType {
switch strings.ToLower(c) {
case "aes-128-gcm", "aead_aes_128_gcm":
return shadowsocks.CipherType_AES_128_GCM
case "aes-256-gcm", "aead_aes_256_gcm":
return shadowsocks.CipherType_AES_256_GCM
case "chacha20-poly1305", "aead_chacha20_poly1305", "chacha20-ietf-poly1305":
return shadowsocks.CipherType_CHACHA20_POLY1305
case "none", "plain":
return shadowsocks.CipherType_NONE
default:
return shadowsocks.CipherType_UNKNOWN
}
}
func (c *Controller) buildSSUser(userInfo *[]api.UserInfo, method string) (users []*protocol.User) {
users = make([]*protocol.User, 0)
cypherMethod := cipherFromString(method)
for _, user := range *userInfo {
ssAccount := &shadowsocks.Account{
Password: user.Secret,
CipherType: cypherMethod,
}
users = append(users, &protocol.User{
Level: 0,
Email: c.buildUserTag(&user),
Account: serial.ToTypedMessage(ssAccount),
})
}
return users
}
func (c *Controller) buildSSPluginUser(userInfo *[]api.UserInfo) (users []*protocol.User) {
users = make([]*protocol.User, 0)
for _, user := range *userInfo {
// Check if the cypher method is AEAD
cypherMethod := cipherFromString(user.Cipher)
for _, aeadMethod := range AEADMethod {
if aeadMethod == cypherMethod {
ssAccount := &shadowsocks.Account{
Password: user.Secret,
CipherType: cypherMethod,
}
users = append(users, &protocol.User{
Level: 0,
Email: c.buildUserTag(&user),
Account: serial.ToTypedMessage(ssAccount),
})
}
}
}
return users
}
func (c *Controller) buildUserTag(user *api.UserInfo) string {
return fmt.Sprintf("%s|%s|%d", c.Tag, user.GetUserEmail(), user.UID)
}