update to v1.1.0

change to uniproxy api
refactor build inbound
refactor limiter and rule
add ss2022 support
add speedlimit support
and more...
This commit is contained in:
Yuzuki999
2022-12-18 23:31:06 +08:00
parent 0ac7ea691d
commit 695da4f4c5
23 changed files with 539 additions and 652 deletions

View File

@@ -5,6 +5,5 @@ type Panel interface {
GetUserList() (userList []UserInfo, err error)
ReportUserTraffic(userTraffic []UserTraffic) (err error)
Describe() ClientInfo
GetNodeRule() (ruleList *DetectRule, err error)
Debug()
}

View File

@@ -1,266 +1,82 @@
package panel
import (
"bufio"
"bytes"
md52 "crypto/md5"
"fmt"
"github.com/go-resty/resty/v2"
"github.com/goccy/go-json"
"github.com/xtls/xray-core/infra/conf"
"log"
"os"
"regexp"
"strconv"
)
type DetectRule struct {
ProtocolRule []string
DestinationRule []DestinationRule
type NodeInfo struct {
Host string `json:"host"`
ServerPort int `json:"server_port"`
ServerName string `json:"server_name"`
Network string `json:"network"`
NetworkSettings json.RawMessage `json:"networkSettings"`
Cipher string `json:"cipher"`
ServerKey string `json:"server_key"`
Tls int `json:"tls"`
Routes []Route `json:"routes"`
BaseConfig *BaseConfig `json:"base_config"`
Rules []DestinationRule `json:"-"`
localNodeConfig `json:"-"`
}
type Route struct {
Id int `json:"id"`
Match string `json:"match"`
Action string `json:"action"`
//ActionValue interface{} `json:"action_value"`
}
type BaseConfig struct {
PushInterval any `json:"push_interval"`
PullInterval any `json:"pull_interval"`
}
type DestinationRule struct {
ID int
Pattern *regexp.Regexp
}
// readLocalRuleList reads the local rule list file
func readLocalRuleList(path string) (LocalRuleList *DetectRule) {
LocalRuleList = &DetectRule{}
if path != "" {
// open the file
file, err := os.Open(path)
//handle errors while opening
if err != nil {
log.Printf("Error when opening file: %s", err)
return
}
fileScanner := bufio.NewScanner(file)
// read line by line
for fileScanner.Scan() {
LocalRuleList.DestinationRule = append(LocalRuleList.DestinationRule, DestinationRule{
ID: -1,
Pattern: regexp.MustCompile(fileScanner.Text()),
})
}
// handle first encountered error while reading
if err := fileScanner.Err(); err != nil {
log.Fatalf("Error while reading file: %s", err)
return
}
}
return
}
type NodeInfo struct {
DeviceLimit int
SpeedLimit uint64
NodeType string
type localNodeConfig struct {
NodeId int
NodeType string
TLSType string
EnableVless bool
EnableTls bool
//EnableSS2022 bool
V2ray *V2rayConfig
Trojan *TrojanConfig
SS *SSConfig
SpeedLimit int
DeviceLimit int
}
type SSConfig struct {
Port int `json:"port"`
TransportProtocol string `json:"transportProtocol"`
CypherMethod string `json:"cypher"`
}
type V2rayConfig struct {
Inbounds []conf.InboundDetourConfig `json:"inbounds"`
Routing *struct {
Rules json.RawMessage `json:"rules"`
} `json:"routing"`
}
type Rule struct {
Type string `json:"type"`
InboundTag string `json:"inboundTag,omitempty"`
OutboundTag string `json:"outboundTag"`
Domain []string `json:"domain,omitempty"`
Protocol []string `json:"protocol,omitempty"`
}
type TrojanConfig struct {
LocalPort int `json:"local_port"`
Password []interface{} `json:"password"`
TransportProtocol string
Ssl struct {
Sni string `json:"sni"`
} `json:"ssl"`
}
// GetNodeInfo will pull NodeInfo Config from v2board
func (c *Client) GetNodeInfo() (nodeInfo *NodeInfo, err error) {
var path string
var res *resty.Response
switch c.NodeType {
case "V2ray":
path = "/api/v1/server/Deepbwork/config"
case "Trojan":
path = "/api/v1/server/TrojanTidalab/config"
case "Shadowsocks":
if nodeInfo, err = c.ParseSSNodeResponse(); err == nil {
return nodeInfo, nil
} else {
return nil, err
}
default:
return nil, fmt.Errorf("unsupported Node type: %s", c.NodeType)
const path = "/api/v1/server/UniProxy/config"
r, err := c.client.R().Get(path)
if err = c.checkResponse(r, path, err); err != nil {
return
}
res, err = c.client.R().
SetQueryParam("local_port", "1").
ForceContentType("application/json").
Get(path)
err = c.checkResponse(res, path, err)
err = json.Unmarshal(r.Body(), &nodeInfo)
if err != nil {
return nil, err
return
}
c.access.Lock()
defer c.access.Unlock()
switch c.NodeType {
case "V2ray":
i := bytes.Index(res.Body(), []byte("outbo"))
md := md52.Sum(res.Body()[:i])
nodeNotIsChange := true
if c.NodeInfoRspMd5 == [16]byte{} {
nodeNotIsChange = false
c.NodeInfoRspMd5 = md
} else {
if c.NodeInfoRspMd5 != md {
nodeNotIsChange = false
c.NodeInfoRspMd5 = md
}
}
md2 := md52.Sum(res.Body()[i:])
ruleIsChange := false
if c.NodeRuleRspMd5 != md2 {
ruleIsChange = true
c.NodeRuleRspMd5 = md2
}
nodeInfo, err = c.ParseV2rayNodeResponse(res.Body(), nodeNotIsChange, ruleIsChange)
case "Trojan":
md := md52.Sum(res.Body())
if c.NodeInfoRspMd5 != [16]byte{} {
if c.NodeInfoRspMd5 == md {
return nil, nil
}
}
c.NodeInfoRspMd5 = md
nodeInfo, err = c.ParseTrojanNodeResponse(res.Body())
}
return nodeInfo, nil
}
func (c *Client) GetNodeRule() (*DetectRule, error) {
ruleList := c.LocalRuleList
if c.NodeType != "V2ray" || c.RemoteRuleCache == nil {
if c.etag == r.Header().Get("ETag") { // node info not changed
return nil, nil
}
// V2board only support the rule for v2ray
// fix: reuse config response
c.access.Lock()
defer c.access.Unlock()
if len(c.RemoteRuleCache) >= 2 {
for i, rule := range (c.RemoteRuleCache)[1].Domain {
ruleListItem := DestinationRule{
ID: i,
Pattern: regexp.MustCompile(rule),
}
ruleList.DestinationRule = append(ruleList.DestinationRule, ruleListItem)
nodeInfo.NodeId = c.NodeId
nodeInfo.NodeType = c.NodeType
for i := range nodeInfo.Routes { // parse rules from routes
r := &nodeInfo.Routes[i]
if r.Action == "block" {
nodeInfo.Rules = append(nodeInfo.Rules, DestinationRule{
ID: r.Id,
Pattern: regexp.MustCompile(r.Match),
})
}
}
if len(c.RemoteRuleCache) >= 3 {
for _, str := range (c.RemoteRuleCache)[2].Protocol {
ruleList.ProtocolRule = append(ruleList.ProtocolRule, str)
}
nodeInfo.Routes = nil
if _, ok := nodeInfo.BaseConfig.PullInterval.(int); !ok {
i, _ := strconv.Atoi(nodeInfo.BaseConfig.PullInterval.(string))
nodeInfo.BaseConfig.PullInterval = i
}
c.RemoteRuleCache = nil
return ruleList, nil
}
// ParseTrojanNodeResponse parse the response for the given node info format
func (c *Client) ParseTrojanNodeResponse(body []byte) (*NodeInfo, error) {
node := &NodeInfo{Trojan: &TrojanConfig{}}
var err = json.Unmarshal(body, node.Trojan)
if err != nil {
return nil, fmt.Errorf("unmarshal nodeinfo error: %s", err)
}
node.SpeedLimit = uint64(c.SpeedLimit * 1000000 / 8)
node.DeviceLimit = c.DeviceLimit
node.NodeId = c.NodeID
node.NodeType = c.NodeType
node.Trojan.TransportProtocol = "tcp"
return node, nil
}
// ParseSSNodeResponse parse the response for the given node info format
func (c *Client) ParseSSNodeResponse() (*NodeInfo, error) {
var port int
var method string
userInfo, err := c.GetUserList()
if err != nil {
return nil, err
}
if len(userInfo) > 0 {
port = userInfo[0].Port
method = userInfo[0].Cipher
} else {
return nil, fmt.Errorf("shadowsocks node need a active user")
}
if err != nil {
return nil, err
}
node := &NodeInfo{
SpeedLimit: uint64(c.SpeedLimit * 1000000 / 8),
DeviceLimit: c.DeviceLimit,
//EnableSS2022: c.EnableSS2022,
NodeType: c.NodeType,
NodeId: c.NodeID,
SS: &SSConfig{
Port: port,
TransportProtocol: "tcp",
CypherMethod: method,
},
}
return node, nil
}
// ParseV2rayNodeResponse parse the response for the given nodeinfor format
func (c *Client) ParseV2rayNodeResponse(body []byte, notParseNode, parseRule bool) (*NodeInfo, error) {
if notParseNode && !parseRule {
return nil, nil
}
node := &NodeInfo{V2ray: &V2rayConfig{}}
err := json.Unmarshal(body, node.V2ray)
if err != nil {
return nil, fmt.Errorf("unmarshal nodeinfo error: %s", err)
}
if parseRule {
c.RemoteRuleCache = []Rule{}
err := json.Unmarshal(node.V2ray.Routing.Rules, &c.RemoteRuleCache)
if err != nil {
log.Println(err)
}
if notParseNode {
return nil, nil
}
}
node.V2ray.Routing = nil
node.SpeedLimit = uint64(c.SpeedLimit * 1000000 / 8)
node.DeviceLimit = c.DeviceLimit
node.NodeType = c.NodeType
node.NodeId = c.NodeID
if c.EnableXTLS {
node.TLSType = "xtls"
} else {
node.TLSType = "tls"
}
node.EnableVless = c.EnableVless
node.EnableTls = node.V2ray.Inbounds[0].StreamSetting.Security == "tls"
return node, nil
if _, ok := nodeInfo.BaseConfig.PushInterval.(int); !ok {
i, _ := strconv.Atoi(nodeInfo.BaseConfig.PushInterval.(string))
nodeInfo.BaseConfig.PushInterval = i
}
c.etag = r.Header().Get("Etag")
return
}

20
api/panel/node_test.go Normal file
View File

@@ -0,0 +1,20 @@
package panel
import (
"github.com/Yuzuki616/V2bX/conf"
"github.com/Yuzuki616/V2bX/node/controller/legoCmd/log"
"testing"
)
func TestClient_GetNodeInfo(t *testing.T) {
c, err := New(&conf.ApiConfig{
APIHost: "http://127.0.0.1",
Key: "token",
NodeType: "V2ray",
NodeID: 1,
})
if err != nil {
log.Print(err)
}
log.Println(c.GetNodeInfo())
}

View File

@@ -1,11 +1,15 @@
package panel
import (
"bufio"
"fmt"
"github.com/Yuzuki616/V2bX/conf"
"github.com/go-resty/resty/v2"
"log"
"os"
"regexp"
"strconv"
"sync"
"strings"
"time"
)
@@ -19,28 +23,22 @@ type ClientInfo struct {
}
type Client struct {
client *resty.Client
APIHost string
NodeID int
Key string
NodeType string
//EnableSS2022 bool
EnableVless bool
EnableXTLS bool
SpeedLimit float64
DeviceLimit int
LocalRuleList *DetectRule
RemoteRuleCache []Rule
access sync.Mutex
NodeInfoRspMd5 [16]byte
NodeRuleRspMd5 [16]byte
client *resty.Client
APIHost string
Key string
NodeType string
NodeId int
SpeedLimit int
DeviceLimit int
LocalRuleList []DestinationRule
etag string
}
func New(apiConfig *conf.ApiConfig) Panel {
func New(c *conf.ApiConfig) (Panel, error) {
client := resty.New()
client.SetRetryCount(3)
if apiConfig.Timeout > 0 {
client.SetTimeout(time.Duration(apiConfig.Timeout) * time.Second)
if c.Timeout > 0 {
client.SetTimeout(time.Duration(c.Timeout) * time.Second)
} else {
client.SetTimeout(5 * time.Second)
}
@@ -51,25 +49,57 @@ func New(apiConfig *conf.ApiConfig) Panel {
log.Print(v.Err)
}
})
client.SetBaseURL(apiConfig.APIHost)
client.SetBaseURL(c.APIHost)
// Check node type
if c.NodeType != "V2ray" &&
c.NodeType != "Trojan" &&
c.NodeType != "Shadowsocks" {
return nil, fmt.Errorf("unsupported Node type: %s", c.NodeType)
}
// Create Key for each requests
client.SetQueryParams(map[string]string{
"node_id": strconv.Itoa(apiConfig.NodeID),
"token": apiConfig.Key,
"node_type": strings.ToLower(c.NodeType),
"node_id": strconv.Itoa(c.NodeID),
"token": c.Key,
})
// Read local rule list
localRuleList := readLocalRuleList(apiConfig.RuleListPath)
localRuleList := readLocalRuleList(c.RuleListPath)
return &Client{
client: client,
NodeID: apiConfig.NodeID,
Key: apiConfig.Key,
APIHost: apiConfig.APIHost,
NodeType: apiConfig.NodeType,
//EnableSS2022: apiConfig.EnableSS2022,
EnableVless: apiConfig.EnableVless,
EnableXTLS: apiConfig.EnableXTLS,
SpeedLimit: apiConfig.SpeedLimit,
DeviceLimit: apiConfig.DeviceLimit,
client: client,
Key: c.Key,
APIHost: c.APIHost,
NodeType: c.NodeType,
SpeedLimit: c.SpeedLimit,
DeviceLimit: c.DeviceLimit,
NodeId: c.NodeID,
LocalRuleList: localRuleList,
}
}, nil
}
// readLocalRuleList reads the local rule list file
func readLocalRuleList(path string) (LocalRuleList []DestinationRule) {
LocalRuleList = make([]DestinationRule, 0)
if path != "" {
// open the file
file, err := os.Open(path)
//handle errors while opening
if err != nil {
log.Printf("Error when opening file: %s", err)
return
}
fileScanner := bufio.NewScanner(file)
// read line by line
for fileScanner.Scan() {
LocalRuleList = append(LocalRuleList, DestinationRule{
ID: -1,
Pattern: regexp.MustCompile(fileScanner.Text()),
})
}
// handle first encountered error while reading
if err := fileScanner.Err(); err != nil {
log.Fatalf("Error while reading file: %s", err)
return
}
}
return
}

View File

@@ -3,7 +3,6 @@ package panel
import (
"fmt"
"github.com/goccy/go-json"
"strconv"
)
type OnlineUser struct {
@@ -20,46 +19,22 @@ type TrojanUserInfo struct {
Password string `json:"password"`
}
type UserInfo struct {
/*DeviceLimit int `json:"device_limit"`
SpeedLimit uint64 `json:"speed_limit"`*/
UID int `json:"id"`
Traffic int64 `json:"-"`
Port int `json:"port"`
Cipher string `json:"cipher"`
Secret string `json:"secret"`
V2rayUser *V2RayUserInfo `json:"v2ray_user"`
TrojanUser *TrojanUserInfo `json:"trojan_user"`
}
func (p *UserInfo) GetUserEmail() string {
if p.V2rayUser != nil {
return p.V2rayUser.Email
} else if p.TrojanUser != nil {
return p.TrojanUser.Password
}
return p.Secret
Id int `json:"id"`
Uuid string `json:"uuid"`
Email string `json:"-"`
SpeedLimit int `json:"speed_limit"`
Traffic int64 `json:"-"`
}
type UserListBody struct {
//Msg string `json:"msg"`
Data []UserInfo `json:"data"`
Users []UserInfo `json:"users"`
}
// GetUserList will pull user form sspanel
func (c *Client) GetUserList() (UserList []UserInfo, err error) {
var path string
switch c.NodeType {
case "V2ray":
path = "/api/v1/server/Deepbwork/user"
case "Trojan":
path = "/api/v1/server/TrojanTidalab/user"
case "Shadowsocks":
path = "/api/v1/server/ShadowsocksTidalab/user"
default:
return nil, fmt.Errorf("unsupported Node type: %s", c.NodeType)
}
const path = "/api/v1/server/UniProxy/user"
res, err := c.client.R().
ForceContentType("application/json").
Get(path)
err = c.checkResponse(res, path, err)
if err != nil {
@@ -70,38 +45,24 @@ func (c *Client) GetUserList() (UserList []UserInfo, err error) {
if err != nil {
return nil, fmt.Errorf("unmarshal userlist error: %s", err)
}
return userList.Data, nil
return userList.Users, nil
}
type UserTraffic struct {
UID int `json:"user_id"`
Upload int64 `json:"u"`
Download int64 `json:"d"`
UID int
Upload int64
Download int64
}
// ReportUserTraffic reports the user traffic
func (c *Client) ReportUserTraffic(userTraffic []UserTraffic) error {
var path string
switch c.NodeType {
case "V2ray":
path = "/api/v1/server/Deepbwork/submit"
case "Trojan":
path = "/api/v1/server/TrojanTidalab/submit"
case "Shadowsocks":
path = "/api/v1/server/ShadowsocksTidalab/submit"
data := make(map[int][]int64, len(userTraffic))
for i := range userTraffic {
data[userTraffic[i].UID] = []int64{userTraffic[i].Upload, userTraffic[i].Download}
}
data := make([]UserTraffic, len(userTraffic))
for i, traffic := range userTraffic {
data[i] = UserTraffic{
UID: traffic.UID,
Upload: traffic.Upload,
Download: traffic.Download}
}
const path = "/api/v1/server/UniProxy/user"
res, err := c.client.R().
SetQueryParam("node_id", strconv.Itoa(c.NodeID)).
SetBody(data).
SetBody(userTraffic).
ForceContentType("application/json").
Post(path)
err = c.checkResponse(res, path, err)

View File

@@ -3,11 +3,12 @@ package panel
import (
"fmt"
"github.com/go-resty/resty/v2"
path2 "path"
)
// Describe return a description of the client
func (c *Client) Describe() ClientInfo {
return ClientInfo{APIHost: c.APIHost, NodeID: c.NodeID, Key: c.Key, NodeType: c.NodeType}
return ClientInfo{APIHost: c.APIHost, NodeID: c.NodeId, Key: c.Key, NodeType: c.NodeType}
}
// Debug set the client debug for client
@@ -16,13 +17,12 @@ func (c *Client) Debug() {
}
func (c *Client) assembleURL(path string) string {
return c.APIHost + path
return path2.Join(c.APIHost + path)
}
func (c *Client) checkResponse(res *resty.Response, path string, err error) error {
if err != nil {
return fmt.Errorf("request %s failed: %s", c.assembleURL(path), err)
}
if res.StatusCode() > 400 {
body := res.Body()
return fmt.Errorf("request %s failed: %s, %s", c.assembleURL(path), string(body), err)