add support for regenrate config, make parallel call for warp config

This commit is contained in:
Hiddify
2024-02-15 14:47:27 +01:00
parent d72e42cf6a
commit be58cb333f
5 changed files with 86 additions and 130 deletions

View File

@@ -2,7 +2,7 @@ package config
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net" "net"
@@ -13,7 +13,6 @@ import (
C "github.com/sagernet/sing-box/constant" C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/option"
dns "github.com/sagernet/sing-dns" dns "github.com/sagernet/sing-dns"
"github.com/sagernet/sing/common/batch"
) )
const ( const (
@@ -73,10 +72,10 @@ func BuildConfig(opt ConfigOptions, input option.Options) (*option.Options, erro
ClashAPI: &option.ClashAPIOptions{ ClashAPI: &option.ClashAPIOptions{
ExternalController: fmt.Sprintf("%s:%d", "127.0.0.1", opt.ClashApiPort), ExternalController: fmt.Sprintf("%s:%d", "127.0.0.1", opt.ClashApiPort),
}, },
// CacheFile: &option.CacheFileOptions{ CacheFile: &option.CacheFileOptions{
// Enabled: true, Enabled: true,
// Path: "clash.db", Path: "clash.db",
// }, },
} }
} }
@@ -408,10 +407,9 @@ func BuildConfig(opt ConfigOptions, input option.Options) (*option.Options, erro
case C.TypeCustom: case C.TypeCustom:
continue continue
default: default:
if strings.Contains(out.Tag, "§hide§") { if !strings.Contains(out.Tag, "§hide§") {
continue tags = append(tags, out.Tag)
} }
tags = append(tags, out.Tag)
outbounds = append(outbounds, out) outbounds = append(outbounds, out)
} }
} }
@@ -473,26 +471,26 @@ func BuildConfig(opt ConfigOptions, input option.Options) (*option.Options, erro
}..., }...,
) )
if len(directDNSDomains) > 0 { if len(directDNSDomains) > 0 {
trickDnsDomains := []string{} // trickDnsDomains := []string{}
directDNSDomains = removeDuplicateStr(directDNSDomains) // directDNSDomains = removeDuplicateStr(directDNSDomains)
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[bool](10)) // b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[bool](10))
for _, d := range directDNSDomains { // for _, d := range directDNSDomains {
b.Go(d, func() (bool, error) { // b.Go(d, func() (bool, error) {
return isBlockedDomain(d), nil // return isBlockedDomain(d), nil
}) // })
} // }
b.Wait() // b.Wait()
for domain, isBlock := range b.Result() { // for domain, isBlock := range b.Result() {
if isBlock.Value { // if isBlock.Value {
trickDnsDomains = append(trickDnsDomains, domain) // trickDnsDomains = append(trickDnsDomains, domain)
} // }
} // }
trickDomains := strings.Join(trickDnsDomains, ",") // trickDomains := strings.Join(trickDnsDomains, ",")
trickRule := Rule{Domains: trickDomains, Outbound: OutboundBypassTag} // trickRule := Rule{Domains: trickDomains, Outbound: OutboundBypassTag}
trickDnsRule := trickRule.MakeDNSRule() // trickDnsRule := trickRule.MakeDNSRule()
trickDnsRule.Server = DNSTricksDirectTag // trickDnsRule.Server = DNSTricksDirectTag
options.DNS.Rules = append([]option.DNSRule{{Type: C.RuleTypeDefault, DefaultOptions: trickDnsRule}}, options.DNS.Rules...) // options.DNS.Rules = append([]option.DNSRule{{Type: C.RuleTypeDefault, DefaultOptions: trickDnsRule}}, options.DNS.Rules...)
domains := strings.Join(directDNSDomains, ",") domains := strings.Join(directDNSDomains, ",")
directRule := Rule{Domains: domains, Outbound: OutboundBypassTag} directRule := Rule{Domains: domains, Outbound: OutboundBypassTag}

View File

@@ -2,6 +2,7 @@ package config
import ( import (
"bytes" "bytes"
"context"
_ "embed" _ "embed"
"encoding/json" "encoding/json"
"fmt" "fmt"
@@ -12,6 +13,7 @@ import (
"github.com/hiddify/ray2sing/ray2sing" "github.com/hiddify/ray2sing/ray2sing"
"github.com/sagernet/sing-box/experimental/libbox" "github.com/sagernet/sing-box/experimental/libbox"
"github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common/batch"
SJ "github.com/sagernet/sing/common/json" SJ "github.com/sagernet/sing/common/json"
"github.com/xmdhs/clash2singbox/convert" "github.com/xmdhs/clash2singbox/convert"
"github.com/xmdhs/clash2singbox/model/clash" "github.com/xmdhs/clash2singbox/model/clash"
@@ -80,14 +82,26 @@ func patchConfig(content []byte, name string) ([]byte, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("[SingboxParser] unmarshal error: %w", err) return nil, fmt.Errorf("[SingboxParser] unmarshal error: %w", err)
} }
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[*option.Outbound](10))
for i, base := range options.Outbounds { for _, base := range options.Outbounds {
err := patchWarp(&base) out := base
if err != nil { b.Go(base.Tag, func() (*option.Outbound, error) {
return nil, fmt.Errorf("[Warp] patch warp error: %w", err) err := patchWarp(&out)
if err != nil {
return nil, fmt.Errorf("[Warp] patch warp error: %w", err)
}
// options.Outbounds[i] = base
return &out, nil
})
}
if res, err := b.WaitAndGetResult(); err != nil {
return nil, err
} else {
options.Outbounds = []option.Outbound{}
for s := range res {
fmt.Println(s)
options.Outbounds = append(options.Outbounds, *res[s].Value)
} }
options.Outbounds[i] = base
} }
content, _ = json.MarshalIndent(options, "", " ") content, _ = json.MarshalIndent(options, "", " ")

View File

@@ -1,35 +1,15 @@
package config package config
import ( import (
"bufio"
"encoding/json" "encoding/json"
"fmt" "fmt"
"math/rand" "math/rand"
"net/netip" "net/netip"
"os"
"strings"
"github.com/bepass-org/wireguard-go/warp" "github.com/bepass-org/wireguard-go/warp"
T "github.com/sagernet/sing-box/option" T "github.com/sagernet/sing-box/option"
) )
type WireGuardConfig struct {
Interface InterfaceConfig `json:"Interface"`
Peer PeerConfig `json:"Peer"`
}
type InterfaceConfig struct {
PrivateKey string `json:"PrivateKey"`
DNS string `json:"DNS"`
Address []string `json:"Address"`
}
type PeerConfig struct {
PublicKey string `json:"PublicKey"`
AllowedIPs []string `json:"AllowedIPs"`
Endpoint string `json:"Endpoint"`
}
type SingboxConfig struct { type SingboxConfig struct {
Type string `json:"type"` Type string `json:"type"`
Tag string `json:"tag"` Tag string `json:"tag"`
@@ -42,7 +22,7 @@ type SingboxConfig struct {
MTU int `json:"mtu"` MTU int `json:"mtu"`
} }
func wireGuardToSingbox(wgConfig WireGuardConfig, server string, port uint16) (*T.Outbound, error) { func wireGuardToSingbox(wgConfig warp.WireguardConfig, server string, port uint16) (*T.Outbound, error) {
// splt := strings.Split(wgConfig.Peer.Endpoint, ":") // splt := strings.Split(wgConfig.Peer.Endpoint, ":")
// port, err := strconv.Atoi(splt[1]) // port, err := strconv.Atoi(splt[1])
// if err != nil { // if err != nil {
@@ -58,73 +38,26 @@ func wireGuardToSingbox(wgConfig WireGuardConfig, server string, port uint16) (*
ServerPort: port, ServerPort: port,
}, },
PrivateKey: wgConfig.Interface.PrivateKey, PrivateKey: wgConfig.PrivateKey,
PeerPublicKey: wgConfig.Peer.PublicKey, PeerPublicKey: wgConfig.PeerPublicKey,
Reserved: []uint8{0, 0, 0}, Reserved: []uint8{0, 0, 0},
MTU: 1280, MTU: 1280,
}, },
} }
for _, addr := range wgConfig.Interface.Address { ips := []string{wgConfig.LocalAddressIPv4 + "/24", wgConfig.LocalAddressIPv6 + "/128"}
for _, addr := range ips {
if addr == "" {
continue
}
prefix, err := netip.ParsePrefix(addr) prefix, err := netip.ParsePrefix(addr)
if err != nil { if err != nil {
return nil, err // Handle the error appropriately return nil, err // Handle the error appropriately
} }
out.WireGuardOptions.LocalAddress = append(out.WireGuardOptions.LocalAddress, prefix) out.WireGuardOptions.LocalAddress = append(out.WireGuardOptions.LocalAddress, prefix)
} }
return &out, nil return &out, nil
} }
func readWireGuardConfig(filePath string) (WireGuardConfig, error) {
file, err := os.Open(filePath)
if err != nil {
return WireGuardConfig{}, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var wgConfig WireGuardConfig
var currentSection string
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
currentSection = strings.TrimSpace(line[1 : len(line)-1])
continue
}
if currentSection == "Interface" {
parseInterfaceConfig(&wgConfig.Interface, line)
} else if currentSection == "Peer" {
parsePeerConfig(&wgConfig.Peer, line)
}
}
return wgConfig, nil
}
func parseInterfaceConfig(interfaceConfig *InterfaceConfig, line string) {
if strings.HasPrefix(line, "PrivateKey") {
interfaceConfig.PrivateKey = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
} else if strings.HasPrefix(line, "DNS") {
interfaceConfig.DNS = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
} else if strings.HasPrefix(line, "Address") {
interfaceConfig.Address = append(interfaceConfig.Address, strings.TrimSpace(strings.SplitN(line, "=", 2)[1]))
}
}
func parsePeerConfig(peerConfig *PeerConfig, line string) {
if strings.HasPrefix(line, "PublicKey") {
peerConfig.PublicKey = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
} else if strings.HasPrefix(line, "AllowedIPs") {
peerConfig.AllowedIPs = append(peerConfig.AllowedIPs, strings.TrimSpace(strings.SplitN(line, "=", 2)[1]))
} else if strings.HasPrefix(line, "Endpoint") {
peerConfig.Endpoint = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
}
}
var warpIPList = []string{ var warpIPList = []string{
"162.159.192.0/24", "162.159.192.0/24",
@@ -170,26 +103,19 @@ func generateWarp(license string, host string, port uint16, fakePackets string,
fakePacketsDelay = "20-250" fakePacketsDelay = "20-250"
} }
// warp.UpdatePath("./secondary") _, _, wgConfig, err := warp.LoadOrCreateIdentityHiddify(license, nil)
if _, err := os.Stat("./wgcf-identity.json"); err == nil {
os.Remove("./wgcf-identity.json")
}
if !warp.CheckProfileExists(license) {
fmt.Printf("profile s not exit! ---%s---", license)
err := warp.LoadOrCreateIdentity(license)
if err != nil {
return nil, err
}
}
wgConfig, err := readWireGuardConfig("wgcf-profile.ini")
if err != nil { if err != nil {
fmt.Println("Error reading WireGuard configuration:", err)
return nil, err return nil, err
} }
// fmt.Printf("%v", wgConfig) if wgConfig == nil {
singboxConfig, err := wireGuardToSingbox(wgConfig, host, port) return nil, fmt.Errorf("invalid warp config")
}
fmt.Printf("%v", wgConfig)
singboxConfig, err := wireGuardToSingbox(*wgConfig, host, port)
if err != nil {
fmt.Printf("%v %v", singboxConfig, err)
return nil, err
}
singboxConfig.WireGuardOptions.FakePackets = fakePackets singboxConfig.WireGuardOptions.FakePackets = fakePackets
singboxConfig.WireGuardOptions.FakePacketsSize = fakePacketsSize singboxConfig.WireGuardOptions.FakePacketsSize = fakePacketsSize
@@ -203,3 +129,21 @@ func generateWarp(license string, host string, port uint16, fakePackets string,
fmt.Println(string(singboxJSON)) fmt.Println(string(singboxJSON))
return singboxConfig, nil return singboxConfig, nil
} }
func GenerateWarpInfo(license string, oldAccountId string, oldAccessToken string) (*warp.AccountData, string, *warp.WireguardConfig, error) {
if oldAccountId != "" && oldAccessToken != "" {
accountData := warp.AccountData{
AccountID: oldAccountId,
AccessToken: oldAccessToken,
}
err := warp.RemoveDevice(accountData)
if err != nil {
fmt.Printf("Error in removing old device: %v\n", err)
} else {
fmt.Printf("Old Device Removed")
}
}
return warp.LoadOrCreateIdentityHiddify(license, nil)
}

