V2bX/service/controller/controller.go

415 lines
11 KiB
Go
Raw Normal View History

2022-06-01 13:35:41 -04:00
package controller
import (
"fmt"
"log"
"math"
2022-06-05 01:19:39 -04:00
"reflect"
2022-06-04 00:05:46 -04:00
"runtime"
2022-06-01 13:35:41 -04:00
"time"
"github.com/Yuzuki616/V2bX/api"
"github.com/Yuzuki616/V2bX/common/legoCmd"
2022-06-01 13:35:41 -04:00
"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
2022-06-04 00:05:46 -04:00
if err := c.AddInboundLimiter(c.Tag, userInfo); err != nil {
2022-06-02 13:22:56 -04:00
log.Print(err)
}
2022-06-01 13:35:41 -04:00
// Add Rule Manager
if !c.config.DisableGetRule {
2022-06-12 09:10:20 -04:00
if ruleList, protocolRule, err := c.apiClient.GetNodeRule(); err != nil {
2022-06-01 13:35:41 -04:00
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)
}
2022-06-12 09:10:20 -04:00
if len(*protocolRule) > 0 {
if err := c.UpdateProtocolRule(c.Tag, *protocolRule); err != nil {
log.Print(err)
}
}
2022-06-01 13:35:41 -04:00
}
}
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()
}()
2022-06-05 01:19:39 -04:00
runtime.GC()
2022-06-01 13:35:41 -04:00
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
}
var nodeInfoChanged = false
// If nodeInfo changed
2022-06-02 13:22:56 -04:00
if newNodeInfo != nil {
2022-06-06 05:07:21 -04:00
if c.nodeInfo.SS == nil || !reflect.DeepEqual(c.nodeInfo.SS, newNodeInfo.SS) {
2022-06-05 01:19:39 -04:00
// Remove old tag
oldtag := c.Tag
err := c.removeOldTag(oldtag)
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
}
2022-06-01 13:35:41 -04:00
}
}
// Check Rule
if !c.config.DisableGetRule {
2022-06-12 09:10:20 -04:00
if ruleList, protocolRule, err := c.apiClient.GetNodeRule(); err != nil {
2022-06-01 13:35:41 -04:00
log.Printf("Get rule list filed: %s", err)
2022-06-12 09:10:20 -04:00
} else if len(*ruleList) > 0 {
2022-06-01 13:35:41 -04:00
if err := c.UpdateRule(c.Tag, *ruleList); err != nil {
log.Print(err)
}
2022-06-12 09:10:20 -04:00
if len(*protocolRule) > 0 {
if err := c.UpdateProtocolRule(c.Tag, *protocolRule); err != nil {
log.Print(err)
}
}
2022-06-01 13:35:41 -04:00
}
}
// Check Cert
2022-06-04 00:05:46 -04:00
if c.nodeInfo.EnableTls && c.config.CertConfig.CertMode != "none" &&
(c.config.CertConfig.CertMode == "dns" || c.config.CertConfig.CertMode == "http") {
lego, err := legoCmd.New()
2022-06-01 13:35:41 -04:00
if err != nil {
log.Print(err)
}
// Xray-core supports the OcspStapling certification hot renew
2022-06-04 00:05:46 -04:00
_, _, err = lego.RenewCert(c.config.CertConfig.CertDomain, c.config.CertConfig.Email,
c.config.CertConfig.CertMode, c.config.CertConfig.Provider, c.config.CertConfig.DNSEnv)
2022-06-01 13:35:41 -04:00
if err != nil {
log.Print(err)
}
}
2022-06-04 00:05:46 -04:00
// Update User
newUserInfo, err := c.apiClient.GetUserList()
if err != nil {
log.Print(err)
return nil
}
2022-06-01 13:35:41 -04:00
if nodeInfoChanged {
2022-06-09 09:19:57 -04:00
c.userList = newUserInfo
2022-06-05 22:08:02 -04:00
newUserInfo = nil
err = c.addNewUser(c.userList, newNodeInfo)
2022-06-01 13:35:41 -04:00
if err != nil {
log.Print(err)
return nil
}
2022-06-05 01:19:39 -04:00
newNodeInfo = nil
2022-06-04 00:05:46 -04:00
// Add Limiter
2022-06-05 22:08:02 -04:00
if err := c.AddInboundLimiter(c.Tag, c.userList); err != nil {
2022-06-04 00:05:46 -04:00
log.Print(err)
return nil
}
2022-06-05 01:19:39 -04:00
runtime.GC()
2022-06-09 09:19:57 -04:00
} else {
2022-06-01 13:35:41 -04:00
deleted, added := compareUserList(c.userList, newUserInfo)
if len(deleted) > 0 {
deletedEmail := make([]string, len(deleted))
2022-06-02 13:22:56 -04:00
for i := range deleted {
deletedEmail[i] = fmt.Sprintf("%s|%s|%d", c.Tag,
(*c.userList)[deleted[i]].GetUserEmail(),
(*c.userList)[deleted[i]].UID)
2022-06-01 13:35:41 -04:00
}
err := c.removeUsers(deletedEmail, c.Tag)
if err != nil {
log.Print(err)
}
}
if len(added) > 0 {
2022-06-02 13:22:56 -04:00
err = c.addNewUserFromIndex(newUserInfo, &added, c.nodeInfo)
2022-06-01 13:35:41 -04:00
if err != nil {
log.Print(err)
}
// Update Limiter
2022-06-02 13:22:56 -04:00
if err := c.UpdateInboundLimiter(c.Tag, newUserInfo, &added); err != nil {
2022-06-01 13:35:41 -04:00
log.Print(err)
}
}
log.Printf("[%s: %d] %d user deleted, %d user added", c.nodeInfo.NodeType, c.nodeInfo.NodeId,
len(deleted), len(added))
2022-06-04 00:05:46 -04:00
c.userList = newUserInfo
2022-06-05 01:19:39 -04:00
newUserInfo = nil
runtime.GC()
2022-06-01 13:35:41 -04:00
}
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 {
2022-06-02 13:22:56 -04:00
users = c.buildVlessUsers(userInfo)
2022-06-01 13:35:41 -04:00
} else {
alterID := 0
alterID = (*userInfo)[0].V2rayUser.AlterId
if alterID >= 0 && alterID < math.MaxUint16 {
2022-06-02 13:22:56 -04:00
users = c.buildVmessUsers(userInfo, uint16(alterID))
2022-06-01 13:35:41 -04:00
} else {
2022-06-02 13:22:56 -04:00
users = c.buildVmessUsers(userInfo, 0)
2022-06-01 13:35:41 -04:00
return fmt.Errorf("AlterID should between 0 to 1<<16 - 1, set it to 0 for now")
}
}
} else if nodeInfo.NodeType == "Trojan" {
2022-06-02 13:22:56 -04:00
users = c.buildTrojanUsers(userInfo)
2022-06-01 13:35:41 -04:00
} else if nodeInfo.NodeType == "Shadowsocks" {
2022-06-02 13:22:56 -04:00
users = c.buildSSUsers(userInfo, nodeInfo.SS.CypherMethod)
2022-06-01 13:35:41 -04:00
} 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
}
2022-06-02 13:22:56 -04:00
func (c *Controller) addNewUserFromIndex(userInfo *[]api.UserInfo, userIndex *[]int, nodeInfo *api.NodeInfo) (err error) {
users := make([]*protocol.User, 0, len(*userIndex))
for _, v := range *userIndex {
if nodeInfo.NodeType == "V2ray" {
if nodeInfo.EnableVless {
users = append(users, c.buildVlessUser(&(*userInfo)[v]))
} else {
alterID := 0
alterID = (*userInfo)[0].V2rayUser.AlterId
if alterID >= 0 && alterID < math.MaxUint16 {
users = append(users, c.buildVmessUser(&(*userInfo)[v], uint16(alterID)))
} else {
users = append(users, c.buildVmessUser(&(*userInfo)[v], 0))
return fmt.Errorf("AlterID should between 0 to 1<<16 - 1, set it to 0 for now")
}
}
} else if nodeInfo.NodeType == "Trojan" {
users = append(users, c.buildTrojanUser(&(*userInfo)[v]))
} else if nodeInfo.NodeType == "Shadowsocks" {
users = append(users, c.buildSSUser(&(*userInfo)[v], 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(*userIndex))
return nil
}
func compareUserList(old, new *[]api.UserInfo) (deleted, added []int) {
2022-06-09 09:19:57 -04:00
tmp := map[string]struct{}{}
tmp2 := map[string]struct{}{}
2022-06-01 13:35:41 -04:00
for i := range *old {
2022-06-09 09:19:57 -04:00
tmp[(*old)[i].GetUserEmail()] = struct{}{}
2022-06-01 13:35:41 -04:00
}
l := len(tmp)
for i := range *new {
2022-06-09 09:40:23 -04:00
e := (*new)[i].GetUserEmail()
tmp[e] = struct{}{}
tmp2[e] = struct{}{}
2022-06-01 13:35:41 -04:00
if l != len(tmp) {
2022-06-02 13:22:56 -04:00
added = append(added, i)
2022-06-01 13:35:41 -04:00
l++
}
}
2022-06-02 13:22:56 -04:00
tmp = nil
l = len(tmp2)
2022-06-01 13:35:41 -04:00
for i := range *old {
2022-06-09 09:19:57 -04:00
tmp2[(*old)[i].GetUserEmail()] = struct{}{}
2022-06-02 13:22:56 -04:00
if l != len(tmp2) {
deleted = append(deleted, i)
2022-06-01 13:35:41 -04:00
l++
}
}
return deleted, added
}
func (c *Controller) userInfoMonitor() (err error) {
// Get User traffic
userTraffic := make([]api.UserTraffic, 0)
2022-06-05 01:19:39 -04:00
for i := range *c.userList {
up, down := c.getTraffic(c.buildUserTag(&(*c.userList)[i]))
2022-06-01 13:35:41 -04:00
if up > 0 || down > 0 {
userTraffic = append(userTraffic, api.UserTraffic{
2022-06-05 01:19:39 -04:00
UID: (*c.userList)[i].UID,
2022-06-01 13:35:41 -04:00
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))
}
2022-06-05 01:19:39 -04:00
userTraffic = nil
runtime.GC()
2022-06-01 13:35:41 -04:00
return nil
}
func (c *Controller) buildNodeTag() string {
return fmt.Sprintf("%s_%s_%d", c.nodeInfo.NodeType, c.config.ListenIP, c.nodeInfo.NodeId)
}