2
go.mod
View File

@@ -109,4 +109,4 @@ replace github.com/sagernet/sing-box => github.com/hiddify/hiddify-sing-box v1.8
replace github.com/sagernet/wireguard-go => github.com/hiddify/wireguard-go v0.0.0-20240214142457-fadc619f4357 replace github.com/sagernet/wireguard-go => github.com/hiddify/wireguard-go v0.0.0-20240214142457-fadc619f4357
replace github.com/bepass-org/wireguard-go => github.com/hiddify-com/wireguard-go v0.0.2-alpha.0.20240212065415-62301f758cb7 replace github.com/bepass-org/wireguard-go => github.com/hiddify-com/wireguard-go v0.0.2-alpha.0.20240215114454-3acea56c88fc

4
go.sum
View File

@@ -51,8 +51,8 @@ github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a h1:fEBsGL/sjAuJrgah5X
github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik=
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE= github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ= github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
github.com/hiddify-com/wireguard-go v0.0.2-alpha.0.20240212065415-62301f758cb7 h1:RTlGYawrP2Ir2ADQmLS7+OmRShmk1qPm69ufArXvsqI= github.com/hiddify-com/wireguard-go v0.0.2-alpha.0.20240215114454-3acea56c88fc h1:7Nbu6wraBxlYZzBCcacGwMP8iv1cxbToFRLDeZgajdo=
github.com/hiddify-com/wireguard-go v0.0.2-alpha.0.20240212065415-62301f758cb7/go.mod h1:/ny1FvyrV7/QPClexDyYCEFQfTQn7dD/+1DfedBSwuY= github.com/hiddify-com/wireguard-go v0.0.2-alpha.0.20240215114454-3acea56c88fc/go.mod h1:E1qZQpw2IrbRtFpTloTHGfJ2bJc4ZpZRNS497Eq5jCo=
github.com/hiddify/hiddify-sing-box v1.8.6-0.20240214144108-11fb33cac74a h1:QoA1CZRVuq9C6BpOgZHzzqiX7JoEBBoRqjLlpXGLUP4= github.com/hiddify/hiddify-sing-box v1.8.6-0.20240214144108-11fb33cac74a h1:QoA1CZRVuq9C6BpOgZHzzqiX7JoEBBoRqjLlpXGLUP4=
github.com/hiddify/hiddify-sing-box v1.8.6-0.20240214144108-11fb33cac74a/go.mod h1:usnCk4Fbp/3HAJ+b7LnogPP7x4En2Kc4ujNlnDsi1Sc= github.com/hiddify/hiddify-sing-box v1.8.6-0.20240214144108-11fb33cac74a/go.mod h1:usnCk4Fbp/3HAJ+b7LnogPP7x4En2Kc4ujNlnDsi1Sc=
github.com/hiddify/ray2sing v0.0.0-20240213091709-ba1d827e4f4a h1:ObxmZ8AyhIxtH2Vu+vmDAsxsbsTPGq9pJzcY0V+3BCU= github.com/hiddify/ray2sing v0.0.0-20240213091709-ba1d827e4f4a h1:ObxmZ8AyhIxtH2Vu+vmDAsxsbsTPGq9pJzcY0V+3BCU=