repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_darwin.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_darwin.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build !ios && darwin package goos const GOOS = `darwin` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 1 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/internal/update_apple_version/main.go
Bcore/windows/resources/sing-box-main/cmd/internal/update_apple_version/main.go
package main import ( "os" "path/filepath" "regexp" "strings" "github.com/sagernet/sing-box/cmd/internal/build_shared" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/common" "howett.net/plist" ) func main() { newVersion := common.Must1(build_shared.ReadTagVersion()) applePath, err := filepath.Abs("../sing-box-for-apple") if err != nil { log.Fatal(err) } common.Must(os.Chdir(applePath)) projectFile := common.Must1(os.Open("sing-box.xcodeproj/project.pbxproj")) var project map[string]any decoder := plist.NewDecoder(projectFile) common.Must(decoder.Decode(&project)) objectsMap := project["objects"].(map[string]any) projectContent := string(common.Must1(os.ReadFile("sing-box.xcodeproj/project.pbxproj"))) newContent, updated0 := findAndReplace(objectsMap, projectContent, []string{"io.nekohasekai.sfavt"}, newVersion.VersionString()) newContent, updated1 := findAndReplace(objectsMap, newContent, []string{"io.nekohasekai.sfavt.standalone", "io.nekohasekai.sfavt.system"}, newVersion.String()) if updated0 || updated1 { log.Info("updated version to ", newVersion.VersionString(), " (", newVersion.String(), ")") } var updated2 bool if macProjectVersion := os.Getenv("MACOS_PROJECT_VERSION"); macProjectVersion != "" { newContent, updated2 = findAndReplaceProjectVersion(objectsMap, newContent, []string{"SFM"}, macProjectVersion) if updated2 { log.Info("updated macos project version to ", macProjectVersion) } } if updated0 || updated1 || updated2 { common.Must(os.WriteFile("sing-box.xcodeproj/project.pbxproj", []byte(newContent), 0o644)) } } func findAndReplace(objectsMap map[string]any, projectContent string, bundleIDList []string, newVersion string) (string, bool) { objectKeyList := findObjectKey(objectsMap, bundleIDList) var updated bool for _, objectKey := range objectKeyList { matchRegexp := common.Must1(regexp.Compile(objectKey + ".*= \\{")) indexes := matchRegexp.FindStringIndex(projectContent) if len(indexes) < 2 { println(projectContent) log.Fatal("failed to find object key ", objectKey, ": ", strings.Index(projectContent, objectKey)) } indexStart := indexes[1] indexEnd := indexStart + strings.Index(projectContent[indexStart:], "}") versionStart := indexStart + strings.Index(projectContent[indexStart:indexEnd], "MARKETING_VERSION = ") + 20 versionEnd := versionStart + strings.Index(projectContent[versionStart:indexEnd], ";") version := projectContent[versionStart:versionEnd] if version == newVersion { continue } updated = true projectContent = projectContent[:versionStart] + newVersion + projectContent[versionEnd:] } return projectContent, updated } func findAndReplaceProjectVersion(objectsMap map[string]any, projectContent string, directoryList []string, newVersion string) (string, bool) { objectKeyList := findObjectKeyByDirectory(objectsMap, directoryList) var updated bool for _, objectKey := range objectKeyList { matchRegexp := common.Must1(regexp.Compile(objectKey + ".*= \\{")) indexes := matchRegexp.FindStringIndex(projectContent) if len(indexes) < 2 { println(projectContent) log.Fatal("failed to find object key ", objectKey, ": ", strings.Index(projectContent, objectKey)) } indexStart := indexes[1] indexEnd := indexStart + strings.Index(projectContent[indexStart:], "}") versionStart := indexStart + strings.Index(projectContent[indexStart:indexEnd], "CURRENT_PROJECT_VERSION = ") + 26 versionEnd := versionStart + strings.Index(projectContent[versionStart:indexEnd], ";") version := projectContent[versionStart:versionEnd] if version == newVersion { continue } updated = true projectContent = projectContent[:versionStart] + newVersion + projectContent[versionEnd:] } return projectContent, updated } func findObjectKey(objectsMap map[string]any, bundleIDList []string) []string { var objectKeyList []string for objectKey, object := range objectsMap { buildSettings := object.(map[string]any)["buildSettings"] if buildSettings == nil { continue } bundleIDObject := buildSettings.(map[string]any)["PRODUCT_BUNDLE_IDENTIFIER"] if bundleIDObject == nil { continue } if common.Contains(bundleIDList, bundleIDObject.(string)) { objectKeyList = append(objectKeyList, objectKey) } } return objectKeyList } func findObjectKeyByDirectory(objectsMap map[string]any, directoryList []string) []string { var objectKeyList []string for objectKey, object := range objectsMap { buildSettings := object.(map[string]any)["buildSettings"] if buildSettings == nil { continue } infoPListFile := buildSettings.(map[string]any)["INFOPLIST_FILE"] if infoPListFile == nil { continue } for _, searchDirectory := range directoryList { if strings.HasPrefix(infoPListFile.(string), searchDirectory+"/") { objectKeyList = append(objectKeyList, objectKey) } } } return objectKeyList }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/internal/update_android_version/main.go
Bcore/windows/resources/sing-box-main/cmd/internal/update_android_version/main.go
package main import ( "os" "path/filepath" "runtime" "strconv" "strings" "github.com/sagernet/sing-box/cmd/internal/build_shared" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/common" ) func main() { newVersion := common.Must1(build_shared.ReadTagVersion()) androidPath, err := filepath.Abs("../sing-box-for-android") if err != nil { log.Fatal(err) } common.Must(os.Chdir(androidPath)) localProps := common.Must1(os.ReadFile("version.properties")) var propsList [][]string for _, propLine := range strings.Split(string(localProps), "\n") { propsList = append(propsList, strings.Split(propLine, "=")) } var ( versionUpdated bool goVersionUpdated bool ) for _, propPair := range propsList { switch propPair[0] { case "VERSION_NAME": if propPair[1] != newVersion.String() { versionUpdated = true propPair[1] = newVersion.String() log.Info("updated version to ", newVersion.String()) } case "GO_VERSION": if propPair[1] != runtime.Version() { goVersionUpdated = true propPair[1] = runtime.Version() log.Info("updated Go version to ", runtime.Version()) } } } if !(versionUpdated || goVersionUpdated) { log.Info("version not changed") return } for _, propPair := range propsList { switch propPair[0] { case "VERSION_CODE": versionCode := common.Must1(strconv.ParseInt(propPair[1], 10, 64)) propPair[1] = strconv.Itoa(int(versionCode + 1)) log.Info("updated version code to ", propPair[1]) } } var newProps []string for _, propPair := range propsList { newProps = append(newProps, strings.Join(propPair, "=")) } common.Must(os.WriteFile("version.properties", []byte(strings.Join(newProps, "\n")), 0o644)) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/internal/build_shared/sdk.go
Bcore/windows/resources/sing-box-main/cmd/internal/build_shared/sdk.go
package build_shared import ( "go/build" "os" "path/filepath" "runtime" "sort" "strconv" "strings" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/rw" "github.com/sagernet/sing/common/shell" ) var ( androidSDKPath string androidNDKPath string ) func FindSDK() { searchPath := []string{ "$ANDROID_HOME", "$HOME/Android/Sdk", "$HOME/.local/lib/android/sdk", "$HOME/Library/Android/sdk", } for _, path := range searchPath { path = os.ExpandEnv(path) if rw.IsFile(filepath.Join(path, "licenses", "android-sdk-license")) { androidSDKPath = path break } } if androidSDKPath == "" { log.Fatal("android SDK not found") } if !findNDK() { log.Fatal("android NDK not found") } javaVersion, err := shell.Exec("java", "--version").ReadOutput() if err != nil { log.Fatal(E.Cause(err, "check java version")) } if !strings.Contains(javaVersion, "openjdk 17") { log.Fatal("java version should be openjdk 17") } os.Setenv("ANDROID_HOME", androidSDKPath) os.Setenv("ANDROID_SDK_HOME", androidSDKPath) os.Setenv("ANDROID_NDK_HOME", androidNDKPath) os.Setenv("NDK", androidNDKPath) os.Setenv("PATH", os.Getenv("PATH")+":"+filepath.Join(androidNDKPath, "toolchains", "llvm", "prebuilt", runtime.GOOS+"-x86_64", "bin")) } func findNDK() bool { const fixedVersion = "26.2.11394342" const versionFile = "source.properties" if fixedPath := filepath.Join(androidSDKPath, "ndk", fixedVersion); rw.IsFile(filepath.Join(fixedPath, versionFile)) { androidNDKPath = fixedPath return true } ndkVersions, err := os.ReadDir(filepath.Join(androidSDKPath, "ndk")) if err != nil { return false } versionNames := common.Map(ndkVersions, os.DirEntry.Name) if len(versionNames) == 0 { return false } sort.Slice(versionNames, func(i, j int) bool { iVersions := strings.Split(versionNames[i], ".") jVersions := strings.Split(versionNames[j], ".") for k := 0; k < len(iVersions) && k < len(jVersions); k++ { iVersion, _ := strconv.Atoi(iVersions[k]) jVersion, _ := strconv.Atoi(jVersions[k]) if iVersion != jVersion { return iVersion > jVersion } } return true }) for _, versionName := range versionNames { currentNDKPath := filepath.Join(androidSDKPath, "ndk", versionName) if rw.IsFile(filepath.Join(currentNDKPath, versionFile)) { androidNDKPath = currentNDKPath log.Warn("reproducibility warning: using NDK version " + versionName + " instead of " + fixedVersion) return true } } return false } var GoBinPath string func FindMobile() { goBin := filepath.Join(build.Default.GOPATH, "bin") if runtime.GOOS == "windows" { if !rw.IsFile(filepath.Join(goBin, "gobind.exe")) { log.Fatal("missing gomobile installation") } } else { if !rw.IsFile(filepath.Join(goBin, "gobind")) { log.Fatal("missing gomobile installation") } } GoBinPath = goBin }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/internal/build_shared/tag.go
Bcore/windows/resources/sing-box-main/cmd/internal/build_shared/tag.go
package build_shared import ( "github.com/sagernet/sing-box/common/badversion" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/shell" ) func ReadTag() (string, error) { currentTag, err := shell.Exec("git", "describe", "--tags").ReadOutput() if err != nil { return currentTag, err } currentTagRev, _ := shell.Exec("git", "describe", "--tags", "--abbrev=0").ReadOutput() if currentTagRev == currentTag { return currentTag[1:], nil } shortCommit, _ := shell.Exec("git", "rev-parse", "--short", "HEAD").ReadOutput() version := badversion.Parse(currentTagRev[1:]) return version.String() + "-" + shortCommit, nil } func ReadTagVersion() (badversion.Version, error) { currentTag := common.Must1(shell.Exec("git", "describe", "--tags").ReadOutput()) currentTagRev := common.Must1(shell.Exec("git", "describe", "--tags", "--abbrev=0").ReadOutput()) version := badversion.Parse(currentTagRev[1:]) if currentTagRev != currentTag { if version.PreReleaseIdentifier == "" { version.Patch++ } } return version, nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/internal/protogen/main.go
Bcore/windows/resources/sing-box-main/cmd/internal/protogen/main.go
package main import ( "bufio" "bytes" "fmt" "go/build" "io" "os" "os/exec" "path/filepath" "runtime" "strings" ) // envFile returns the name of the Go environment configuration file. // Copy from https://github.com/golang/go/blob/c4f2a9788a7be04daf931ac54382fbe2cb754938/src/cmd/go/internal/cfg/cfg.go#L150-L166 func envFile() (string, error) { if file := os.Getenv("GOENV"); file != "" { if file == "off" { return "", fmt.Errorf("GOENV=off") } return file, nil } dir, err := os.UserConfigDir() if err != nil { return "", err } if dir == "" { return "", fmt.Errorf("missing user-config dir") } return filepath.Join(dir, "go", "env"), nil } // GetRuntimeEnv returns the value of runtime environment variable, // that is set by running following command: `go env -w key=value`. func GetRuntimeEnv(key string) (string, error) { file, err := envFile() if err != nil { return "", err } if file == "" { return "", fmt.Errorf("missing runtime env file") } var data []byte var runtimeEnv string data, readErr := os.ReadFile(file) if readErr != nil { return "", readErr } envStrings := strings.Split(string(data), "\n") for _, envItem := range envStrings { envItem = strings.TrimSuffix(envItem, "\r") envKeyValue := strings.Split(envItem, "=") if strings.EqualFold(strings.TrimSpace(envKeyValue[0]), key) { runtimeEnv = strings.TrimSpace(envKeyValue[1]) } } return runtimeEnv, nil } // GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty. func GetGOBIN() string { // The one set by user explicitly by `export GOBIN=/path` or `env GOBIN=/path command` GOBIN := os.Getenv("GOBIN") if GOBIN == "" { var err error // The one set by user by running `go env -w GOBIN=/path` GOBIN, err = GetRuntimeEnv("GOBIN") if err != nil { // The default one that Golang uses return filepath.Join(build.Default.GOPATH, "bin") } if GOBIN == "" { return filepath.Join(build.Default.GOPATH, "bin") } return GOBIN } return GOBIN } func main() { pwd, err := os.Getwd() if err != nil { fmt.Println("Can not get current working directory.") os.Exit(1) } GOBIN := GetGOBIN() binPath := os.Getenv("PATH") pathSlice := []string{pwd, GOBIN, binPath} binPath = strings.Join(pathSlice, string(os.PathListSeparator)) os.Setenv("PATH", binPath) suffix := "" if runtime.GOOS == "windows" { suffix = ".exe" } protoc := "protoc" if linkPath, err := os.Readlink(protoc); err == nil { protoc = linkPath } protoFilesMap := make(map[string][]string) walkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error { if err != nil { fmt.Println(err) return err } if info.IsDir() { return nil } dir := filepath.Dir(path) filename := filepath.Base(path) if strings.HasSuffix(filename, ".proto") && filename != "typed_message.proto" && filename != "descriptor.proto" { protoFilesMap[dir] = append(protoFilesMap[dir], path) } return nil }) if walkErr != nil { fmt.Println(walkErr) os.Exit(1) } for _, files := range protoFilesMap { for _, relProtoFile := range files { args := []string{ "-I", ".", "--go_out", pwd, "--go_opt", "paths=source_relative", "--go-grpc_out", pwd, "--go-grpc_opt", "paths=source_relative", "--plugin", "protoc-gen-go=" + filepath.Join(GOBIN, "protoc-gen-go"+suffix), "--plugin", "protoc-gen-go-grpc=" + filepath.Join(GOBIN, "protoc-gen-go-grpc"+suffix), } args = append(args, relProtoFile) cmd := exec.Command(protoc, args...) cmd.Env = append(cmd.Env, os.Environ()...) output, cmdErr := cmd.CombinedOutput() if len(output) > 0 { fmt.Println(string(output)) } if cmdErr != nil { fmt.Println(cmdErr) os.Exit(1) } } } normalizeWalkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error { if err != nil { fmt.Println(err) return err } if info.IsDir() { return nil } filename := filepath.Base(path) if strings.HasSuffix(filename, ".pb.go") && path != "config.pb.go" { if err := NormalizeGeneratedProtoFile(path); err != nil { fmt.Println(err) os.Exit(1) } } return nil }) if normalizeWalkErr != nil { fmt.Println(normalizeWalkErr) os.Exit(1) } } func NormalizeGeneratedProtoFile(path string) error { fd, err := os.OpenFile(path, os.O_RDWR, 0o644) if err != nil { return err } _, err = fd.Seek(0, io.SeekStart) if err != nil { return err } out := bytes.NewBuffer(nil) scanner := bufio.NewScanner(fd) valid := false for scanner.Scan() { if !valid && !strings.HasPrefix(scanner.Text(), "package ") { continue } valid = true out.Write(scanner.Bytes()) out.Write([]byte("\n")) } _, err = fd.Seek(0, io.SeekStart) if err != nil { return err } err = fd.Truncate(0) if err != nil { return err } _, err = io.Copy(fd, bytes.NewReader(out.Bytes())) if err != nil { return err } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/internal/build_libbox/main.go
Bcore/windows/resources/sing-box-main/cmd/internal/build_libbox/main.go
package main import ( "flag" "os" "os/exec" "path/filepath" "strings" _ "github.com/sagernet/gomobile" "github.com/sagernet/sing-box/cmd/internal/build_shared" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/common/rw" ) var ( debugEnabled bool target string ) func init() { flag.BoolVar(&debugEnabled, "debug", false, "enable debug") flag.StringVar(&target, "target", "android", "target platform") } func main() { flag.Parse() build_shared.FindMobile() switch target { case "android": buildAndroid() case "ios": buildiOS() } } var ( sharedFlags []string debugFlags []string sharedTags []string iosTags []string debugTags []string ) func init() { sharedFlags = append(sharedFlags, "-trimpath") sharedFlags = append(sharedFlags, "-buildvcs=false") currentTag, err := build_shared.ReadTag() if err != nil { currentTag = "unknown" } sharedFlags = append(sharedFlags, "-ldflags", "-X github.com/sagernet/sing-box/constant.Version="+currentTag+" -s -w -buildid=") debugFlags = append(debugFlags, "-ldflags", "-X github.com/sagernet/sing-box/constant.Version="+currentTag) sharedTags = append(sharedTags, "with_gvisor", "with_quic", "with_wireguard", "with_ech", "with_utls", "with_clash_api") iosTags = append(iosTags, "with_dhcp", "with_low_memory", "with_conntrack") debugTags = append(debugTags, "debug") } func buildAndroid() { build_shared.FindSDK() args := []string{ "bind", "-v", "-androidapi", "21", "-javapkg=io.nekohasekai", "-libname=box", } if !debugEnabled { args = append(args, sharedFlags...) } else { args = append(args, debugFlags...) } args = append(args, "-tags") if !debugEnabled { args = append(args, strings.Join(sharedTags, ",")) } else { args = append(args, strings.Join(append(sharedTags, debugTags...), ",")) } args = append(args, "./experimental/libbox") command := exec.Command(build_shared.GoBinPath+"/gomobile", args...) command.Stdout = os.Stdout command.Stderr = os.Stderr err := command.Run() if err != nil { log.Fatal(err) } const name = "libbox.aar" copyPath := filepath.Join("..", "sing-box-for-android", "app", "libs") if rw.IsDir(copyPath) { copyPath, _ = filepath.Abs(copyPath) err = rw.CopyFile(name, filepath.Join(copyPath, name)) if err != nil { log.Fatal(err) } log.Info("copied to ", copyPath) } } func buildiOS() { args := []string{ "bind", "-v", "-target", "ios,iossimulator,tvos,tvossimulator,macos", "-libname=box", } if !debugEnabled { args = append(args, sharedFlags...) } else { args = append(args, debugFlags...) } tags := append(sharedTags, iosTags...) args = append(args, "-tags") if !debugEnabled { args = append(args, strings.Join(tags, ",")) } else { args = append(args, strings.Join(append(tags, debugTags...), ",")) } args = append(args, "./experimental/libbox") command := exec.Command(build_shared.GoBinPath+"/gomobile", args...) command.Stdout = os.Stdout command.Stderr = os.Stderr err := command.Run() if err != nil { log.Fatal(err) } copyPath := filepath.Join("..", "sing-box-for-apple") if rw.IsDir(copyPath) { targetDir := filepath.Join(copyPath, "Libbox.xcframework") targetDir, _ = filepath.Abs(targetDir) os.RemoveAll(targetDir) os.Rename("Libbox.xcframework", targetDir) log.Info("copied to ", targetDir) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/internal/read_tag/main.go
Bcore/windows/resources/sing-box-main/cmd/internal/read_tag/main.go
package main import ( "os" "github.com/sagernet/sing-box/cmd/internal/build_shared" "github.com/sagernet/sing-box/log" ) func main() { currentTag, err := build_shared.ReadTag() if err != nil { log.Error(err) _, err = os.Stdout.WriteString("1.10.1\n") } else { _, err = os.Stdout.WriteString(currentTag + "\n") } if err != nil { log.Error(err) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_version.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_version.go
package main import ( "os" "runtime" "runtime/debug" C "github.com/sagernet/sing-box/constant" "github.com/spf13/cobra" ) var commandVersion = &cobra.Command{ Use: "version", Short: "Print current version of sing-box", Run: printVersion, Args: cobra.NoArgs, } var nameOnly bool func init() { commandVersion.Flags().BoolVarP(&nameOnly, "name", "n", false, "print version name only") mainCommand.AddCommand(commandVersion) } func printVersion(cmd *cobra.Command, args []string) { if nameOnly { os.Stdout.WriteString(C.Version + "\n") return } version := "sing-box version " + C.Version + "\n\n" version += "Environment: " + runtime.Version() + " " + runtime.GOOS + "/" + runtime.GOARCH + "\n" var tags string var revision string debugInfo, loaded := debug.ReadBuildInfo() if loaded { for _, setting := range debugInfo.Settings { switch setting.Key { case "-tags": tags = setting.Value case "vcs.revision": revision = setting.Value } } } if tags != "" { version += "Tags: " + tags + "\n" } if revision != "" { version += "Revision: " + revision + "\n" } if C.CGO_ENABLED { version += "CGO: enabled\n" } else { version += "CGO: disabled\n" } os.Stdout.WriteString(version) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_connect.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_connect.go
package main import ( "context" "os" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/bufio" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/task" "github.com/spf13/cobra" ) var commandConnectFlagNetwork string var commandConnect = &cobra.Command{ Use: "connect <address>", Short: "Connect to an address", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := connect(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandConnect.Flags().StringVarP(&commandConnectFlagNetwork, "network", "n", "tcp", "network type") commandTools.AddCommand(commandConnect) } func connect(address string) error { switch N.NetworkName(commandConnectFlagNetwork) { case N.NetworkTCP, N.NetworkUDP: default: return E.Cause(N.ErrUnknownNetwork, commandConnectFlagNetwork) } instance, err := createPreStartedClient() if err != nil { return err } defer instance.Close() dialer, err := createDialer(instance, commandConnectFlagNetwork, commandToolsFlagOutbound) if err != nil { return err } conn, err := dialer.DialContext(context.Background(), commandConnectFlagNetwork, M.ParseSocksaddr(address)) if err != nil { return E.Cause(err, "connect to server") } var group task.Group group.Append("upload", func(ctx context.Context) error { return common.Error(bufio.Copy(conn, os.Stdin)) }) group.Append("download", func(ctx context.Context) error { return common.Error(bufio.Copy(os.Stdout, conn)) }) group.Cleanup(func() { conn.Close() }) err = group.Run(context.Background()) if E.IsClosed(err) { log.Info(err) } else { log.Error(err) } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_upgrade.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_upgrade.go
package main import ( "bytes" "io" "os" "path/filepath" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" "github.com/spf13/cobra" ) var commandRuleSetUpgradeFlagWrite bool var commandRuleSetUpgrade = &cobra.Command{ Use: "upgrade <source-path>", Short: "Upgrade rule-set json", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := upgradeRuleSet(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandRuleSetUpgrade.Flags().BoolVarP(&commandRuleSetUpgradeFlagWrite, "write", "w", false, "write result to (source) file instead of stdout") commandRuleSet.AddCommand(commandRuleSetUpgrade) } func upgradeRuleSet(sourcePath string) error { var ( reader io.Reader err error ) if sourcePath == "stdin" { reader = os.Stdin } else { reader, err = os.Open(sourcePath) if err != nil { return err } } content, err := io.ReadAll(reader) if err != nil { return err } plainRuleSetCompat, err := json.UnmarshalExtended[option.PlainRuleSetCompat](content) if err != nil { return err } switch plainRuleSetCompat.Version { case C.RuleSetVersion1: default: log.Info("already up-to-date") return nil } plainRuleSet, err := plainRuleSetCompat.Upgrade() if err != nil { return err } buffer := new(bytes.Buffer) encoder := json.NewEncoder(buffer) encoder.SetIndent("", " ") err = encoder.Encode(plainRuleSet) if err != nil { return E.Cause(err, "encode config") } outputPath, _ := filepath.Abs(sourcePath) if !commandRuleSetUpgradeFlagWrite || sourcePath == "stdin" { os.Stdout.WriteString(buffer.String() + "\n") return nil } if bytes.Equal(content, buffer.Bytes()) { return nil } output, err := os.Create(sourcePath) if err != nil { return E.Cause(err, "open output") } _, err = output.Write(buffer.Bytes()) output.Close() if err != nil { return E.Cause(err, "write output") } os.Stderr.WriteString(outputPath + "\n") return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_synctime.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_synctime.go
package main import ( "context" "os" "github.com/sagernet/sing-box/common/settings" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/ntp" "github.com/spf13/cobra" ) var ( commandSyncTimeFlagServer string commandSyncTimeOutputFormat string commandSyncTimeWrite bool ) var commandSyncTime = &cobra.Command{ Use: "synctime", Short: "Sync time using the NTP protocol", Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { err := syncTime() if err != nil { log.Fatal(err) } }, } func init() { commandSyncTime.Flags().StringVarP(&commandSyncTimeFlagServer, "server", "s", "time.apple.com", "Set NTP server") commandSyncTime.Flags().StringVarP(&commandSyncTimeOutputFormat, "format", "f", C.TimeLayout, "Set output format") commandSyncTime.Flags().BoolVarP(&commandSyncTimeWrite, "write", "w", false, "Write time to system") commandTools.AddCommand(commandSyncTime) } func syncTime() error { instance, err := createPreStartedClient() if err != nil { return err } dialer, err := createDialer(instance, N.NetworkUDP, commandToolsFlagOutbound) if err != nil { return err } defer instance.Close() serverAddress := M.ParseSocksaddr(commandSyncTimeFlagServer) if serverAddress.Port == 0 { serverAddress.Port = 123 } response, err := ntp.Exchange(context.Background(), dialer, serverAddress) if err != nil { return err } if commandSyncTimeWrite { err = settings.SetSystemTime(response.Time) if err != nil { return E.Cause(err, "write time to system") } } os.Stdout.WriteString(response.Time.Local().Format(commandSyncTimeOutputFormat)) return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_compile.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_compile.go
package main import ( "io" "os" "strings" "github.com/sagernet/sing-box/common/srs" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/json" "github.com/spf13/cobra" ) var flagRuleSetCompileOutput string const flagRuleSetCompileDefaultOutput = "<file_name>.srs" var commandRuleSetCompile = &cobra.Command{ Use: "compile [source-path]", Short: "Compile rule-set json to binary", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := compileRuleSet(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandRuleSet.AddCommand(commandRuleSetCompile) commandRuleSetCompile.Flags().StringVarP(&flagRuleSetCompileOutput, "output", "o", flagRuleSetCompileDefaultOutput, "Output file") } func compileRuleSet(sourcePath string) error { var ( reader io.Reader err error ) if sourcePath == "stdin" { reader = os.Stdin } else { reader, err = os.Open(sourcePath) if err != nil { return err } } content, err := io.ReadAll(reader) if err != nil { return err } plainRuleSet, err := json.UnmarshalExtended[option.PlainRuleSetCompat](content) if err != nil { return err } ruleSet, err := plainRuleSet.Upgrade() if err != nil { return err } var outputPath string if flagRuleSetCompileOutput == flagRuleSetCompileDefaultOutput { if strings.HasSuffix(sourcePath, ".json") { outputPath = sourcePath[:len(sourcePath)-5] + ".srs" } else { outputPath = sourcePath + ".srs" } } else { outputPath = flagRuleSetCompileOutput } outputFile, err := os.Create(outputPath) if err != nil { return err } err = srs.Write(outputFile, ruleSet, plainRuleSet.Version == C.RuleSetVersion2) if err != nil { outputFile.Close() os.Remove(outputPath) return err } outputFile.Close() return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate.go
package main import ( "crypto/rand" "encoding/base64" "encoding/hex" "os" "strconv" "github.com/sagernet/sing-box/log" "github.com/gofrs/uuid/v5" "github.com/spf13/cobra" ) var commandGenerate = &cobra.Command{ Use: "generate", Short: "Generate things", } func init() { commandGenerate.AddCommand(commandGenerateUUID) commandGenerate.AddCommand(commandGenerateRandom) mainCommand.AddCommand(commandGenerate) } var ( outputBase64 bool outputHex bool ) var commandGenerateRandom = &cobra.Command{ Use: "rand <length>", Short: "Generate random bytes", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := generateRandom(args) if err != nil { log.Fatal(err) } }, } func init() { commandGenerateRandom.Flags().BoolVar(&outputBase64, "base64", false, "Generate base64 string") commandGenerateRandom.Flags().BoolVar(&outputHex, "hex", false, "Generate hex string") } func generateRandom(args []string) error { length, err := strconv.Atoi(args[0]) if err != nil { return err } randomBytes := make([]byte, length) _, err = rand.Read(randomBytes) if err != nil { return err } if outputBase64 { _, err = os.Stdout.WriteString(base64.StdEncoding.EncodeToString(randomBytes) + "\n") } else if outputHex { _, err = os.Stdout.WriteString(hex.EncodeToString(randomBytes) + "\n") } else { _, err = os.Stdout.Write(randomBytes) } return err } var commandGenerateUUID = &cobra.Command{ Use: "uuid", Short: "Generate UUID string", Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { err := generateUUID() if err != nil { log.Fatal(err) } }, } func generateUUID() error { newUUID, err := uuid.NewV4() if err != nil { return err } _, err = os.Stdout.WriteString(newUUID.String() + "\n") return err }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite.go
package main import ( "github.com/sagernet/sing-box/common/geosite" "github.com/sagernet/sing-box/log" E "github.com/sagernet/sing/common/exceptions" "github.com/spf13/cobra" ) var ( commandGeoSiteFlagFile string geositeReader *geosite.Reader geositeCodeList []string ) var commandGeoSite = &cobra.Command{ Use: "geosite", Short: "Geosite tools", PersistentPreRun: func(cmd *cobra.Command, args []string) { err := geositePreRun() if err != nil { log.Fatal(err) } }, } func init() { commandGeoSite.PersistentFlags().StringVarP(&commandGeoSiteFlagFile, "file", "f", "geosite.db", "geosite file") mainCommand.AddCommand(commandGeoSite) } func geositePreRun() error { reader, codeList, err := geosite.Open(commandGeoSiteFlagFile) if err != nil { return E.Cause(err, "open geosite file") } geositeReader = reader geositeCodeList = codeList return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite_export.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite_export.go
package main import ( "io" "os" "github.com/sagernet/sing-box/common/geosite" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/json" "github.com/spf13/cobra" ) var commandGeositeExportOutput string const commandGeositeExportDefaultOutput = "geosite-<category>.json" var commandGeositeExport = &cobra.Command{ Use: "export <category>", Short: "Export geosite category as rule-set", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := geositeExport(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandGeositeExport.Flags().StringVarP(&commandGeositeExportOutput, "output", "o", commandGeositeExportDefaultOutput, "Output path") commandGeoSite.AddCommand(commandGeositeExport) } func geositeExport(category string) error { sourceSet, err := geositeReader.Read(category) if err != nil { return err } var ( outputFile *os.File outputWriter io.Writer ) if commandGeositeExportOutput == "stdout" { outputWriter = os.Stdout } else if commandGeositeExportOutput == commandGeositeExportDefaultOutput { outputFile, err = os.Create("geosite-" + category + ".json") if err != nil { return err } defer outputFile.Close() outputWriter = outputFile } else { outputFile, err = os.Create(commandGeositeExportOutput) if err != nil { return err } defer outputFile.Close() outputWriter = outputFile } encoder := json.NewEncoder(outputWriter) encoder.SetIndent("", " ") var headlessRule option.DefaultHeadlessRule defaultRule := geosite.Compile(sourceSet) headlessRule.Domain = defaultRule.Domain headlessRule.DomainSuffix = defaultRule.DomainSuffix headlessRule.DomainKeyword = defaultRule.DomainKeyword headlessRule.DomainRegex = defaultRule.DomainRegex var plainRuleSet option.PlainRuleSetCompat plainRuleSet.Version = C.RuleSetVersion2 plainRuleSet.Options.Rules = []option.HeadlessRule{ { Type: C.RuleTypeDefault, DefaultOptions: headlessRule, }, } return encoder.Encode(plainRuleSet) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geoip.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geoip.go
package main import ( "github.com/sagernet/sing-box/log" E "github.com/sagernet/sing/common/exceptions" "github.com/oschwald/maxminddb-golang" "github.com/spf13/cobra" ) var ( geoipReader *maxminddb.Reader commandGeoIPFlagFile string ) var commandGeoip = &cobra.Command{ Use: "geoip", Short: "GeoIP tools", PersistentPreRun: func(cmd *cobra.Command, args []string) { err := geoipPreRun() if err != nil { log.Fatal(err) } }, } func init() { commandGeoip.PersistentFlags().StringVarP(&commandGeoIPFlagFile, "file", "f", "geoip.db", "geoip file") mainCommand.AddCommand(commandGeoip) } func geoipPreRun() error { reader, err := maxminddb.Open(commandGeoIPFlagFile) if err != nil { return err } if reader.Metadata.DatabaseType != "sing-geoip" { reader.Close() return E.New("incorrect database type, expected sing-geoip, got ", reader.Metadata.DatabaseType) } geoipReader = reader return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_format.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_format.go
package main import ( "bytes" "os" "path/filepath" "github.com/sagernet/sing-box/log" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" "github.com/sagernet/sing/common/json/badjson" "github.com/spf13/cobra" ) var commandFormatFlagWrite bool var commandFormat = &cobra.Command{ Use: "format", Short: "Format configuration", Run: func(cmd *cobra.Command, args []string) { err := format() if err != nil { log.Fatal(err) } }, Args: cobra.NoArgs, } func init() { commandFormat.Flags().BoolVarP(&commandFormatFlagWrite, "write", "w", false, "write result to (source) file instead of stdout") mainCommand.AddCommand(commandFormat) } func format() error { optionsList, err := readConfig() if err != nil { return err } for _, optionsEntry := range optionsList { optionsEntry.options, err = badjson.Omitempty(optionsEntry.options) if err != nil { return err } buffer := new(bytes.Buffer) encoder := json.NewEncoder(buffer) encoder.SetIndent("", " ") err = encoder.Encode(optionsEntry.options) if err != nil { return E.Cause(err, "encode config") } outputPath, _ := filepath.Abs(optionsEntry.path) if !commandFormatFlagWrite { if len(optionsList) > 1 { os.Stdout.WriteString(outputPath + "\n") } os.Stdout.WriteString(buffer.String() + "\n") continue } if bytes.Equal(optionsEntry.content, buffer.Bytes()) { continue } output, err := os.Create(optionsEntry.path) if err != nil { return E.Cause(err, "open output") } _, err = output.Write(buffer.Bytes()) output.Close() if err != nil { return E.Cause(err, "write output") } os.Stderr.WriteString(outputPath + "\n") } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_format.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_format.go
package main import ( "bytes" "io" "os" "path/filepath" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" "github.com/spf13/cobra" ) var commandRuleSetFormatFlagWrite bool var commandRuleSetFormat = &cobra.Command{ Use: "format <source-path>", Short: "Format rule-set json", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := formatRuleSet(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandRuleSetFormat.Flags().BoolVarP(&commandRuleSetFormatFlagWrite, "write", "w", false, "write result to (source) file instead of stdout") commandRuleSet.AddCommand(commandRuleSetFormat) } func formatRuleSet(sourcePath string) error { var ( reader io.Reader err error ) if sourcePath == "stdin" { reader = os.Stdin } else { reader, err = os.Open(sourcePath) if err != nil { return err } } content, err := io.ReadAll(reader) if err != nil { return err } plainRuleSet, err := json.UnmarshalExtended[option.PlainRuleSetCompat](content) if err != nil { return err } buffer := new(bytes.Buffer) encoder := json.NewEncoder(buffer) encoder.SetIndent("", " ") err = encoder.Encode(plainRuleSet) if err != nil { return E.Cause(err, "encode config") } outputPath, _ := filepath.Abs(sourcePath) if !commandRuleSetFormatFlagWrite || sourcePath == "stdin" { os.Stdout.WriteString(buffer.String() + "\n") return nil } if bytes.Equal(content, buffer.Bytes()) { return nil } output, err := os.Create(sourcePath) if err != nil { return E.Cause(err, "open output") } _, err = output.Write(buffer.Bytes()) output.Close() if err != nil { return E.Cause(err, "write output") } os.Stderr.WriteString(outputPath + "\n") return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_convert.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_convert.go
package main import ( "io" "os" "strings" "github.com/sagernet/sing-box/cmd/sing-box/internal/convertor/adguard" "github.com/sagernet/sing-box/common/srs" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/spf13/cobra" ) var ( flagRuleSetConvertType string flagRuleSetConvertOutput string ) var commandRuleSetConvert = &cobra.Command{ Use: "convert [source-path]", Short: "Convert adguard DNS filter to rule-set", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := convertRuleSet(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandRuleSet.AddCommand(commandRuleSetConvert) commandRuleSetConvert.Flags().StringVarP(&flagRuleSetConvertType, "type", "t", "", "Source type, available: adguard") commandRuleSetConvert.Flags().StringVarP(&flagRuleSetConvertOutput, "output", "o", flagRuleSetCompileDefaultOutput, "Output file") } func convertRuleSet(sourcePath string) error { var ( reader io.Reader err error ) if sourcePath == "stdin" { reader = os.Stdin } else { reader, err = os.Open(sourcePath) if err != nil { return err } } var rules []option.HeadlessRule switch flagRuleSetConvertType { case "adguard": rules, err = adguard.Convert(reader) case "": return E.New("source type is required") default: return E.New("unsupported source type: ", flagRuleSetConvertType) } if err != nil { return err } var outputPath string if flagRuleSetConvertOutput == flagRuleSetCompileDefaultOutput { if strings.HasSuffix(sourcePath, ".txt") { outputPath = sourcePath[:len(sourcePath)-4] + ".srs" } else { outputPath = sourcePath + ".srs" } } else { outputPath = flagRuleSetConvertOutput } outputFile, err := os.Create(outputPath) if err != nil { return err } defer outputFile.Close() err = srs.Write(outputFile, option.PlainRuleSet{Rules: rules}, true) if err != nil { outputFile.Close() os.Remove(outputPath) return err } outputFile.Close() return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_check.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_check.go
package main import ( "context" "github.com/sagernet/sing-box" "github.com/sagernet/sing-box/log" "github.com/spf13/cobra" ) var commandCheck = &cobra.Command{ Use: "check", Short: "Check configuration", Run: func(cmd *cobra.Command, args []string) { err := check() if err != nil { log.Fatal(err) } }, Args: cobra.NoArgs, } func init() { mainCommand.AddCommand(commandCheck) } func check() error { options, err := readConfigAndMerge() if err != nil { return err } ctx, cancel := context.WithCancel(context.Background()) instance, err := box.New(box.Options{ Context: ctx, Options: options, }) if err == nil { instance.Close() } cancel() return err }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_fetch_http3_stub.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_fetch_http3_stub.go
//go:build !with_quic package main import ( "net/url" "os" box "github.com/sagernet/sing-box" ) func initializeHTTP3Client(instance *box.Box) error { return os.ErrInvalid } func fetchHTTP3(parsedURL *url.URL) error { return os.ErrInvalid }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate_vapid.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate_vapid.go
//go:build go1.20 package main import ( "crypto/ecdh" "crypto/rand" "encoding/base64" "os" "github.com/sagernet/sing-box/log" "github.com/spf13/cobra" ) var commandGenerateVAPIDKeyPair = &cobra.Command{ Use: "vapid-keypair", Short: "Generate VAPID key pair", Run: func(cmd *cobra.Command, args []string) { err := generateVAPIDKeyPair() if err != nil { log.Fatal(err) } }, } func init() { commandGenerate.AddCommand(commandGenerateVAPIDKeyPair) } func generateVAPIDKeyPair() error { privateKey, err := ecdh.P256().GenerateKey(rand.Reader) if err != nil { return err } publicKey := privateKey.PublicKey() os.Stdout.WriteString("PrivateKey: " + base64.RawURLEncoding.EncodeToString(privateKey.Bytes()) + "\n") os.Stdout.WriteString("PublicKey: " + base64.RawURLEncoding.EncodeToString(publicKey.Bytes()) + "\n") return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geoip_export.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geoip_export.go
package main import ( "io" "net" "os" "strings" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" "github.com/oschwald/maxminddb-golang" "github.com/spf13/cobra" ) var flagGeoipExportOutput string const flagGeoipExportDefaultOutput = "geoip-<country>.srs" var commandGeoipExport = &cobra.Command{ Use: "export <country>", Short: "Export geoip country as rule-set", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := geoipExport(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandGeoipExport.Flags().StringVarP(&flagGeoipExportOutput, "output", "o", flagGeoipExportDefaultOutput, "Output path") commandGeoip.AddCommand(commandGeoipExport) } func geoipExport(countryCode string) error { networks := geoipReader.Networks(maxminddb.SkipAliasedNetworks) countryMap := make(map[string][]*net.IPNet) var ( ipNet *net.IPNet nextCountryCode string err error ) for networks.Next() { ipNet, err = networks.Network(&nextCountryCode) if err != nil { return err } countryMap[nextCountryCode] = append(countryMap[nextCountryCode], ipNet) } ipNets := countryMap[strings.ToLower(countryCode)] if len(ipNets) == 0 { return E.New("country code not found: ", countryCode) } var ( outputFile *os.File outputWriter io.Writer ) if flagGeoipExportOutput == "stdout" { outputWriter = os.Stdout } else if flagGeoipExportOutput == flagGeoipExportDefaultOutput { outputFile, err = os.Create("geoip-" + countryCode + ".json") if err != nil { return err } defer outputFile.Close() outputWriter = outputFile } else { outputFile, err = os.Create(flagGeoipExportOutput) if err != nil { return err } defer outputFile.Close() outputWriter = outputFile } encoder := json.NewEncoder(outputWriter) encoder.SetIndent("", " ") var headlessRule option.DefaultHeadlessRule headlessRule.IPCIDR = make([]string, 0, len(ipNets)) for _, cidr := range ipNets { headlessRule.IPCIDR = append(headlessRule.IPCIDR, cidr.String()) } var plainRuleSet option.PlainRuleSetCompat plainRuleSet.Version = C.RuleSetVersion2 plainRuleSet.Options.Rules = []option.HeadlessRule{ { Type: C.RuleTypeDefault, DefaultOptions: headlessRule, }, } return encoder.Encode(plainRuleSet) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_run.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_run.go
package main import ( "context" "io" "os" "os/signal" "path/filepath" runtimeDebug "runtime/debug" "sort" "strings" "syscall" "time" "github.com/sagernet/sing-box" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" "github.com/sagernet/sing/common/json/badjson" "github.com/spf13/cobra" ) var commandRun = &cobra.Command{ Use: "run", Short: "Run service", Run: func(cmd *cobra.Command, args []string) { err := run() if err != nil { log.Fatal(err) } }, } func init() { mainCommand.AddCommand(commandRun) } type OptionsEntry struct { content []byte path string options option.Options } func readConfigAt(path string) (*OptionsEntry, error) { var ( configContent []byte err error ) if path == "stdin" { configContent, err = io.ReadAll(os.Stdin) } else { configContent, err = os.ReadFile(path) } if err != nil { return nil, E.Cause(err, "read config at ", path) } options, err := json.UnmarshalExtended[option.Options](configContent) if err != nil { return nil, E.Cause(err, "decode config at ", path) } return &OptionsEntry{ content: configContent, path: path, options: options, }, nil } func readConfig() ([]*OptionsEntry, error) { var optionsList []*OptionsEntry for _, path := range configPaths { optionsEntry, err := readConfigAt(path) if err != nil { return nil, err } optionsList = append(optionsList, optionsEntry) } for _, directory := range configDirectories { entries, err := os.ReadDir(directory) if err != nil { return nil, E.Cause(err, "read config directory at ", directory) } for _, entry := range entries { if !strings.HasSuffix(entry.Name(), ".json") || entry.IsDir() { continue } optionsEntry, err := readConfigAt(filepath.Join(directory, entry.Name())) if err != nil { return nil, err } optionsList = append(optionsList, optionsEntry) } } sort.Slice(optionsList, func(i, j int) bool { return optionsList[i].path < optionsList[j].path }) return optionsList, nil } func readConfigAndMerge() (option.Options, error) { optionsList, err := readConfig() if err != nil { return option.Options{}, err } if len(optionsList) == 1 { return optionsList[0].options, nil } var mergedMessage json.RawMessage for _, options := range optionsList { mergedMessage, err = badjson.MergeJSON(options.options.RawMessage, mergedMessage, false) if err != nil { return option.Options{}, E.Cause(err, "merge config at ", options.path) } } var mergedOptions option.Options err = mergedOptions.UnmarshalJSON(mergedMessage) if err != nil { return option.Options{}, E.Cause(err, "unmarshal merged config") } return mergedOptions, nil } func create() (*box.Box, context.CancelFunc, error) { options, err := readConfigAndMerge() if err != nil { return nil, nil, err } if disableColor { if options.Log == nil { options.Log = &option.LogOptions{} } options.Log.DisableColor = true } ctx, cancel := context.WithCancel(globalCtx) instance, err := box.New(box.Options{ Context: ctx, Options: options, }) if err != nil { cancel() return nil, nil, E.Cause(err, "create service") } osSignals := make(chan os.Signal, 1) signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP) defer func() { signal.Stop(osSignals) close(osSignals) }() startCtx, finishStart := context.WithCancel(context.Background()) go func() { _, loaded := <-osSignals if loaded { cancel() closeMonitor(startCtx) } }() err = instance.Start() finishStart() if err != nil { cancel() return nil, nil, E.Cause(err, "start service") } return instance, cancel, nil } func run() error { osSignals := make(chan os.Signal, 1) signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP) defer signal.Stop(osSignals) for { instance, cancel, err := create() if err != nil { return err } runtimeDebug.FreeOSMemory() for { osSignal := <-osSignals if osSignal == syscall.SIGHUP { err = check() if err != nil { log.Error(E.Cause(err, "reload service")) continue } } cancel() closeCtx, closed := context.WithCancel(context.Background()) go closeMonitor(closeCtx) err = instance.Close() closed() if osSignal != syscall.SIGHUP { if err != nil { log.Error(E.Cause(err, "sing-box did not closed properly")) } return nil } break } } } func closeMonitor(ctx context.Context) { time.Sleep(C.FatalStopTimeout) select { case <-ctx.Done(): return default: } log.Fatal("sing-box did not close!") }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_decompile.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_decompile.go
package main import ( "io" "os" "strings" "github.com/sagernet/sing-box/common/srs" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/json" "github.com/spf13/cobra" ) var flagRuleSetDecompileOutput string const flagRuleSetDecompileDefaultOutput = "<file_name>.json" var commandRuleSetDecompile = &cobra.Command{ Use: "decompile [binary-path]", Short: "Decompile rule-set binary to json", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := decompileRuleSet(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandRuleSet.AddCommand(commandRuleSetDecompile) commandRuleSetDecompile.Flags().StringVarP(&flagRuleSetDecompileOutput, "output", "o", flagRuleSetDecompileDefaultOutput, "Output file") } func decompileRuleSet(sourcePath string) error { var ( reader io.Reader err error ) if sourcePath == "stdin" { reader = os.Stdin } else { reader, err = os.Open(sourcePath) if err != nil { return err } } plainRuleSet, err := srs.Read(reader, true) if err != nil { return err } ruleSet := option.PlainRuleSetCompat{ Version: C.RuleSetVersion1, Options: plainRuleSet, } var outputPath string if flagRuleSetDecompileOutput == flagRuleSetDecompileDefaultOutput { if strings.HasSuffix(sourcePath, ".srs") { outputPath = sourcePath[:len(sourcePath)-4] + ".json" } else { outputPath = sourcePath + ".json" } } else { outputPath = flagRuleSetDecompileOutput } outputFile, err := os.Create(outputPath) if err != nil { return err } encoder := json.NewEncoder(outputFile) encoder.SetIndent("", " ") err = encoder.Encode(ruleSet) if err != nil { outputFile.Close() os.Remove(outputPath) return err } outputFile.Close() return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate_wireguard.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate_wireguard.go
package main import ( "encoding/base64" "os" "github.com/sagernet/sing-box/log" "github.com/spf13/cobra" "golang.zx2c4.com/wireguard/wgctrl/wgtypes" ) func init() { commandGenerate.AddCommand(commandGenerateWireGuardKeyPair) commandGenerate.AddCommand(commandGenerateRealityKeyPair) } var commandGenerateWireGuardKeyPair = &cobra.Command{ Use: "wg-keypair", Short: "Generate WireGuard key pair", Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { err := generateWireGuardKey() if err != nil { log.Fatal(err) } }, } func generateWireGuardKey() error { privateKey, err := wgtypes.GeneratePrivateKey() if err != nil { return err } os.Stdout.WriteString("PrivateKey: " + privateKey.String() + "\n") os.Stdout.WriteString("PublicKey: " + privateKey.PublicKey().String() + "\n") return nil } var commandGenerateRealityKeyPair = &cobra.Command{ Use: "reality-keypair", Short: "Generate reality key pair", Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { err := generateRealityKey() if err != nil { log.Fatal(err) } }, } func generateRealityKey() error { privateKey, err := wgtypes.GeneratePrivateKey() if err != nil { return err } publicKey := privateKey.PublicKey() os.Stdout.WriteString("PrivateKey: " + base64.RawURLEncoding.EncodeToString(privateKey[:]) + "\n") os.Stdout.WriteString("PublicKey: " + base64.RawURLEncoding.EncodeToString(publicKey[:]) + "\n") return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd.go
package main import ( "context" "os" "os/user" "strconv" "time" _ "github.com/sagernet/sing-box/include" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/service/filemanager" "github.com/spf13/cobra" ) var ( globalCtx context.Context configPaths []string configDirectories []string workingDir string disableColor bool ) var mainCommand = &cobra.Command{ Use: "sing-box", PersistentPreRun: preRun, } func init() { mainCommand.PersistentFlags().StringArrayVarP(&configPaths, "config", "c", nil, "set configuration file path") mainCommand.PersistentFlags().StringArrayVarP(&configDirectories, "config-directory", "C", nil, "set configuration directory path") mainCommand.PersistentFlags().StringVarP(&workingDir, "directory", "D", "", "set working directory") mainCommand.PersistentFlags().BoolVarP(&disableColor, "disable-color", "", false, "disable color output") } func preRun(cmd *cobra.Command, args []string) { globalCtx = context.Background() sudoUser := os.Getenv("SUDO_USER") sudoUID, _ := strconv.Atoi(os.Getenv("SUDO_UID")) sudoGID, _ := strconv.Atoi(os.Getenv("SUDO_GID")) if sudoUID == 0 && sudoGID == 0 && sudoUser != "" { sudoUserObject, _ := user.Lookup(sudoUser) if sudoUserObject != nil { sudoUID, _ = strconv.Atoi(sudoUserObject.Uid) sudoGID, _ = strconv.Atoi(sudoUserObject.Gid) } } if sudoUID > 0 && sudoGID > 0 { globalCtx = filemanager.WithDefault(globalCtx, "", "", sudoUID, sudoGID) } if disableColor { log.SetStdLogger(log.NewDefaultFactory(context.Background(), log.Formatter{BaseTime: time.Now(), DisableColors: true}, os.Stderr, "", nil, false).Logger()) } if workingDir != "" { _, err := os.Stat(workingDir) if err != nil { filemanager.MkdirAll(globalCtx, workingDir, 0o777) } err = os.Chdir(workingDir) if err != nil { log.Fatal(err) } } if len(configPaths) == 0 && len(configDirectories) == 0 { configPaths = append(configPaths, "config.json") } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_fetch.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_fetch.go
package main import ( "context" "errors" "io" "net" "net/http" "net/url" "os" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/common/bufio" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" "github.com/spf13/cobra" ) var commandFetch = &cobra.Command{ Use: "fetch", Short: "Fetch an URL", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { err := fetch(args) if err != nil { log.Fatal(err) } }, } func init() { commandTools.AddCommand(commandFetch) } var ( httpClient *http.Client http3Client *http.Client ) func fetch(args []string) error { instance, err := createPreStartedClient() if err != nil { return err } defer instance.Close() httpClient = &http.Client{ Transport: &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { dialer, err := createDialer(instance, network, commandToolsFlagOutbound) if err != nil { return nil, err } return dialer.DialContext(ctx, network, M.ParseSocksaddr(addr)) }, ForceAttemptHTTP2: true, }, } defer httpClient.CloseIdleConnections() if C.WithQUIC { err = initializeHTTP3Client(instance) if err != nil { return err } defer http3Client.CloseIdleConnections() } for _, urlString := range args { var parsedURL *url.URL parsedURL, err = url.Parse(urlString) if err != nil { return err } switch parsedURL.Scheme { case "": parsedURL.Scheme = "http" fallthrough case "http", "https": err = fetchHTTP(httpClient, parsedURL) if err != nil { return err } case "http3": if !C.WithQUIC { return C.ErrQUICNotIncluded } parsedURL.Scheme = "https" err = fetchHTTP(http3Client, parsedURL) if err != nil { return err } default: return E.New("unsupported scheme: ", parsedURL.Scheme) } } return nil } func fetchHTTP(httpClient *http.Client, parsedURL *url.URL) error { request, err := http.NewRequest("GET", parsedURL.String(), nil) if err != nil { return err } request.Header.Add("User-Agent", "curl/7.88.0") response, err := httpClient.Do(request) if err != nil { return err } defer response.Body.Close() _, err = bufio.Copy(os.Stdout, response.Body) if errors.Is(err, io.EOF) { return nil } return err }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set.go
package main import ( "github.com/spf13/cobra" ) var commandRuleSet = &cobra.Command{ Use: "rule-set", Short: "Manage rule-sets", } func init() { mainCommand.AddCommand(commandRuleSet) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/generate_completions.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/generate_completions.go
//go:build generate && generate_completions package main import "github.com/sagernet/sing-box/log" func main() { err := generateCompletions() if err != nil { log.Fatal(err) } } func generateCompletions() error { err := mainCommand.GenBashCompletionFile("release/completions/sing-box.bash") if err != nil { return err } err = mainCommand.GenFishCompletionFile("release/completions/sing-box.fish", true) if err != nil { return err } err = mainCommand.GenZshCompletionFile("release/completions/sing-box.zsh") if err != nil { return err } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_match.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_rule_set_match.go
package main import ( "bytes" "io" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/srs" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/route" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" "github.com/sagernet/sing/common/json" M "github.com/sagernet/sing/common/metadata" "github.com/spf13/cobra" ) var flagRuleSetMatchFormat string var commandRuleSetMatch = &cobra.Command{ Use: "match <rule-set path> <IP address/domain>", Short: "Check if an IP address or a domain matches the rule-set", Args: cobra.ExactArgs(2), Run: func(cmd *cobra.Command, args []string) { err := ruleSetMatch(args[0], args[1]) if err != nil { log.Fatal(err) } }, } func init() { commandRuleSetMatch.Flags().StringVarP(&flagRuleSetMatchFormat, "format", "f", "source", "rule-set format") commandRuleSet.AddCommand(commandRuleSetMatch) } func ruleSetMatch(sourcePath string, domain string) error { var ( reader io.Reader err error ) if sourcePath == "stdin" { reader = os.Stdin } else { reader, err = os.Open(sourcePath) if err != nil { return E.Cause(err, "read rule-set") } } content, err := io.ReadAll(reader) if err != nil { return E.Cause(err, "read rule-set") } var plainRuleSet option.PlainRuleSet switch flagRuleSetMatchFormat { case C.RuleSetFormatSource: var compat option.PlainRuleSetCompat compat, err = json.UnmarshalExtended[option.PlainRuleSetCompat](content) if err != nil { return err } plainRuleSet, err = compat.Upgrade() if err != nil { return err } case C.RuleSetFormatBinary: plainRuleSet, err = srs.Read(bytes.NewReader(content), false) if err != nil { return err } default: return E.New("unknown rule-set format: ", flagRuleSetMatchFormat) } ipAddress := M.ParseAddr(domain) var metadata adapter.InboundContext if ipAddress.IsValid() { metadata.Destination = M.SocksaddrFrom(ipAddress, 0) } else { metadata.Domain = domain } for i, ruleOptions := range plainRuleSet.Rules { var currentRule adapter.HeadlessRule currentRule, err = route.NewHeadlessRule(nil, ruleOptions) if err != nil { return E.Cause(err, "parse rule_set.rules.[", i, "]") } if currentRule.Match(&metadata) { println(F.ToString("match rules.[", i, "]: ", currentRule)) } } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geoip_lookup.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geoip_lookup.go
package main import ( "net/netip" "os" "github.com/sagernet/sing-box/log" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" "github.com/spf13/cobra" ) var commandGeoipLookup = &cobra.Command{ Use: "lookup <address>", Short: "Lookup if an IP address is contained in the GeoIP database", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := geoipLookup(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandGeoip.AddCommand(commandGeoipLookup) } func geoipLookup(address string) error { addr, err := netip.ParseAddr(address) if err != nil { return E.Cause(err, "parse address") } if !N.IsPublicAddr(addr) { os.Stdout.WriteString("private\n") return nil } var code string _ = geoipReader.Lookup(addr.AsSlice(), &code) if code != "" { os.Stdout.WriteString(code + "\n") return nil } os.Stdout.WriteString("unknown\n") return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite_list.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite_list.go
package main import ( "os" "sort" "github.com/sagernet/sing-box/log" F "github.com/sagernet/sing/common/format" "github.com/spf13/cobra" ) var commandGeositeList = &cobra.Command{ Use: "list <category>", Short: "List geosite categories", Run: func(cmd *cobra.Command, args []string) { err := geositeList() if err != nil { log.Fatal(err) } }, } func init() { commandGeoSite.AddCommand(commandGeositeList) } func geositeList() error { var geositeEntry []struct { category string items int } for _, category := range geositeCodeList { sourceSet, err := geositeReader.Read(category) if err != nil { return err } geositeEntry = append(geositeEntry, struct { category string items int }{category, len(sourceSet)}) } sort.SliceStable(geositeEntry, func(i, j int) bool { return geositeEntry[i].items < geositeEntry[j].items }) for _, entry := range geositeEntry { os.Stdout.WriteString(F.ToString(entry.category, " (", entry.items, ")\n")) } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate_ech.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate_ech.go
package main import ( "os" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/log" "github.com/spf13/cobra" ) var pqSignatureSchemesEnabled bool var commandGenerateECHKeyPair = &cobra.Command{ Use: "ech-keypair <plain_server_name>", Short: "Generate TLS ECH key pair", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := generateECHKeyPair(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandGenerateECHKeyPair.Flags().BoolVar(&pqSignatureSchemesEnabled, "pq-signature-schemes-enabled", false, "Enable PQ signature schemes") commandGenerate.AddCommand(commandGenerateECHKeyPair) } func generateECHKeyPair(serverName string) error { configPem, keyPem, err := tls.ECHKeygenDefault(serverName, pqSignatureSchemesEnabled) if err != nil { return err } os.Stdout.WriteString(configPem) os.Stdout.WriteString(keyPem) return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geoip_list.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geoip_list.go
package main import ( "os" "github.com/sagernet/sing-box/log" "github.com/spf13/cobra" ) var commandGeoipList = &cobra.Command{ Use: "list", Short: "List geoip country codes", Run: func(cmd *cobra.Command, args []string) { err := listGeoip() if err != nil { log.Fatal(err) } }, } func init() { commandGeoip.AddCommand(commandGeoipList) } func listGeoip() error { for _, code := range geoipReader.Metadata.Languages { os.Stdout.WriteString(code + "\n") } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_merge.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_merge.go
package main import ( "bytes" "os" "path/filepath" "strings" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" "github.com/sagernet/sing/common/rw" "github.com/spf13/cobra" ) var commandMerge = &cobra.Command{ Use: "merge <output>", Short: "Merge configurations", Run: func(cmd *cobra.Command, args []string) { err := merge(args[0]) if err != nil { log.Fatal(err) } }, Args: cobra.ExactArgs(1), } func init() { mainCommand.AddCommand(commandMerge) } func merge(outputPath string) error { mergedOptions, err := readConfigAndMerge() if err != nil { return err } err = mergePathResources(&mergedOptions) if err != nil { return err } buffer := new(bytes.Buffer) encoder := json.NewEncoder(buffer) encoder.SetIndent("", " ") err = encoder.Encode(mergedOptions) if err != nil { return E.Cause(err, "encode config") } if existsContent, err := os.ReadFile(outputPath); err != nil { if string(existsContent) == buffer.String() { return nil } } err = rw.MkdirParent(outputPath) if err != nil { return err } err = os.WriteFile(outputPath, buffer.Bytes(), 0o644) if err != nil { return err } outputPath, _ = filepath.Abs(outputPath) os.Stderr.WriteString(outputPath + "\n") return nil } func mergePathResources(options *option.Options) error { for index, inbound := range options.Inbounds { rawOptions, err := inbound.RawOptions() if err != nil { return err } if tlsOptions, containsTLSOptions := rawOptions.(option.InboundTLSOptionsWrapper); containsTLSOptions { tlsOptions.ReplaceInboundTLSOptions(mergeTLSInboundOptions(tlsOptions.TakeInboundTLSOptions())) } options.Inbounds[index] = inbound } for index, outbound := range options.Outbounds { rawOptions, err := outbound.RawOptions() if err != nil { return err } switch outbound.Type { case C.TypeSSH: outbound.SSHOptions = mergeSSHOutboundOptions(outbound.SSHOptions) } if tlsOptions, containsTLSOptions := rawOptions.(option.OutboundTLSOptionsWrapper); containsTLSOptions { tlsOptions.ReplaceOutboundTLSOptions(mergeTLSOutboundOptions(tlsOptions.TakeOutboundTLSOptions())) } options.Outbounds[index] = outbound } return nil } func mergeTLSInboundOptions(options *option.InboundTLSOptions) *option.InboundTLSOptions { if options == nil { return nil } if options.CertificatePath != "" { if content, err := os.ReadFile(options.CertificatePath); err == nil { options.Certificate = trimStringArray(strings.Split(string(content), "\n")) } } if options.KeyPath != "" { if content, err := os.ReadFile(options.KeyPath); err == nil { options.Key = trimStringArray(strings.Split(string(content), "\n")) } } if options.ECH != nil { if options.ECH.KeyPath != "" { if content, err := os.ReadFile(options.ECH.KeyPath); err == nil { options.ECH.Key = trimStringArray(strings.Split(string(content), "\n")) } } } return options } func mergeTLSOutboundOptions(options *option.OutboundTLSOptions) *option.OutboundTLSOptions { if options == nil { return nil } if options.CertificatePath != "" { if content, err := os.ReadFile(options.CertificatePath); err == nil { options.Certificate = trimStringArray(strings.Split(string(content), "\n")) } } if options.ECH != nil { if options.ECH.ConfigPath != "" { if content, err := os.ReadFile(options.ECH.ConfigPath); err == nil { options.ECH.Config = trimStringArray(strings.Split(string(content), "\n")) } } } return options } func mergeSSHOutboundOptions(options option.SSHOutboundOptions) option.SSHOutboundOptions { if options.PrivateKeyPath != "" { if content, err := os.ReadFile(os.ExpandEnv(options.PrivateKeyPath)); err == nil { options.PrivateKey = trimStringArray(strings.Split(string(content), "\n")) } } return options } func trimStringArray(array []string) []string { return common.Filter(array, func(it string) bool { return strings.TrimSpace(it) != "" }) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_fetch_http3.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools_fetch_http3.go
//go:build with_quic package main import ( "context" "crypto/tls" "net/http" "github.com/sagernet/quic-go" "github.com/sagernet/quic-go/http3" box "github.com/sagernet/sing-box" "github.com/sagernet/sing/common/bufio" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) func initializeHTTP3Client(instance *box.Box) error { dialer, err := createDialer(instance, N.NetworkUDP, commandToolsFlagOutbound) if err != nil { return err } http3Client = &http.Client{ Transport: &http3.RoundTripper{ Dial: func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) { destination := M.ParseSocksaddr(addr) udpConn, dErr := dialer.DialContext(ctx, N.NetworkUDP, destination) if dErr != nil { return nil, dErr } return quic.DialEarly(ctx, bufio.NewUnbindPacketConn(udpConn), udpConn.RemoteAddr(), tlsCfg, cfg) }, }, } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_tools.go
package main import ( "github.com/sagernet/sing-box" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" "github.com/spf13/cobra" ) var commandToolsFlagOutbound string var commandTools = &cobra.Command{ Use: "tools", Short: "Experimental tools", } func init() { commandTools.PersistentFlags().StringVarP(&commandToolsFlagOutbound, "outbound", "o", "", "Use specified tag instead of default outbound") mainCommand.AddCommand(commandTools) } func createPreStartedClient() (*box.Box, error) { options, err := readConfigAndMerge() if err != nil { return nil, err } instance, err := box.New(box.Options{Options: options}) if err != nil { return nil, E.Cause(err, "create service") } err = instance.PreStart() if err != nil { return nil, E.Cause(err, "start service") } return instance, nil } func createDialer(instance *box.Box, network string, outboundTag string) (N.Dialer, error) { if outboundTag == "" { return instance.Router().DefaultOutbound(N.NetworkName(network)) } else { outbound, loaded := instance.Router().Outbound(outboundTag) if !loaded { return nil, E.New("outbound not found: ", outboundTag) } return outbound, nil } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite_lookup.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite_lookup.go
package main import ( "os" "sort" "github.com/sagernet/sing-box/log" E "github.com/sagernet/sing/common/exceptions" "github.com/spf13/cobra" ) var commandGeositeLookup = &cobra.Command{ Use: "lookup [category] <domain>", Short: "Check if a domain is in the geosite", Args: cobra.RangeArgs(1, 2), Run: func(cmd *cobra.Command, args []string) { var ( source string target string ) switch len(args) { case 1: target = args[0] case 2: source = args[0] target = args[1] } err := geositeLookup(source, target) if err != nil { log.Fatal(err) } }, } func init() { commandGeoSite.AddCommand(commandGeositeLookup) } func geositeLookup(source string, target string) error { var sourceMatcherList []struct { code string matcher *searchGeositeMatcher } if source != "" { sourceSet, err := geositeReader.Read(source) if err != nil { return err } sourceMatcher, err := newSearchGeositeMatcher(sourceSet) if err != nil { return E.Cause(err, "compile code: "+source) } sourceMatcherList = []struct { code string matcher *searchGeositeMatcher }{ { code: source, matcher: sourceMatcher, }, } } else { for _, code := range geositeCodeList { sourceSet, err := geositeReader.Read(code) if err != nil { return err } sourceMatcher, err := newSearchGeositeMatcher(sourceSet) if err != nil { return E.Cause(err, "compile code: "+code) } sourceMatcherList = append(sourceMatcherList, struct { code string matcher *searchGeositeMatcher }{ code: code, matcher: sourceMatcher, }) } } sort.SliceStable(sourceMatcherList, func(i, j int) bool { return sourceMatcherList[i].code < sourceMatcherList[j].code }) for _, matcherItem := range sourceMatcherList { if matchRule := matcherItem.matcher.Match(target); matchRule != "" { os.Stdout.WriteString("Match code (") os.Stdout.WriteString(matcherItem.code) os.Stdout.WriteString(") ") os.Stdout.WriteString(matchRule) os.Stdout.WriteString("\n") } } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite_matcher.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_geosite_matcher.go
package main import ( "regexp" "strings" "github.com/sagernet/sing-box/common/geosite" ) type searchGeositeMatcher struct { domainMap map[string]bool suffixList []string keywordList []string regexList []string } func newSearchGeositeMatcher(items []geosite.Item) (*searchGeositeMatcher, error) { options := geosite.Compile(items) domainMap := make(map[string]bool) for _, domain := range options.Domain { domainMap[domain] = true } rule := &searchGeositeMatcher{ domainMap: domainMap, suffixList: options.DomainSuffix, keywordList: options.DomainKeyword, regexList: options.DomainRegex, } return rule, nil } func (r *searchGeositeMatcher) Match(domain string) string { if r.domainMap[domain] { return "domain=" + domain } for _, suffix := range r.suffixList { if strings.HasSuffix(domain, suffix) { return "domain_suffix=" + suffix } } for _, keyword := range r.keywordList { if strings.Contains(domain, keyword) { return "domain_keyword=" + keyword } } for _, regexStr := range r.regexList { regex, err := regexp.Compile(regexStr) if err != nil { continue } if regex.MatchString(domain) { return "domain_regex=" + regexStr } } return "" }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/main.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/main.go
//go:build !generate package main import "github.com/sagernet/sing-box/log" func main() { if err := mainCommand.Execute(); err != nil { log.Fatal(err) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate_tls.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/cmd_generate_tls.go
package main import ( "os" "time" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/log" "github.com/spf13/cobra" ) var flagGenerateTLSKeyPairMonths int var commandGenerateTLSKeyPair = &cobra.Command{ Use: "tls-keypair <server_name>", Short: "Generate TLS self sign key pair", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { err := generateTLSKeyPair(args[0]) if err != nil { log.Fatal(err) } }, } func init() { commandGenerateTLSKeyPair.Flags().IntVarP(&flagGenerateTLSKeyPairMonths, "months", "m", 1, "Valid months") commandGenerate.AddCommand(commandGenerateTLSKeyPair) } func generateTLSKeyPair(serverName string) error { privateKeyPem, publicKeyPem, err := tls.GenerateKeyPair(time.Now, serverName, time.Now().AddDate(0, flagGenerateTLSKeyPairMonths, 0)) if err != nil { return err } os.Stdout.WriteString(string(privateKeyPem) + "\n") os.Stdout.WriteString(string(publicKeyPem) + "\n") return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/internal/convertor/adguard/convertor_test.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/internal/convertor/adguard/convertor_test.go
package adguard import ( "strings" "testing" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/route" "github.com/stretchr/testify/require" ) func TestConverter(t *testing.T) { t.Parallel() rules, err := Convert(strings.NewReader(` ||example.org^ |example.com^ example.net^ ||example.edu ||example.edu.tw^ |example.gov example.arpa @@|sagernet.example.org| ||sagernet.org^$important @@|sing-box.sagernet.org^$important `)) require.NoError(t, err) require.Len(t, rules, 1) rule, err := route.NewHeadlessRule(nil, rules[0]) require.NoError(t, err) matchDomain := []string{ "example.org", "www.example.org", "example.com", "example.net", "isexample.net", "www.example.net", "example.edu", "example.edu.cn", "example.edu.tw", "www.example.edu", "www.example.edu.cn", "example.gov", "example.gov.cn", "example.arpa", "www.example.arpa", "isexample.arpa", "example.arpa.cn", "www.example.arpa.cn", "isexample.arpa.cn", "sagernet.org", "www.sagernet.org", } notMatchDomain := []string{ "example.org.cn", "notexample.org", "example.com.cn", "www.example.com.cn", "example.net.cn", "notexample.edu", "notexample.edu.cn", "www.example.gov", "notexample.gov", "sagernet.example.org", "sing-box.sagernet.org", } for _, domain := range matchDomain { require.True(t, rule.Match(&adapter.InboundContext{ Domain: domain, }), domain) } for _, domain := range notMatchDomain { require.False(t, rule.Match(&adapter.InboundContext{ Domain: domain, }), domain) } } func TestHosts(t *testing.T) { t.Parallel() rules, err := Convert(strings.NewReader(` 127.0.0.1 localhost ::1 localhost #[IPv6] 0.0.0.0 google.com `)) require.NoError(t, err) require.Len(t, rules, 1) rule, err := route.NewHeadlessRule(nil, rules[0]) require.NoError(t, err) matchDomain := []string{ "google.com", } notMatchDomain := []string{ "www.google.com", "notgoogle.com", "localhost", } for _, domain := range matchDomain { require.True(t, rule.Match(&adapter.InboundContext{ Domain: domain, }), domain) } for _, domain := range notMatchDomain { require.False(t, rule.Match(&adapter.InboundContext{ Domain: domain, }), domain) } } func TestSimpleHosts(t *testing.T) { t.Parallel() rules, err := Convert(strings.NewReader(` example.com www.example.org `)) require.NoError(t, err) require.Len(t, rules, 1) rule, err := route.NewHeadlessRule(nil, rules[0]) require.NoError(t, err) matchDomain := []string{ "example.com", "www.example.org", } notMatchDomain := []string{ "example.com.cn", "www.example.com", "notexample.com", "example.org", } for _, domain := range matchDomain { require.True(t, rule.Match(&adapter.InboundContext{ Domain: domain, }), domain) } for _, domain := range notMatchDomain { require.False(t, rule.Match(&adapter.InboundContext{ Domain: domain, }), domain) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/cmd/sing-box/internal/convertor/adguard/convertor.go
Bcore/windows/resources/sing-box-main/cmd/sing-box/internal/convertor/adguard/convertor.go
package adguard import ( "bufio" "io" "net/netip" "os" "strconv" "strings" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" ) type agdguardRuleLine struct { ruleLine string isRawDomain bool isExclude bool isSuffix bool hasStart bool hasEnd bool isRegexp bool isImportant bool } func Convert(reader io.Reader) ([]option.HeadlessRule, error) { scanner := bufio.NewScanner(reader) var ( ruleLines []agdguardRuleLine ignoredLines int ) parseLine: for scanner.Scan() { ruleLine := scanner.Text() if ruleLine == "" || ruleLine[0] == '!' || ruleLine[0] == '#' { continue } originRuleLine := ruleLine if M.IsDomainName(ruleLine) { ruleLines = append(ruleLines, agdguardRuleLine{ ruleLine: ruleLine, isRawDomain: true, }) continue } hostLine, err := parseAdGuardHostLine(ruleLine) if err == nil { if hostLine != "" { ruleLines = append(ruleLines, agdguardRuleLine{ ruleLine: hostLine, isRawDomain: true, hasStart: true, hasEnd: true, }) } continue } if strings.HasSuffix(ruleLine, "|") { ruleLine = ruleLine[:len(ruleLine)-1] } var ( isExclude bool isSuffix bool hasStart bool hasEnd bool isRegexp bool isImportant bool ) if !strings.HasPrefix(ruleLine, "/") && strings.Contains(ruleLine, "$") { params := common.SubstringAfter(ruleLine, "$") for _, param := range strings.Split(params, ",") { paramParts := strings.Split(param, "=") var ignored bool if len(paramParts) > 0 && len(paramParts) <= 2 { switch paramParts[0] { case "app", "network": // maybe support by package_name/process_name case "dnstype": // maybe support by query_type case "important": ignored = true isImportant = true case "dnsrewrite": if len(paramParts) == 2 && M.ParseAddr(paramParts[1]).IsUnspecified() { ignored = true } } } if !ignored { ignoredLines++ log.Debug("ignored unsupported rule with modifier: ", paramParts[0], ": ", ruleLine) continue parseLine } } ruleLine = common.SubstringBefore(ruleLine, "$") } if strings.HasPrefix(ruleLine, "@@") { ruleLine = ruleLine[2:] isExclude = true } if strings.HasSuffix(ruleLine, "|") { ruleLine = ruleLine[:len(ruleLine)-1] } if strings.HasPrefix(ruleLine, "||") { ruleLine = ruleLine[2:] isSuffix = true } else if strings.HasPrefix(ruleLine, "|") { ruleLine = ruleLine[1:] hasStart = true } if strings.HasSuffix(ruleLine, "^") { ruleLine = ruleLine[:len(ruleLine)-1] hasEnd = true } if strings.HasPrefix(ruleLine, "/") && strings.HasSuffix(ruleLine, "/") { ruleLine = ruleLine[1 : len(ruleLine)-1] if ignoreIPCIDRRegexp(ruleLine) { ignoredLines++ log.Debug("ignored unsupported rule with IPCIDR regexp: ", ruleLine) continue } isRegexp = true } else { if strings.Contains(ruleLine, "://") { ruleLine = common.SubstringAfter(ruleLine, "://") } if strings.Contains(ruleLine, "/") { ignoredLines++ log.Debug("ignored unsupported rule with path: ", ruleLine) continue } if strings.Contains(ruleLine, "##") { ignoredLines++ log.Debug("ignored unsupported rule with element hiding: ", ruleLine) continue } if strings.Contains(ruleLine, "#$#") { ignoredLines++ log.Debug("ignored unsupported rule with element hiding: ", ruleLine) continue } var domainCheck string if strings.HasPrefix(ruleLine, ".") || strings.HasPrefix(ruleLine, "-") { domainCheck = "r" + ruleLine } else { domainCheck = ruleLine } if ruleLine == "" { ignoredLines++ log.Debug("ignored unsupported rule with empty domain", originRuleLine) continue } else { domainCheck = strings.ReplaceAll(domainCheck, "*", "x") if !M.IsDomainName(domainCheck) { _, ipErr := parseADGuardIPCIDRLine(ruleLine) if ipErr == nil { ignoredLines++ log.Debug("ignored unsupported rule with IPCIDR: ", ruleLine) continue } if M.ParseSocksaddr(domainCheck).Port != 0 { log.Debug("ignored unsupported rule with port: ", ruleLine) } else { log.Debug("ignored unsupported rule with invalid domain: ", ruleLine) } ignoredLines++ continue } } } ruleLines = append(ruleLines, agdguardRuleLine{ ruleLine: ruleLine, isExclude: isExclude, isSuffix: isSuffix, hasStart: hasStart, hasEnd: hasEnd, isRegexp: isRegexp, isImportant: isImportant, }) } if len(ruleLines) == 0 { return nil, E.New("AdGuard rule-set is empty or all rules are unsupported") } if common.All(ruleLines, func(it agdguardRuleLine) bool { return it.isRawDomain }) { return []option.HeadlessRule{ { Type: C.RuleTypeDefault, DefaultOptions: option.DefaultHeadlessRule{ Domain: common.Map(ruleLines, func(it agdguardRuleLine) string { return it.ruleLine }), }, }, }, nil } mapDomain := func(it agdguardRuleLine) string { ruleLine := it.ruleLine if it.isSuffix { ruleLine = "||" + ruleLine } else if it.hasStart { ruleLine = "|" + ruleLine } if it.hasEnd { ruleLine += "^" } return ruleLine } importantDomain := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return it.isImportant && !it.isRegexp && !it.isExclude }), mapDomain) importantDomainRegex := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return it.isImportant && it.isRegexp && !it.isExclude }), mapDomain) importantExcludeDomain := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return it.isImportant && !it.isRegexp && it.isExclude }), mapDomain) importantExcludeDomainRegex := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return it.isImportant && it.isRegexp && it.isExclude }), mapDomain) domain := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return !it.isImportant && !it.isRegexp && !it.isExclude }), mapDomain) domainRegex := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return !it.isImportant && it.isRegexp && !it.isExclude }), mapDomain) excludeDomain := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return !it.isImportant && !it.isRegexp && it.isExclude }), mapDomain) excludeDomainRegex := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return !it.isImportant && it.isRegexp && it.isExclude }), mapDomain) currentRule := option.HeadlessRule{ Type: C.RuleTypeDefault, DefaultOptions: option.DefaultHeadlessRule{ AdGuardDomain: domain, DomainRegex: domainRegex, }, } if len(excludeDomain) > 0 || len(excludeDomainRegex) > 0 { currentRule = option.HeadlessRule{ Type: C.RuleTypeLogical, LogicalOptions: option.LogicalHeadlessRule{ Mode: C.LogicalTypeAnd, Rules: []option.HeadlessRule{ { Type: C.RuleTypeDefault, DefaultOptions: option.DefaultHeadlessRule{ AdGuardDomain: excludeDomain, DomainRegex: excludeDomainRegex, Invert: true, }, }, currentRule, }, }, } } if len(importantDomain) > 0 || len(importantDomainRegex) > 0 { currentRule = option.HeadlessRule{ Type: C.RuleTypeLogical, LogicalOptions: option.LogicalHeadlessRule{ Mode: C.LogicalTypeOr, Rules: []option.HeadlessRule{ { Type: C.RuleTypeDefault, DefaultOptions: option.DefaultHeadlessRule{ AdGuardDomain: importantDomain, DomainRegex: importantDomainRegex, }, }, currentRule, }, }, } } if len(importantExcludeDomain) > 0 || len(importantExcludeDomainRegex) > 0 { currentRule = option.HeadlessRule{ Type: C.RuleTypeLogical, LogicalOptions: option.LogicalHeadlessRule{ Mode: C.LogicalTypeAnd, Rules: []option.HeadlessRule{ { Type: C.RuleTypeDefault, DefaultOptions: option.DefaultHeadlessRule{ AdGuardDomain: importantExcludeDomain, DomainRegex: importantExcludeDomainRegex, Invert: true, }, }, currentRule, }, }, } } log.Info("parsed rules: ", len(ruleLines), "/", len(ruleLines)+ignoredLines) return []option.HeadlessRule{currentRule}, nil } func ignoreIPCIDRRegexp(ruleLine string) bool { if strings.HasPrefix(ruleLine, "(http?:\\/\\/)") { ruleLine = ruleLine[12:] } else if strings.HasPrefix(ruleLine, "(https?:\\/\\/)") { ruleLine = ruleLine[13:] } else if strings.HasPrefix(ruleLine, "^") { ruleLine = ruleLine[1:] } else { return false } _, parseErr := strconv.ParseUint(common.SubstringBefore(ruleLine, "\\."), 10, 8) return parseErr == nil } func parseAdGuardHostLine(ruleLine string) (string, error) { idx := strings.Index(ruleLine, " ") if idx == -1 { return "", os.ErrInvalid } address, err := netip.ParseAddr(ruleLine[:idx]) if err != nil { return "", err } if !address.IsUnspecified() { return "", nil } domain := ruleLine[idx+1:] if !M.IsDomainName(domain) { return "", E.New("invalid domain name: ", domain) } return domain, nil } func parseADGuardIPCIDRLine(ruleLine string) (netip.Prefix, error) { var isPrefix bool if strings.HasSuffix(ruleLine, ".") { isPrefix = true ruleLine = ruleLine[:len(ruleLine)-1] } ruleStringParts := strings.Split(ruleLine, ".") if len(ruleStringParts) > 4 || len(ruleStringParts) < 4 && !isPrefix { return netip.Prefix{}, os.ErrInvalid } ruleParts := make([]uint8, 0, len(ruleStringParts)) for _, part := range ruleStringParts { rulePart, err := strconv.ParseUint(part, 10, 8) if err != nil { return netip.Prefix{}, err } ruleParts = append(ruleParts, uint8(rulePart)) } bitLen := len(ruleParts) * 8 for len(ruleParts) < 4 { ruleParts = append(ruleParts, 0) } return netip.PrefixFrom(netip.AddrFrom4(*(*[4]byte)(ruleParts)), bitLen), nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/box_test.go
Bcore/windows/resources/sing-box-main/test/box_test.go
package main import ( "context" "crypto/tls" "io" "net" "net/http" "testing" "time" "github.com/sagernet/quic-go" "github.com/sagernet/quic-go/http3" "github.com/sagernet/sing-box" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/bufio" "github.com/sagernet/sing/common/debug" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/protocol/socks" "github.com/stretchr/testify/require" "go.uber.org/goleak" ) func TestMain(m *testing.M) { goleak.VerifyTestMain(m) } func startInstance(t *testing.T, options option.Options) *box.Box { if debug.Enabled { options.Log = &option.LogOptions{ Level: "trace", } } else { options.Log = &option.LogOptions{ Level: "warning", } } // ctx := context.Background() ctx, cancel := context.WithCancel(context.Background()) var instance *box.Box var err error for retry := 0; retry < 3; retry++ { instance, err = box.New(box.Options{ Context: ctx, Options: options, }) require.NoError(t, err) err = instance.Start() if err != nil { time.Sleep(time.Second) continue } break } require.NoError(t, err) t.Cleanup(func() { instance.Close() cancel() }) return instance } func testSuit(t *testing.T, clientPort uint16, testPort uint16) { dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "") dialTCP := func() (net.Conn, error) { return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } dialUDP := func() (net.PacketConn, error) { return dialer.ListenPacket(context.Background(), M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } require.NoError(t, testPingPongWithConn(t, testPort, dialTCP)) require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP)) require.NoError(t, testLargeDataWithConn(t, testPort, dialTCP)) require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP)) // require.NoError(t, testPacketConnTimeout(t, dialUDP)) } func testQUIC(t *testing.T, clientPort uint16) { dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "") client := &http.Client{ Transport: &http3.RoundTripper{ Dial: func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) { destination := M.ParseSocksaddr(addr) udpConn, err := dialer.DialContext(ctx, N.NetworkUDP, destination) if err != nil { return nil, err } return quic.DialEarly(ctx, udpConn.(net.PacketConn), destination, tlsCfg, cfg) }, }, } response, err := client.Get("https://cloudflare.com/cdn-cgi/trace") require.NoError(t, err) require.Equal(t, http.StatusOK, response.StatusCode) content, err := io.ReadAll(response.Body) require.NoError(t, err) println(string(content)) } func testSuitLargeUDP(t *testing.T, clientPort uint16, testPort uint16) { dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "") dialTCP := func() (net.Conn, error) { return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } dialUDP := func() (net.PacketConn, error) { return dialer.ListenPacket(context.Background(), M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } require.NoError(t, testPingPongWithConn(t, testPort, dialTCP)) require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP)) require.NoError(t, testLargeDataWithConn(t, testPort, dialTCP)) require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP)) require.NoError(t, testLargeDataWithPacketConnSize(t, testPort, 4096, dialUDP)) } func testTCP(t *testing.T, clientPort uint16, testPort uint16) { dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "") dialTCP := func() (net.Conn, error) { return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } require.NoError(t, testPingPongWithConn(t, testPort, dialTCP)) require.NoError(t, testLargeDataWithConn(t, testPort, dialTCP)) } func testSuitSimple(t *testing.T, clientPort uint16, testPort uint16) { dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "") dialTCP := func() (net.Conn, error) { return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } dialUDP := func() (net.PacketConn, error) { return dialer.ListenPacket(context.Background(), M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } require.NoError(t, testPingPongWithConn(t, testPort, dialTCP)) require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP)) require.NoError(t, testPingPongWithConn(t, testPort, dialTCP)) require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP)) } func testSuitSimple1(t *testing.T, clientPort uint16, testPort uint16) { dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "") dialTCP := func() (net.Conn, error) { return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } dialUDP := func() (net.PacketConn, error) { return dialer.ListenPacket(context.Background(), M.ParseSocksaddrHostPort("127.0.0.1", testPort)) } require.NoError(t, testPingPongWithConn(t, testPort, dialTCP)) if !C.IsDarwin { require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP)) } require.NoError(t, testPingPongWithConn(t, testPort, dialTCP)) if !C.IsDarwin { require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP)) } } func testSuitWg(t *testing.T, clientPort uint16, testPort uint16) { dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "") dialTCP := func() (net.Conn, error) { return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("10.0.0.1", testPort)) } dialUDP := func() (net.PacketConn, error) { conn, err := dialer.DialContext(context.Background(), "udp", M.ParseSocksaddrHostPort("10.0.0.1", testPort)) if err != nil { return nil, err } return bufio.NewUnbindPacketConn(conn), nil } require.NoError(t, testPingPongWithConn(t, testPort, dialTCP)) require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP)) require.NoError(t, testLargeDataWithConn(t, testPort, dialTCP)) require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP)) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/tfo_test.go
Bcore/windows/resources/sing-box-main/test/tfo_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks/shadowaead" ) func TestTCPSlowOpen(t *testing.T) { method := shadowaead.List[0] password := mkBase64(t, 16) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, TCPFastOpen: true, }, Method: method, Password: password, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeShadowsocks, Tag: "ss-out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, DialerOptions: option.DialerOptions{ TCPFastOpen: true, }, Method: method, Password: password, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/tls_test.go
Bcore/windows/resources/sing-box-main/test/tls_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" ) func TestUTLS(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTrojan, TrojanOptions: option.TrojanInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TrojanUser{ { Name: "sekai", Password: "password", }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTrojan, Tag: "trojan-out", TrojanOptions: option.TrojanOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Password: "password", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, UTLS: &option.OutboundUTLSOptions{ Enabled: true, Fingerprint: "chrome", }, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "trojan-out", }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/wrapper_test.go
Bcore/windows/resources/sing-box-main/test/wrapper_test.go
package main import ( "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/stretchr/testify/require" ) func TestOptionsWrapper(t *testing.T) { inbound := option.Inbound{ Type: C.TypeHTTP, HTTPOptions: option.HTTPMixedInboundOptions{ InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, }, }, }, } rawOptions, err := inbound.RawOptions() require.NoError(t, err) tlsOptionsWrapper, loaded := rawOptions.(option.InboundTLSOptionsWrapper) require.True(t, loaded, "find inbound tls options") tlsOptions := tlsOptionsWrapper.TakeInboundTLSOptions() require.NotNil(t, tlsOptions, "find inbound tls options") tlsOptions.Enabled = false tlsOptionsWrapper.ReplaceInboundTLSOptions(tlsOptions) require.False(t, inbound.HTTPOptions.TLS.Enabled, "replace tls enabled") }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/clash_darwin_test.go
Bcore/windows/resources/sing-box-main/test/clash_darwin_test.go
package main import ( "errors" "fmt" "net" "net/netip" "syscall" "golang.org/x/net/route" ) func defaultRouteIP() (netip.Addr, error) { idx, err := defaultRouteInterfaceIndex() if err != nil { return netip.Addr{}, err } iface, err := net.InterfaceByIndex(idx) if err != nil { return netip.Addr{}, err } addrs, err := iface.Addrs() if err != nil { return netip.Addr{}, err } for _, addr := range addrs { ip := addr.(*net.IPNet).IP if ip.To4() != nil { return netip.AddrFrom4(*(*[4]byte)(ip)), nil } } return netip.Addr{}, errors.New("no ipv4 addr") } func defaultRouteInterfaceIndex() (int, error) { rib, err := route.FetchRIB(syscall.AF_UNSPEC, syscall.NET_RT_DUMP2, 0) if err != nil { return 0, fmt.Errorf("route.FetchRIB: %w", err) } msgs, err := route.ParseRIB(syscall.NET_RT_IFLIST2, rib) if err != nil { return 0, fmt.Errorf("route.ParseRIB: %w", err) } for _, message := range msgs { routeMessage := message.(*route.RouteMessage) if routeMessage.Flags&(syscall.RTF_UP|syscall.RTF_GATEWAY|syscall.RTF_STATIC) == 0 { continue } addresses := routeMessage.Addrs destination, ok := addresses[0].(*route.Inet4Addr) if !ok { continue } if destination.IP != [4]byte{0, 0, 0, 0} { continue } switch addresses[1].(type) { case *route.Inet4Addr: return routeMessage.Index, nil default: continue } } return 0, fmt.Errorf("ambiguous gateway interfaces found") }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/brutal_test.go
Bcore/windows/resources/sing-box-main/test/brutal_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks/shadowaead_2022" "github.com/gofrs/uuid/v5" ) func TestBrutalShadowsocks(t *testing.T) { method := shadowaead_2022.List[0] password := mkBase64(t, 16) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Method: method, Password: password, Multiplex: &option.InboundMultiplexOptions{ Enabled: true, Brutal: &option.BrutalOptions{ Enabled: true, UpMbps: 100, DownMbps: 100, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeShadowsocks, Tag: "ss-out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: method, Password: password, Multiplex: &option.OutboundMultiplexOptions{ Enabled: true, Protocol: "smux", Padding: true, Brutal: &option.BrutalOptions{ Enabled: true, UpMbps: 100, DownMbps: 100, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestBrutalTrojan(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") password := mkBase64(t, 16) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTrojan, TrojanOptions: option.TrojanInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TrojanUser{{Password: password}}, Multiplex: &option.InboundMultiplexOptions{ Enabled: true, Brutal: &option.BrutalOptions{ Enabled: true, UpMbps: 100, DownMbps: 100, }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTrojan, Tag: "ss-out", TrojanOptions: option.TrojanOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Password: password, Multiplex: &option.OutboundMultiplexOptions{ Enabled: true, Protocol: "yamux", Padding: true, Brutal: &option.BrutalOptions{ Enabled: true, UpMbps: 100, DownMbps: 100, }, }, OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestBrutalVMess(t *testing.T) { user, _ := uuid.NewV4() startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{{UUID: user.String()}}, Multiplex: &option.InboundMultiplexOptions{ Enabled: true, Brutal: &option.BrutalOptions{ Enabled: true, UpMbps: 100, DownMbps: 100, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeVMess, Tag: "ss-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: user.String(), Multiplex: &option.OutboundMultiplexOptions{ Enabled: true, Protocol: "h2mux", Padding: true, Brutal: &option.BrutalOptions{ Enabled: true, UpMbps: 100, DownMbps: 100, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestBrutalVLESS(t *testing.T) { user, _ := uuid.NewV4() startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeVLESS, VLESSOptions: option.VLESSInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VLESSUser{{UUID: user.String()}}, Multiplex: &option.InboundMultiplexOptions{ Enabled: true, Brutal: &option.BrutalOptions{ Enabled: true, UpMbps: 100, DownMbps: 100, }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "google.com", Reality: &option.InboundRealityOptions{ Enabled: true, Handshake: option.InboundRealityHandshakeOptions{ ServerOptions: option.ServerOptions{ Server: "google.com", ServerPort: 443, }, }, ShortID: []string{"0123456789abcdef"}, PrivateKey: "UuMBgl7MXTPx9inmQp2UC7Jcnwc6XYbwDNebonM-FCc", }, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeVLESS, Tag: "ss-out", VLESSOptions: option.VLESSOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: user.String(), OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "google.com", Reality: &option.OutboundRealityOptions{ Enabled: true, ShortID: "0123456789abcdef", PublicKey: "jNXHt1yRo0vDuchQlIP6Z0ZvjT3KtzVI-T4E7RoLJS0", }, UTLS: &option.OutboundUTLSOptions{ Enabled: true, }, }, }, Multiplex: &option.OutboundMultiplexOptions{ Enabled: true, Protocol: "h2mux", Padding: true, Brutal: &option.BrutalOptions{ Enabled: true, UpMbps: 100, DownMbps: 100, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/v2ray_ws_test.go
Bcore/windows/resources/sing-box-main/test/v2ray_ws_test.go
package main import ( "net/netip" "os" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/gofrs/uuid/v5" "github.com/spyzhov/ajson" "github.com/stretchr/testify/require" ) func TestV2RayWebsocket(t *testing.T) { t.Run("self", func(t *testing.T) { testV2RayTransportSelf(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeWebsocket, }) }) t.Run("self-early-data", func(t *testing.T) { testV2RayTransportSelf(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeWebsocket, WebsocketOptions: option.V2RayWebsocketOptions{ MaxEarlyData: 2048, }, }) }) t.Run("self-xray-early-data", func(t *testing.T) { testV2RayTransportSelf(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeWebsocket, WebsocketOptions: option.V2RayWebsocketOptions{ MaxEarlyData: 2048, EarlyDataHeaderName: "Sec-WebSocket-Protocol", }, }) }) t.Run("inbound", func(t *testing.T) { testV2RayWebsocketInbound(t, 0, "") }) t.Run("inbound-early-data", func(t *testing.T) { testV2RayWebsocketInbound(t, 2048, "") }) t.Run("inbound-xray-early-data", func(t *testing.T) { testV2RayWebsocketInbound(t, 2048, "Sec-WebSocket-Protocol") }) t.Run("outbound", func(t *testing.T) { testV2RayWebsocketOutbound(t, 0, "") }) t.Run("outbound-early-data", func(t *testing.T) { testV2RayWebsocketOutbound(t, 2048, "") }) t.Run("outbound-xray-early-data", func(t *testing.T) { testV2RayWebsocketOutbound(t, 2048, "Sec-WebSocket-Protocol") }) } func testV2RayWebsocketInbound(t *testing.T, maxEarlyData uint32, earlyDataHeaderName string) { userId, err := uuid.DefaultGenerator.NewV4() require.NoError(t, err) _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: userId.String(), }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, Transport: &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeWebsocket, WebsocketOptions: option.V2RayWebsocketOptions{ MaxEarlyData: maxEarlyData, EarlyDataHeaderName: earlyDataHeaderName, }, }, }, }, }, }) content, err := os.ReadFile("config/vmess-ws-client.json") require.NoError(t, err) config, err := ajson.Unmarshal(content) require.NoError(t, err) config.MustKey("inbounds").MustIndex(0).MustKey("port").SetNumeric(float64(clientPort)) outbound := config.MustKey("outbounds").MustIndex(0) settings := outbound.MustKey("settings").MustKey("vnext").MustIndex(0) settings.MustKey("port").SetNumeric(float64(serverPort)) user := settings.MustKey("users").MustIndex(0) user.MustKey("id").SetString(userId.String()) wsSettings := outbound.MustKey("streamSettings").MustKey("wsSettings") wsSettings.MustKey("maxEarlyData").SetNumeric(float64(maxEarlyData)) wsSettings.MustKey("earlyDataHeaderName").SetString(earlyDataHeaderName) content, err = ajson.Marshal(config) require.NoError(t, err) startDockerContainer(t, DockerOptions{ Image: ImageV2RayCore, Ports: []uint16{serverPort, testPort}, EntryPoint: "v2ray", Cmd: []string{"run"}, Stdin: content, Bind: map[string]string{ certPem: "/path/to/certificate.crt", keyPem: "/path/to/private.key", }, }) testSuitSimple(t, clientPort, testPort) } func testV2RayWebsocketOutbound(t *testing.T, maxEarlyData uint32, earlyDataHeaderName string) { userId, err := uuid.DefaultGenerator.NewV4() require.NoError(t, err) _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") content, err := os.ReadFile("config/vmess-ws-server.json") require.NoError(t, err) config, err := ajson.Unmarshal(content) require.NoError(t, err) inbound := config.MustKey("inbounds").MustIndex(0) inbound.MustKey("port").SetNumeric(float64(serverPort)) inbound.MustKey("settings").MustKey("clients").MustIndex(0).MustKey("id").SetString(userId.String()) wsSettings := inbound.MustKey("streamSettings").MustKey("wsSettings") wsSettings.MustKey("maxEarlyData").SetNumeric(float64(maxEarlyData)) wsSettings.MustKey("earlyDataHeaderName").SetString(earlyDataHeaderName) content, err = ajson.Marshal(config) require.NoError(t, err) startDockerContainer(t, DockerOptions{ Image: ImageV2RayCore, Ports: []uint16{serverPort, testPort}, EntryPoint: "v2ray", Cmd: []string{"run"}, Stdin: content, Env: []string{"V2RAY_VMESS_AEAD_FORCED=false"}, Bind: map[string]string{ certPem: "/path/to/certificate.crt", keyPem: "/path/to/private.key", }, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeVMess, Tag: "vmess-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: userId.String(), Security: "zero", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, Transport: &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeWebsocket, WebsocketOptions: option.V2RayWebsocketOptions{ MaxEarlyData: maxEarlyData, EarlyDataHeaderName: earlyDataHeaderName, }, }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/direct_test.go
Bcore/windows/resources/sing-box-main/test/direct_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" ) // Since this is a feature one-off added by outsiders, I won't address these anymore. func _TestProxyProtocol(t *testing.T) { startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeDirect, DirectOptions: option.DirectInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, ProxyProtocol: true, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeDirect, Tag: "proxy-out", DirectOptions: option.DirectOutboundOptions{ OverrideAddress: "127.0.0.1", OverridePort: serverPort, ProxyProtocol: 2, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "proxy-out", }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/clash_test.go
Bcore/windows/resources/sing-box-main/test/clash_test.go
package main import ( "context" "crypto/md5" "crypto/rand" "errors" "io" "net" _ "net/http/pprof" "net/netip" "sync" "testing" "time" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/common/control" F "github.com/sagernet/sing/common/format" "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // kanged from clash const ( ImageShadowsocksRustServer = "ghcr.io/shadowsocks/ssserver-rust:latest" ImageShadowsocksRustClient = "ghcr.io/shadowsocks/sslocal-rust:latest" ImageV2RayCore = "v2fly/v2fly-core:latest" ImageTrojan = "trojangfw/trojan:latest" ImageNaive = "pocat/naiveproxy:client" ImageBoringTun = "ghcr.io/ntkme/boringtun:edge" ImageHysteria = "tobyxdd/hysteria:v1.3.5" ImageHysteria2 = "tobyxdd/hysteria:v2" ImageNginx = "nginx:stable" ImageShadowTLS = "ghcr.io/ihciah/shadow-tls:latest" ImageXRayCore = "teddysun/xray:latest" ImageShadowsocksLegacy = "mritd/shadowsocks:latest" ImageTUICServer = "kilvn/tuic-server:latest" ImageTUICClient = "kilvn/tuic-client:latest" ) var allImages = []string{ ImageShadowsocksRustServer, ImageShadowsocksRustClient, ImageV2RayCore, ImageTrojan, ImageNaive, ImageBoringTun, ImageHysteria, ImageHysteria2, ImageNginx, ImageShadowTLS, ImageXRayCore, ImageShadowsocksLegacy, ImageTUICServer, ImageTUICClient, } var localIP = netip.MustParseAddr("127.0.0.1") func init() { dockerClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { panic(err) } defer dockerClient.Close() list, err := dockerClient.ImageList(context.Background(), types.ImageListOptions{All: true}) if err != nil { log.Warn(err) return } imageExist := func(image string) bool { for _, item := range list { for _, tag := range item.RepoTags { if image == tag { return true } } } return false } for _, image := range allImages { if imageExist(image) { continue } log.Info("pulling image: ", image) imageStream, err := dockerClient.ImagePull(context.Background(), image, types.ImagePullOptions{}) if err != nil { panic(err) } io.Copy(io.Discard, imageStream) } } func newPingPongPair() (chan []byte, chan []byte, func(t *testing.T) error) { pingCh := make(chan []byte) pongCh := make(chan []byte) test := func(t *testing.T) error { defer close(pingCh) defer close(pongCh) pingOpen := false pongOpen := false var recv []byte for { if pingOpen && pongOpen { break } select { case recv, pingOpen = <-pingCh: assert.True(t, pingOpen) assert.Equal(t, []byte("ping"), recv) case recv, pongOpen = <-pongCh: assert.True(t, pongOpen) assert.Equal(t, []byte("pong"), recv) case <-time.After(10 * time.Second): return errors.New("timeout") } } return nil } return pingCh, pongCh, test } func newLargeDataPair() (chan hashPair, chan hashPair, func(t *testing.T) error) { pingCh := make(chan hashPair) pongCh := make(chan hashPair) test := func(t *testing.T) error { defer close(pingCh) defer close(pongCh) pingOpen := false pongOpen := false var serverPair hashPair var clientPair hashPair for { if pingOpen && pongOpen { break } select { case serverPair, pingOpen = <-pingCh: assert.True(t, pingOpen) case clientPair, pongOpen = <-pongCh: assert.True(t, pongOpen) case <-time.After(10 * time.Second): return errors.New("timeout") } } assert.Equal(t, serverPair.recvHash, clientPair.sendHash) assert.Equal(t, serverPair.sendHash, clientPair.recvHash) return nil } return pingCh, pongCh, test } func testPingPongWithConn(t *testing.T, port uint16, cc func() (net.Conn, error)) error { l, err := listen("tcp", ":"+F.ToString(port)) if err != nil { return err } defer l.Close() c, err := cc() if err != nil { return err } defer c.Close() pingCh, pongCh, test := newPingPongPair() go func() { c, err := l.Accept() if err != nil { return } buf := make([]byte, 4) if _, err := io.ReadFull(c, buf); err != nil { return } pingCh <- buf if _, err := c.Write([]byte("pong")); err != nil { return } }() go func() { if _, err := c.Write([]byte("ping")); err != nil { return } buf := make([]byte, 4) if _, err := io.ReadFull(c, buf); err != nil { return } pongCh <- buf }() return test(t) } func testPingPongWithPacketConn(t *testing.T, port uint16, pcc func() (net.PacketConn, error)) error { l, err := listenPacket("udp", ":"+F.ToString(port)) if err != nil { return err } defer l.Close() rAddr := &net.UDPAddr{IP: localIP.AsSlice(), Port: int(port)} pingCh, pongCh, test := newPingPongPair() go func() { buf := make([]byte, 1024) n, rAddr, err := l.ReadFrom(buf) if err != nil { return } pingCh <- buf[:n] if _, err := l.WriteTo([]byte("pong"), rAddr); err != nil { return } }() pc, err := pcc() if err != nil { return err } defer pc.Close() go func() { if _, err := pc.WriteTo([]byte("ping"), rAddr); err != nil { return } buf := make([]byte, 1024) n, _, err := pc.ReadFrom(buf) if err != nil { return } pongCh <- buf[:n] }() return test(t) } type hashPair struct { sendHash map[int][]byte recvHash map[int][]byte } func testLargeDataWithConn(t *testing.T, port uint16, cc func() (net.Conn, error)) error { l, err := listen("tcp", ":"+F.ToString(port)) require.NoError(t, err) defer l.Close() times := 100 chunkSize := int64(64 * 1024) pingCh, pongCh, test := newLargeDataPair() writeRandData := func(conn net.Conn) (map[int][]byte, error) { buf := make([]byte, chunkSize) hashMap := map[int][]byte{} for i := 0; i < times; i++ { if _, err := rand.Read(buf[1:]); err != nil { return nil, err } buf[0] = byte(i) hash := md5.Sum(buf) hashMap[i] = hash[:] if _, err := conn.Write(buf); err != nil { return nil, err } } return hashMap, nil } c, err := cc() if err != nil { return err } defer c.Close() go func() { c, err := l.Accept() if err != nil { return } defer c.Close() hashMap := map[int][]byte{} buf := make([]byte, chunkSize) for i := 0; i < times; i++ { _, err := io.ReadFull(c, buf) if err != nil { t.Log(err.Error()) return } hash := md5.Sum(buf) hashMap[int(buf[0])] = hash[:] } sendHash, err := writeRandData(c) if err != nil { t.Log(err.Error()) return } pingCh <- hashPair{ sendHash: sendHash, recvHash: hashMap, } }() go func() { sendHash, err := writeRandData(c) if err != nil { t.Log(err.Error()) return } hashMap := map[int][]byte{} buf := make([]byte, chunkSize) for i := 0; i < times; i++ { _, err := io.ReadFull(c, buf) if err != nil { t.Log(err.Error()) return } hash := md5.Sum(buf) hashMap[int(buf[0])] = hash[:] } pongCh <- hashPair{ sendHash: sendHash, recvHash: hashMap, } }() return test(t) } func testLargeDataWithPacketConn(t *testing.T, port uint16, pcc func() (net.PacketConn, error)) error { return testLargeDataWithPacketConnSize(t, port, 1500, pcc) } func testLargeDataWithPacketConnSize(t *testing.T, port uint16, chunkSize int, pcc func() (net.PacketConn, error)) error { l, err := listenPacket("udp", ":"+F.ToString(port)) if err != nil { return err } defer l.Close() rAddr := &net.UDPAddr{IP: localIP.AsSlice(), Port: int(port)} times := 50 pingCh, pongCh, test := newLargeDataPair() writeRandData := func(pc net.PacketConn, addr net.Addr) (map[int][]byte, error) { hashMap := map[int][]byte{} mux := sync.Mutex{} for i := 0; i < times; i++ { buf := make([]byte, chunkSize) if _, err := rand.Read(buf[1:]); err != nil { t.Log(err.Error()) continue } buf[0] = byte(i) hash := md5.Sum(buf) mux.Lock() hashMap[i] = hash[:] mux.Unlock() if _, err := pc.WriteTo(buf, addr); err != nil { t.Log(err.Error()) } time.Sleep(10 * time.Millisecond) } return hashMap, nil } go func() { var rAddr net.Addr hashMap := map[int][]byte{} buf := make([]byte, 64*1024) for i := 0; i < times; i++ { _, rAddr, err = l.ReadFrom(buf) if err != nil { t.Log(err.Error()) return } hash := md5.Sum(buf[:chunkSize]) hashMap[int(buf[0])] = hash[:] } sendHash, err := writeRandData(l, rAddr) if err != nil { t.Log(err.Error()) return } pingCh <- hashPair{ sendHash: sendHash, recvHash: hashMap, } }() pc, err := pcc() if err != nil { return err } defer pc.Close() go func() { sendHash, err := writeRandData(pc, rAddr) if err != nil { t.Log(err.Error()) return } hashMap := map[int][]byte{} buf := make([]byte, 64*1024) for i := 0; i < times; i++ { _, _, err := pc.ReadFrom(buf) if err != nil { t.Log(err.Error()) return } hash := md5.Sum(buf[:chunkSize]) hashMap[int(buf[0])] = hash[:] } pongCh <- hashPair{ sendHash: sendHash, recvHash: hashMap, } }() return test(t) } func testPacketConnTimeout(t *testing.T, pcc func() (net.PacketConn, error)) error { pc, err := pcc() if err != nil { return err } err = pc.SetReadDeadline(time.Now().Add(time.Millisecond * 300)) require.NoError(t, err) errCh := make(chan error, 1) go func() { buf := make([]byte, 1024) _, _, err := pc.ReadFrom(buf) errCh <- err }() select { case <-errCh: return nil case <-time.After(time.Second * 10): return errors.New("timeout") } } func listen(network, address string) (net.Listener, error) { var lc net.ListenConfig lc.Control = control.ReuseAddr() var lastErr error for i := 0; i < 5; i++ { l, err := lc.Listen(context.Background(), network, address) if err == nil { return l, nil } lastErr = err time.Sleep(5 * time.Millisecond) } return nil, lastErr } func listenPacket(network, address string) (net.PacketConn, error) { var lc net.ListenConfig lc.Control = control.ReuseAddr() var lastErr error for i := 0; i < 5; i++ { l, err := lc.ListenPacket(context.Background(), network, address) if err == nil { return l, nil } lastErr = err time.Sleep(5 * time.Millisecond) } return nil, lastErr }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/shadowtls_test.go
Bcore/windows/resources/sing-box-main/test/shadowtls_test.go
package main import ( "context" "net" "net/http" "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks/shadowaead_2022" F "github.com/sagernet/sing/common/format" "github.com/stretchr/testify/require" ) func TestShadowTLS(t *testing.T) { t.Run("v1", func(t *testing.T) { testShadowTLS(t, 1, "", false) }) t.Run("v2", func(t *testing.T) { testShadowTLS(t, 2, "hello", false) }) t.Run("v3", func(t *testing.T) { testShadowTLS(t, 3, "hello", false) }) t.Run("v2-utls", func(t *testing.T) { testShadowTLS(t, 2, "hello", true) }) t.Run("v3-utls", func(t *testing.T) { testShadowTLS(t, 3, "hello", true) }) } func testShadowTLS(t *testing.T, version int, password string, utlsEanbled bool) { method := shadowaead_2022.List[0] ssPassword := mkBase64(t, 16) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowTLS, Tag: "in", ShadowTLSOptions: option.ShadowTLSInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, Detour: "detour", }, Handshake: option.ShadowTLSHandshakeOptions{ ServerOptions: option.ServerOptions{ Server: "google.com", ServerPort: 443, }, }, Version: version, Password: password, Users: []option.ShadowTLSUser{{Password: password}}, }, }, { Type: C.TypeShadowsocks, Tag: "detour", ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: otherPort, }, Method: method, Password: ssPassword, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksOutboundOptions{ Method: method, Password: ssPassword, DialerOptions: option.DialerOptions{ Detour: "detour", }, }, }, { Type: C.TypeShadowTLS, Tag: "detour", ShadowTLSOptions: option.ShadowTLSOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "google.com", UTLS: &option.OutboundUTLSOptions{ Enabled: utlsEanbled, }, }, }, Version: version, Password: password, }, }, { Type: C.TypeDirect, Tag: "direct", }, }, Route: &option.RouteOptions{ Rules: []option.Rule{{ DefaultOptions: option.DefaultRule{ Inbound: []string{"detour"}, Outbound: "direct", }, }}, }, }) testTCP(t, clientPort, testPort) } func TestShadowTLSFallback(t *testing.T) { startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeShadowTLS, ShadowTLSOptions: option.ShadowTLSInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Handshake: option.ShadowTLSHandshakeOptions{ ServerOptions: option.ServerOptions{ Server: "google.com", ServerPort: 443, }, }, Version: 3, Users: []option.ShadowTLSUser{ {Password: "hello"}, }, }, }, }, }) client := &http.Client{ Transport: &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, network, "127.0.0.1:"+F.ToString(serverPort)) }, }, } response, err := client.Get("https://google.com") require.NoError(t, err) require.Equal(t, response.StatusCode, 200) response.Body.Close() client.CloseIdleConnections() } func TestShadowTLSInbound(t *testing.T) { method := shadowaead_2022.List[0] password := mkBase64(t, 16) startDockerContainer(t, DockerOptions{ Image: ImageShadowTLS, Ports: []uint16{serverPort, otherPort}, EntryPoint: "shadow-tls", Cmd: []string{"--v3", "--threads", "1", "client", "--listen", "0.0.0.0:" + F.ToString(otherPort), "--server", "127.0.0.1:" + F.ToString(serverPort), "--sni", "google.com", "--password", password}, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowTLS, ShadowTLSOptions: option.ShadowTLSInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, Detour: "detour", }, Handshake: option.ShadowTLSHandshakeOptions{ ServerOptions: option.ServerOptions{ Server: "google.com", ServerPort: 443, }, }, Version: 3, Users: []option.ShadowTLSUser{ {Password: password}, }, }, }, { Type: C.TypeShadowsocks, Tag: "detour", ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), }, Method: method, Password: password, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeShadowsocks, Tag: "out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: otherPort, }, Method: method, Password: password, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{{ DefaultOptions: option.DefaultRule{ Inbound: []string{"in"}, Outbound: "out", }, }}, }, }) testTCP(t, clientPort, testPort) } func TestShadowTLSOutbound(t *testing.T) { method := shadowaead_2022.List[0] password := mkBase64(t, 16) startDockerContainer(t, DockerOptions{ Image: ImageShadowTLS, Ports: []uint16{serverPort, otherPort}, EntryPoint: "shadow-tls", Cmd: []string{"--v3", "--threads", "1", "server", "--listen", "0.0.0.0:" + F.ToString(serverPort), "--server", "127.0.0.1:" + F.ToString(otherPort), "--tls", "google.com:443", "--password", "hello"}, Env: []string{"RUST_LOG=trace"}, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowsocks, Tag: "detour", ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: otherPort, }, Method: method, Password: password, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksOutboundOptions{ Method: method, Password: password, DialerOptions: option.DialerOptions{ Detour: "detour", }, }, }, { Type: C.TypeShadowTLS, Tag: "detour", ShadowTLSOptions: option.ShadowTLSOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "google.com", }, }, Version: 3, Password: "hello", }, }, { Type: C.TypeDirect, Tag: "direct", }, }, Route: &option.RouteOptions{ Rules: []option.Rule{{ DefaultOptions: option.DefaultRule{ Inbound: []string{"detour"}, Outbound: "direct", }, }}, }, }) testTCP(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/shadowsocks_legacy_test.go
Bcore/windows/resources/sing-box-main/test/shadowsocks_legacy_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks2/shadowstream" F "github.com/sagernet/sing/common/format" ) func TestShadowsocksLegacy(t *testing.T) { testShadowsocksLegacy(t, shadowstream.MethodList[0]) } func testShadowsocksLegacy(t *testing.T, method string) { startDockerContainer(t, DockerOptions{ Image: ImageShadowsocksLegacy, Ports: []uint16{serverPort}, Env: []string{ "SS_MODULE=ss-server", F.ToString("SS_CONFIG=-s 0.0.0.0 -u -p 10000 -m ", method, " -k FzcLbKs2dY9mhL"), }, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: method, Password: "FzcLbKs2dY9mhL", }, }, }, }) testSuitSimple(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/inbound_detour_test.go
Bcore/windows/resources/sing-box-main/test/inbound_detour_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks/shadowaead_2022" ) func TestChainedInbound(t *testing.T) { method := shadowaead_2022.List[0] password := mkBase64(t, 16) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, Detour: "detour", }, Method: method, Password: password, }, }, { Type: C.TypeShadowsocks, Tag: "detour", ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: otherPort, }, Method: method, Password: password, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeShadowsocks, Tag: "ss-out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ Method: method, Password: password, DialerOptions: option.DialerOptions{ Detour: "detour-out", }, }, }, { Type: C.TypeShadowsocks, Tag: "detour-out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: method, Password: password, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testTCP(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/hysteria_test.go
Bcore/windows/resources/sing-box-main/test/hysteria_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" ) func TestHysteriaSelf(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeHysteria, HysteriaOptions: option.HysteriaInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, UpMbps: 100, DownMbps: 100, Users: []option.HysteriaUser{{ AuthString: "password", }}, Obfs: "fuck me till the daylight", InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeHysteria, Tag: "hy-out", HysteriaOptions: option.HysteriaOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UpMbps: 100, DownMbps: 100, AuthString: "password", Obfs: "fuck me till the daylight", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "hy-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestHysteriaInbound(t *testing.T) { caPem, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeHysteria, HysteriaOptions: option.HysteriaInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, UpMbps: 100, DownMbps: 100, Users: []option.HysteriaUser{{ AuthString: "password", }}, Obfs: "fuck me till the daylight", InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, }) startDockerContainer(t, DockerOptions{ Image: ImageHysteria, Ports: []uint16{serverPort, clientPort}, Cmd: []string{"-c", "/etc/hysteria/config.json", "client"}, Bind: map[string]string{ "hysteria-client.json": "/etc/hysteria/config.json", caPem: "/etc/hysteria/ca.pem", }, }) testSuit(t, clientPort, testPort) } func TestHysteriaOutbound(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startDockerContainer(t, DockerOptions{ Image: ImageHysteria, Ports: []uint16{testPort}, Cmd: []string{"-c", "/etc/hysteria/config.json", "server"}, Bind: map[string]string{ "hysteria-server.json": "/etc/hysteria/config.json", certPem: "/etc/hysteria/cert.pem", keyPem: "/etc/hysteria/key.pem", }, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeHysteria, HysteriaOptions: option.HysteriaOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UpMbps: 100, DownMbps: 100, AuthString: "password", Obfs: "fuck me till the daylight", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, }) testSuitSimple1(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/wireguard_test.go
Bcore/windows/resources/sing-box-main/test/wireguard_test.go
package main import ( "net/netip" "testing" "time" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" ) func _TestWireGuard(t *testing.T) { startDockerContainer(t, DockerOptions{ Image: ImageBoringTun, Cap: []string{"MKNOD", "NET_ADMIN", "NET_RAW"}, Ports: []uint16{serverPort, testPort}, Bind: map[string]string{ "wireguard.conf": "/etc/wireguard/wg0.conf", }, Cmd: []string{"wg0"}, }) time.Sleep(5 * time.Second) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeWireGuard, WireGuardOptions: option.WireGuardOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, LocalAddress: []netip.Prefix{netip.MustParsePrefix("10.0.0.2/32")}, PrivateKey: "qGnwlkZljMxeECW8fbwAWdvgntnbK7B8UmMFl3zM0mk=", PeerPublicKey: "QsdcBm+oJw2oNv0cIFXLIq1E850lgTBonup4qnKEQBg=", }, }, }, }) testSuitWg(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/hysteria2_test.go
Bcore/windows/resources/sing-box-main/test/hysteria2_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-quic/hysteria2" ) func TestHysteria2Self(t *testing.T) { t.Run("self", func(t *testing.T) { testHysteria2Self(t, "") }) t.Run("self-salamander", func(t *testing.T) { testHysteria2Self(t, "password") }) } func testHysteria2Self(t *testing.T, salamanderPassword string) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") var obfs *option.Hysteria2Obfs if salamanderPassword != "" { obfs = &option.Hysteria2Obfs{ Type: hysteria2.ObfsTypeSalamander, Password: salamanderPassword, } } startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeHysteria2, Hysteria2Options: option.Hysteria2InboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, UpMbps: 100, DownMbps: 100, Obfs: obfs, Users: []option.Hysteria2User{{ Password: "password", }}, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeHysteria2, Tag: "hy2-out", Hysteria2Options: option.Hysteria2OutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UpMbps: 100, DownMbps: 100, Obfs: obfs, Password: "password", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { Type: C.RuleTypeDefault, DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "hy2-out", }, }, }, }, }) testSuitLargeUDP(t, clientPort, testPort) } func TestHysteria2Inbound(t *testing.T) { caPem, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeHysteria2, Hysteria2Options: option.Hysteria2InboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Obfs: &option.Hysteria2Obfs{ Type: hysteria2.ObfsTypeSalamander, Password: "cry_me_a_r1ver", }, Users: []option.Hysteria2User{{ Password: "password", }}, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, }) startDockerContainer(t, DockerOptions{ Image: ImageHysteria2, Ports: []uint16{serverPort, clientPort}, Cmd: []string{"client", "-c", "/etc/hysteria/config.yml", "--disable-update-check", "--log-level", "debug"}, Bind: map[string]string{ "hysteria2-client.yml": "/etc/hysteria/config.yml", caPem: "/etc/hysteria/ca.pem", }, }) testSuit(t, clientPort, testPort) } func TestHysteria2Outbound(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startDockerContainer(t, DockerOptions{ Image: ImageHysteria2, Ports: []uint16{testPort}, Cmd: []string{"server", "-c", "/etc/hysteria/config.yml", "--disable-update-check", "--log-level", "debug"}, Bind: map[string]string{ "hysteria2-server.yml": "/etc/hysteria/config.yml", certPem: "/etc/hysteria/cert.pem", keyPem: "/etc/hysteria/key.pem", }, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeHysteria2, Hysteria2Options: option.Hysteria2OutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Obfs: &option.Hysteria2Obfs{ Type: hysteria2.ObfsTypeSalamander, Password: "cry_me_a_r1ver", }, Password: "password", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, }) testSuitSimple1(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/trojan_test.go
Bcore/windows/resources/sing-box-main/test/trojan_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" ) func TestTrojanOutbound(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startDockerContainer(t, DockerOptions{ Image: ImageTrojan, Ports: []uint16{serverPort, testPort}, Bind: map[string]string{ "trojan.json": "/config/config.json", certPem: "/path/to/certificate.crt", keyPem: "/path/to/private.key", }, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeTrojan, TrojanOptions: option.TrojanOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Password: "password", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestTrojanSelf(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTrojan, TrojanOptions: option.TrojanInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TrojanUser{ { Name: "sekai", Password: "password", }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTrojan, Tag: "trojan-out", TrojanOptions: option.TrojanOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Password: "password", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "trojan-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestTrojanPlainSelf(t *testing.T) { startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTrojan, TrojanOptions: option.TrojanInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TrojanUser{ { Name: "sekai", Password: "password", }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTrojan, Tag: "trojan-out", TrojanOptions: option.TrojanOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Password: "password", }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "trojan-out", }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/v2ray_httpupgrade_test.go
Bcore/windows/resources/sing-box-main/test/v2ray_httpupgrade_test.go
package main import ( "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" ) func TestV2RayHTTPUpgrade(t *testing.T) { t.Run("self", func(t *testing.T) { testV2RayTransportSelf(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeHTTPUpgrade, }) }) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/mux_test.go
Bcore/windows/resources/sing-box-main/test/mux_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks/shadowaead_2022" "github.com/gofrs/uuid/v5" ) var muxProtocols = []string{ "h2mux", "smux", "yamux", } func TestVMessSMux(t *testing.T) { testVMessMux(t, option.OutboundMultiplexOptions{ Enabled: true, Protocol: "smux", }) } func TestShadowsocksMux(t *testing.T) { for _, protocol := range muxProtocols { t.Run(protocol, func(t *testing.T) { testShadowsocksMux(t, option.OutboundMultiplexOptions{ Enabled: true, Protocol: protocol, }) }) } } func TestShadowsockH2Mux(t *testing.T) { testShadowsocksMux(t, option.OutboundMultiplexOptions{ Enabled: true, Protocol: "h2mux", Padding: true, }) } func TestShadowsockSMuxPadding(t *testing.T) { testShadowsocksMux(t, option.OutboundMultiplexOptions{ Enabled: true, Protocol: "smux", Padding: true, }) } func testShadowsocksMux(t *testing.T, options option.OutboundMultiplexOptions) { method := shadowaead_2022.List[0] password := mkBase64(t, 16) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Method: method, Password: password, Multiplex: &option.InboundMultiplexOptions{ Enabled: true, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeShadowsocks, Tag: "ss-out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: method, Password: password, Multiplex: &options, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func testVMessMux(t *testing.T, options option.OutboundMultiplexOptions) { user, _ := uuid.NewV4() startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { UUID: user.String(), }, }, Multiplex: &option.InboundMultiplexOptions{ Enabled: true, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeVMess, Tag: "vmess-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Security: "auto", UUID: user.String(), Multiplex: &options, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "vmess-out", }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/vmess_test.go
Bcore/windows/resources/sing-box-main/test/vmess_test.go
package main import ( "net/netip" "os" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/gofrs/uuid/v5" "github.com/spyzhov/ajson" "github.com/stretchr/testify/require" ) func newUUID() uuid.UUID { user, _ := uuid.DefaultGenerator.NewV4() return user } func TestVMessAuto(t *testing.T) { security := "auto" t.Run("self", func(t *testing.T) { testVMessSelf(t, security, 0, false, false, false) }) t.Run("packetaddr", func(t *testing.T) { testVMessSelf(t, security, 0, false, false, true) }) t.Run("inbound", func(t *testing.T) { testVMessInboundWithV2Ray(t, security, 0, false) }) t.Run("outbound", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, false, false, 0) }) } func TestVMess(t *testing.T) { for _, security := range []string{ "zero", } { t.Run(security, func(t *testing.T) { testVMess0(t, security) }) } for _, security := range []string{ "none", } { t.Run(security, func(t *testing.T) { testVMess1(t, security) }) } for _, security := range []string{ "aes-128-gcm", "chacha20-poly1305", "aes-128-cfb", } { t.Run(security, func(t *testing.T) { testVMess2(t, security) }) } } func testVMess0(t *testing.T, security string) { t.Run("self", func(t *testing.T) { testVMessSelf(t, security, 0, false, false, false) }) t.Run("self-legacy", func(t *testing.T) { testVMessSelf(t, security, 1, false, false, false) }) t.Run("packetaddr", func(t *testing.T) { testVMessSelf(t, security, 0, false, false, true) }) t.Run("outbound", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, false, false, 0) }) t.Run("outbound-legacy", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, false, false, 1) }) } func testVMess1(t *testing.T, security string) { t.Run("self", func(t *testing.T) { testVMessSelf(t, security, 0, false, false, false) }) t.Run("self-legacy", func(t *testing.T) { testVMessSelf(t, security, 1, false, false, false) }) t.Run("packetaddr", func(t *testing.T) { testVMessSelf(t, security, 0, false, false, true) }) t.Run("inbound", func(t *testing.T) { testVMessInboundWithV2Ray(t, security, 0, false) }) t.Run("outbound", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, false, false, 0) }) t.Run("outbound-legacy", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, false, false, 1) }) } func testVMess2(t *testing.T, security string) { t.Run("self", func(t *testing.T) { testVMessSelf(t, security, 0, false, false, false) }) t.Run("self-padding", func(t *testing.T) { testVMessSelf(t, security, 0, true, false, false) }) t.Run("self-authid", func(t *testing.T) { testVMessSelf(t, security, 0, false, true, false) }) t.Run("self-padding-authid", func(t *testing.T) { testVMessSelf(t, security, 0, true, true, false) }) t.Run("self-legacy", func(t *testing.T) { testVMessSelf(t, security, 1, false, false, false) }) t.Run("self-legacy-padding", func(t *testing.T) { testVMessSelf(t, security, 1, true, false, false) }) t.Run("packetaddr", func(t *testing.T) { testVMessSelf(t, security, 0, false, false, true) }) t.Run("inbound", func(t *testing.T) { testVMessInboundWithV2Ray(t, security, 0, false) }) t.Run("inbound-authid", func(t *testing.T) { testVMessInboundWithV2Ray(t, security, 0, true) }) t.Run("inbound-legacy", func(t *testing.T) { testVMessInboundWithV2Ray(t, security, 64, false) }) t.Run("outbound", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, false, false, 0) }) t.Run("outbound-padding", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, true, false, 0) }) t.Run("outbound-authid", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, false, true, 0) }) t.Run("outbound-padding-authid", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, true, true, 0) }) t.Run("outbound-legacy", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, false, false, 1) }) t.Run("outbound-legacy-padding", func(t *testing.T) { testVMessOutboundWithV2Ray(t, security, true, false, 1) }) } func testVMessInboundWithV2Ray(t *testing.T, security string, alterId int, authenticatedLength bool) { userId := newUUID() content, err := os.ReadFile("config/vmess-client.json") require.NoError(t, err) config, err := ajson.Unmarshal(content) require.NoError(t, err) config.MustKey("inbounds").MustIndex(0).MustKey("port").SetNumeric(float64(clientPort)) outbound := config.MustKey("outbounds").MustIndex(0).MustKey("settings").MustKey("vnext").MustIndex(0) outbound.MustKey("port").SetNumeric(float64(serverPort)) user := outbound.MustKey("users").MustIndex(0) user.MustKey("id").SetString(userId.String()) user.MustKey("alterId").SetNumeric(float64(alterId)) user.MustKey("security").SetString(security) var experiments string if authenticatedLength { experiments += "AuthenticatedLength" } user.MustKey("experiments").SetString(experiments) content, err = ajson.Marshal(config) require.NoError(t, err) startDockerContainer(t, DockerOptions{ Image: ImageV2RayCore, Ports: []uint16{serverPort, testPort}, EntryPoint: "v2ray", Cmd: []string{"run"}, Stdin: content, Env: []string{"V2RAY_VMESS_AEAD_FORCED=false"}, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: userId.String(), AlterId: alterId, }, }, }, }, }, }) testSuitSimple(t, clientPort, testPort) } func testVMessOutboundWithV2Ray(t *testing.T, security string, globalPadding bool, authenticatedLength bool, alterId int) { user := newUUID() content, err := os.ReadFile("config/vmess-server.json") require.NoError(t, err) config, err := ajson.Unmarshal(content) require.NoError(t, err) inbound := config.MustKey("inbounds").MustIndex(0) inbound.MustKey("port").SetNumeric(float64(serverPort)) inbound.MustKey("settings").MustKey("clients").MustIndex(0).MustKey("id").SetString(user.String()) inbound.MustKey("settings").MustKey("clients").MustIndex(0).MustKey("alterId").SetNumeric(float64(alterId)) content, err = ajson.Marshal(config) require.NoError(t, err) startDockerContainer(t, DockerOptions{ Image: ImageV2RayCore, Ports: []uint16{serverPort, testPort}, EntryPoint: "v2ray", Cmd: []string{"run"}, Stdin: content, Env: []string{"V2RAY_VMESS_AEAD_FORCED=false"}, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeVMess, VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Security: security, UUID: user.String(), GlobalPadding: globalPadding, AuthenticatedLength: authenticatedLength, AlterId: alterId, }, }, }, }) testSuit(t, clientPort, testPort) } func testVMessSelf(t *testing.T, security string, alterId int, globalPadding bool, authenticatedLength bool, packetAddr bool) { user := newUUID() startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: user.String(), AlterId: alterId, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeVMess, Tag: "vmess-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Security: security, UUID: user.String(), AlterId: alterId, GlobalPadding: globalPadding, AuthenticatedLength: authenticatedLength, PacketEncoding: "packetaddr", }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "vmess-out", }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/mkcert.go
Bcore/windows/resources/sing-box-main/test/mkcert.go
package main import ( "crypto/rand" "crypto/rsa" "crypto/sha1" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/pem" "math/big" "os" "path/filepath" "testing" "time" "github.com/sagernet/sing/common/rw" "github.com/stretchr/testify/require" ) func createSelfSignedCertificate(t *testing.T, domain string) (caPem, certPem, keyPem string) { const userAndHostname = "sekai@nekohasekai.local" tempDir, err := os.MkdirTemp("", "sing-box-test") require.NoError(t, err) t.Cleanup(func() { os.RemoveAll(tempDir) }) caKey, err := rsa.GenerateKey(rand.Reader, 3072) require.NoError(t, err) spkiASN1, err := x509.MarshalPKIXPublicKey(caKey.Public()) var spki struct { Algorithm pkix.AlgorithmIdentifier SubjectPublicKey asn1.BitString } _, err = asn1.Unmarshal(spkiASN1, &spki) require.NoError(t, err) skid := sha1.Sum(spki.SubjectPublicKey.Bytes) caTpl := &x509.Certificate{ SerialNumber: randomSerialNumber(t), Subject: pkix.Name{ Organization: []string{"sing-box test CA"}, OrganizationalUnit: []string{userAndHostname}, CommonName: "sing-box " + userAndHostname, }, SubjectKeyId: skid[:], NotAfter: time.Now().AddDate(10, 0, 0), NotBefore: time.Now(), KeyUsage: x509.KeyUsageCertSign, BasicConstraintsValid: true, IsCA: true, MaxPathLenZero: true, } caCert, err := x509.CreateCertificate(rand.Reader, caTpl, caTpl, caKey.Public(), caKey) require.NoError(t, err) err = rw.WriteFile(filepath.Join(tempDir, "ca.pem"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCert})) require.NoError(t, err) key, err := rsa.GenerateKey(rand.Reader, 2048) domainTpl := &x509.Certificate{ SerialNumber: randomSerialNumber(t), Subject: pkix.Name{ Organization: []string{"sing-box test certificate"}, OrganizationalUnit: []string{"sing-box " + userAndHostname}, }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(0, 0, 30), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, } domainTpl.DNSNames = append(domainTpl.DNSNames, domain) cert, err := x509.CreateCertificate(rand.Reader, domainTpl, caTpl, key.Public(), caKey) require.NoError(t, err) certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) privDER, err := x509.MarshalPKCS8PrivateKey(key) require.NoError(t, err) privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privDER}) err = rw.WriteFile(filepath.Join(tempDir, domain+".pem"), certPEM) require.NoError(t, err) err = rw.WriteFile(filepath.Join(tempDir, domain+".key.pem"), privPEM) require.NoError(t, err) return filepath.Join(tempDir, "ca.pem"), filepath.Join(tempDir, domain+".pem"), filepath.Join(tempDir, domain+".key.pem") } func randomSerialNumber(t *testing.T) *big.Int { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) require.NoError(t, err) return serialNumber }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/domain_inbound_test.go
Bcore/windows/resources/sing-box-main/test/domain_inbound_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" dns "github.com/sagernet/sing-dns" "github.com/gofrs/uuid/v5" ) func TestTUICDomainUDP(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTUIC, TUICOptions: option.TUICInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, InboundOptions: option.InboundOptions{ DomainStrategy: option.DomainStrategy(dns.DomainStrategyUseIPv6), }, }, Users: []option.TUICUser{{ UUID: uuid.Nil.String(), }}, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTUIC, Tag: "tuic-out", TUICOptions: option.TUICOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: uuid.Nil.String(), OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "tuic-out", }, }, }, }, }) testQUIC(t, clientPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/ss_plugin_test.go
Bcore/windows/resources/sing-box-main/test/ss_plugin_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" ) func TestShadowsocksObfs(t *testing.T) { for _, mode := range []string{ "http", "tls", } { t.Run("obfs-local "+mode, func(t *testing.T) { testShadowsocksPlugin(t, "obfs-local", "obfs="+mode, "--plugin obfs-server --plugin-opts obfs="+mode) }) } } // Since I can't test this on m1 mac (rosetta error: bss_size overflow), I don't care about it func _TestShadowsocksV2RayPlugin(t *testing.T) { testShadowsocksPlugin(t, "v2ray-plugin", "", "--plugin v2ray-plugin --plugin-opts=server") } func testShadowsocksPlugin(t *testing.T, name string, opts string, args string) { startDockerContainer(t, DockerOptions{ Image: ImageShadowsocksLegacy, Ports: []uint16{serverPort, testPort}, Env: []string{ "SS_MODULE=ss-server", "SS_CONFIG=-s 0.0.0.0 -u -p 10000 -m chacha20-ietf-poly1305 -k FzcLbKs2dY9mhL " + args, }, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: "chacha20-ietf-poly1305", Password: "FzcLbKs2dY9mhL", Plugin: name, PluginOptions: opts, }, }, }, }) testSuitSimple(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/http_test.go
Bcore/windows/resources/sing-box-main/test/http_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" ) func TestHTTPSelf(t *testing.T) { startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeHTTP, Tag: "http-out", HTTPOptions: option.HTTPOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "http-out", }, }, }, }, }) testTCP(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/tuic_test.go
Bcore/windows/resources/sing-box-main/test/tuic_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/gofrs/uuid/v5" ) func TestTUICSelf(t *testing.T) { t.Run("self", func(t *testing.T) { testTUICSelf(t, false, false) }) t.Run("self-udp-stream", func(t *testing.T) { testTUICSelf(t, true, false) }) t.Run("self-early", func(t *testing.T) { testTUICSelf(t, false, true) }) } func testTUICSelf(t *testing.T, udpStream bool, zeroRTTHandshake bool) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") var udpRelayMode string if udpStream { udpRelayMode = "quic" } startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTUIC, TUICOptions: option.TUICInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TUICUser{{ UUID: uuid.Nil.String(), }}, ZeroRTTHandshake: zeroRTTHandshake, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTUIC, Tag: "tuic-out", TUICOptions: option.TUICOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: uuid.Nil.String(), UDPRelayMode: udpRelayMode, ZeroRTTHandshake: zeroRTTHandshake, OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "tuic-out", }, }, }, }, }) testSuitLargeUDP(t, clientPort, testPort) } func TestTUICInbound(t *testing.T) { caPem, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeTUIC, TUICOptions: option.TUICInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TUICUser{{ UUID: "FE35D05B-8803-45C4-BAE6-723AD2CD5D3D", Password: "tuic", }}, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, }) startDockerContainer(t, DockerOptions{ Image: ImageTUICClient, Ports: []uint16{serverPort, clientPort}, Bind: map[string]string{ "tuic-client.json": "/etc/tuic/config.json", caPem: "/etc/tuic/ca.pem", }, }) testSuitLargeUDP(t, clientPort, testPort) } func TestTUICOutbound(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startDockerContainer(t, DockerOptions{ Image: ImageTUICServer, Ports: []uint16{testPort}, Bind: map[string]string{ "tuic-server.json": "/etc/tuic/config.json", certPem: "/etc/tuic/cert.pem", keyPem: "/etc/tuic/key.pem", }, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeTUIC, TUICOptions: option.TUICOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: "FE35D05B-8803-45C4-BAE6-723AD2CD5D3D", Password: "tuic", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, }, }, }, }) testSuitLargeUDP(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/v2ray_transport_test.go
Bcore/windows/resources/sing-box-main/test/v2ray_transport_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/gofrs/uuid/v5" "github.com/stretchr/testify/require" ) func TestV2RayHTTPSelf(t *testing.T) { testV2RayTransportSelf(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeHTTP, HTTPOptions: option.V2RayHTTPOptions{ Method: "POST", }, }) } func TestV2RayHTTPPlainSelf(t *testing.T) { testV2RayTransportNOTLSSelf(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeHTTP, }) } func testV2RayTransportSelf(t *testing.T, transport *option.V2RayTransportOptions) { testV2RayTransportSelfWith(t, transport, transport) } func testV2RayTransportSelfWith(t *testing.T, server, client *option.V2RayTransportOptions) { t.Run("vmess", func(t *testing.T) { testVMessTransportSelf(t, server, client) }) t.Run("trojan", func(t *testing.T) { testTrojanTransportSelf(t, server, client) }) } func testVMessTransportSelf(t *testing.T, server *option.V2RayTransportOptions, client *option.V2RayTransportOptions) { user, err := uuid.DefaultGenerator.NewV4() require.NoError(t, err) _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: user.String(), }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, Transport: server, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeVMess, Tag: "vmess-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: user.String(), Security: "zero", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, Transport: client, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "vmess-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func testTrojanTransportSelf(t *testing.T, server *option.V2RayTransportOptions, client *option.V2RayTransportOptions) { user, err := uuid.DefaultGenerator.NewV4() require.NoError(t, err) _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTrojan, TrojanOptions: option.TrojanInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TrojanUser{ { Name: "sekai", Password: user.String(), }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, Transport: server, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTrojan, Tag: "vmess-out", TrojanOptions: option.TrojanOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Password: user.String(), OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, Transport: client, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "vmess-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestVMessQUICSelf(t *testing.T) { transport := &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeQUIC, } user, err := uuid.DefaultGenerator.NewV4() require.NoError(t, err) _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: user.String(), }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, Transport: transport, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeVMess, Tag: "vmess-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: user.String(), Security: "zero", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, Transport: transport, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "vmess-out", }, }, }, }, }) testSuitSimple1(t, clientPort, testPort) } func testV2RayTransportNOTLSSelf(t *testing.T, transport *option.V2RayTransportOptions) { user, err := uuid.DefaultGenerator.NewV4() require.NoError(t, err) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: user.String(), }, }, Transport: transport, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeVMess, Tag: "vmess-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: user.String(), Security: "zero", Transport: transport, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "vmess-out", }, }, }, }, }) testSuit(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/clash_other_test.go
Bcore/windows/resources/sing-box-main/test/clash_other_test.go
//go:build !darwin package main import ( "errors" "net/netip" ) func defaultRouteIP() (netip.Addr, error) { return netip.Addr{}, errors.New("not supported") }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/naive_test.go
Bcore/windows/resources/sing-box-main/test/naive_test.go
package main import ( "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/auth" "github.com/sagernet/sing/common/network" ) func TestNaiveInboundWithNginx(t *testing.T) { caPem, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeNaive, NaiveOptions: option.NaiveInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: otherPort, }, Users: []auth.User{ { Username: "sekai", Password: "password", }, }, Network: network.NetworkTCP, }, }, }, }) startDockerContainer(t, DockerOptions{ Image: ImageNginx, Ports: []uint16{serverPort, otherPort}, Bind: map[string]string{ "nginx.conf": "/etc/nginx/nginx.conf", "naive-nginx.conf": "/etc/nginx/conf.d/naive.conf", certPem: "/etc/nginx/cert.pem", keyPem: "/etc/nginx/key.pem", }, }) startDockerContainer(t, DockerOptions{ Image: ImageNaive, Ports: []uint16{serverPort, clientPort}, Bind: map[string]string{ "naive.json": "/etc/naiveproxy/config.json", caPem: "/etc/naiveproxy/ca.pem", }, Env: []string{ "SSL_CERT_FILE=/etc/naiveproxy/ca.pem", }, }) testTCP(t, clientPort, testPort) } func TestNaiveInbound(t *testing.T) { caPem, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeNaive, NaiveOptions: option.NaiveInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []auth.User{ { Username: "sekai", Password: "password", }, }, Network: network.NetworkTCP, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, }) startDockerContainer(t, DockerOptions{ Image: ImageNaive, Ports: []uint16{serverPort, clientPort}, Bind: map[string]string{ "naive.json": "/etc/naiveproxy/config.json", caPem: "/etc/naiveproxy/ca.pem", }, Env: []string{ "SSL_CERT_FILE=/etc/naiveproxy/ca.pem", }, }) testTCP(t, clientPort, testPort) } func TestNaiveHTTP3Inbound(t *testing.T) { caPem, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeNaive, NaiveOptions: option.NaiveInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []auth.User{ { Username: "sekai", Password: "password", }, }, Network: network.NetworkUDP, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, }, }, }, }) startDockerContainer(t, DockerOptions{ Image: ImageNaive, Ports: []uint16{serverPort, clientPort}, Bind: map[string]string{ "naive-quic.json": "/etc/naiveproxy/config.json", caPem: "/etc/naiveproxy/ca.pem", }, Env: []string{ "SSL_CERT_FILE=/etc/naiveproxy/ca.pem", }, }) testTCP(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/ech_test.go
Bcore/windows/resources/sing-box-main/test/ech_test.go
package main import ( "net/netip" "testing" "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" "github.com/gofrs/uuid/v5" ) func TestECH(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") echConfig, echKey := common.Must2(tls.ECHKeygenDefault("not.example.org", false)) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTrojan, TrojanOptions: option.TrojanInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TrojanUser{ { Name: "sekai", Password: "password", }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, ECH: &option.InboundECHOptions{ Enabled: true, Key: []string{echKey}, }, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTrojan, Tag: "trojan-out", TrojanOptions: option.TrojanOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Password: "password", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, ECH: &option.OutboundECHOptions{ Enabled: true, Config: []string{echConfig}, }, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "trojan-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestECHQUIC(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") echConfig, echKey := common.Must2(tls.ECHKeygenDefault("not.example.org", false)) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeTUIC, TUICOptions: option.TUICInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.TUICUser{{ UUID: uuid.Nil.String(), }}, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, ECH: &option.InboundECHOptions{ Enabled: true, Key: []string{echKey}, }, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeTUIC, Tag: "tuic-out", TUICOptions: option.TUICOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: uuid.Nil.String(), OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, ECH: &option.OutboundECHOptions{ Enabled: true, Config: []string{echConfig}, }, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "tuic-out", }, }, }, }, }) testSuitLargeUDP(t, clientPort, testPort) } func TestECHHysteria2(t *testing.T) { _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") echConfig, echKey := common.Must2(tls.ECHKeygenDefault("not.example.org", false)) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeHysteria2, Hysteria2Options: option.Hysteria2InboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.Hysteria2User{{ Password: "password", }}, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, ECH: &option.InboundECHOptions{ Enabled: true, Key: []string{echKey}, }, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeHysteria2, Tag: "hy2-out", Hysteria2Options: option.Hysteria2OutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Password: "password", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, ECH: &option.OutboundECHOptions{ Enabled: true, Config: []string{echConfig}, }, }, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { Type: C.RuleTypeDefault, DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "hy2-out", }, }, }, }, }) testSuitLargeUDP(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/docker_test.go
Bcore/windows/resources/sing-box-main/test/docker_test.go
package main import ( "context" "os" "path/filepath" "testing" "time" "github.com/sagernet/sing/common/debug" F "github.com/sagernet/sing/common/format" "github.com/sagernet/sing/common/rw" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/docker/docker/pkg/stdcopy" "github.com/docker/go-connections/nat" "github.com/stretchr/testify/require" ) type DockerOptions struct { Image string EntryPoint string Ports []uint16 Cmd []string Env []string Bind map[string]string Stdin []byte Cap []string } func startDockerContainer(t *testing.T, options DockerOptions) { dockerClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) require.NoError(t, err) defer dockerClient.Close() writeStdin := len(options.Stdin) > 0 var containerOptions container.Config if writeStdin { containerOptions.OpenStdin = true containerOptions.StdinOnce = true } containerOptions.Image = options.Image if options.EntryPoint != "" { containerOptions.Entrypoint = []string{options.EntryPoint} } containerOptions.Cmd = options.Cmd containerOptions.Env = options.Env containerOptions.ExposedPorts = make(nat.PortSet) var hostOptions container.HostConfig hostOptions.NetworkMode = "host" hostOptions.CapAdd = options.Cap hostOptions.PortBindings = make(nat.PortMap) for _, port := range options.Ports { containerOptions.ExposedPorts[nat.Port(F.ToString(port, "/tcp"))] = struct{}{} containerOptions.ExposedPorts[nat.Port(F.ToString(port, "/udp"))] = struct{}{} hostOptions.PortBindings[nat.Port(F.ToString(port, "/tcp"))] = []nat.PortBinding{ {HostPort: F.ToString(port), HostIP: "0.0.0.0"}, } hostOptions.PortBindings[nat.Port(F.ToString(port, "/udp"))] = []nat.PortBinding{ {HostPort: F.ToString(port), HostIP: "0.0.0.0"}, } } if len(options.Bind) > 0 { hostOptions.Binds = []string{} for path, internalPath := range options.Bind { if !rw.FileExists(path) { path = filepath.Join("config", path) } path, _ = filepath.Abs(path) hostOptions.Binds = append(hostOptions.Binds, path+":"+internalPath) } } dockerContainer, err := dockerClient.ContainerCreate(context.Background(), &containerOptions, &hostOptions, nil, nil, "") require.NoError(t, err) t.Cleanup(func() { cleanContainer(dockerContainer.ID) }) require.NoError(t, dockerClient.ContainerStart(context.Background(), dockerContainer.ID, types.ContainerStartOptions{})) if writeStdin { stdinAttach, err := dockerClient.ContainerAttach(context.Background(), dockerContainer.ID, types.ContainerAttachOptions{ Stdin: writeStdin, Stream: true, }) require.NoError(t, err) _, err = stdinAttach.Conn.Write(options.Stdin) require.NoError(t, err) stdinAttach.Close() } if debug.Enabled { attach, err := dockerClient.ContainerAttach(context.Background(), dockerContainer.ID, types.ContainerAttachOptions{ Stdout: true, Stderr: true, Logs: true, Stream: true, }) require.NoError(t, err) go func() { stdcopy.StdCopy(os.Stderr, os.Stderr, attach.Reader) }() } time.Sleep(time.Second) } func cleanContainer(id string) error { dockerClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { return err } defer dockerClient.Close() return dockerClient.ContainerRemove(context.Background(), id, types.ContainerRemoveOptions{Force: true}) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/shadowsocks_test.go
Bcore/windows/resources/sing-box-main/test/shadowsocks_test.go
package main import ( "crypto/rand" "encoding/base64" "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks/shadowaead_2022" F "github.com/sagernet/sing/common/format" "github.com/stretchr/testify/require" ) const ( serverPort uint16 = 10000 + iota clientPort testPort otherPort otherClientPort ) func TestShadowsocks(t *testing.T) { for _, method := range []string{ "aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305", } { t.Run(method+"-inbound", func(t *testing.T) { testShadowsocksInboundWithShadowsocksRust(t, method, mkBase64(t, 16)) }) t.Run(method+"-outbound", func(t *testing.T) { testShadowsocksOutboundWithShadowsocksRust(t, method, mkBase64(t, 16)) }) t.Run(method+"-self", func(t *testing.T) { testShadowsocksSelf(t, method, mkBase64(t, 16)) }) } } func TestShadowsocksNone(t *testing.T) { testShadowsocksSelf(t, "none", "") } func TestShadowsocks2022(t *testing.T) { for _, method16 := range []string{ "2022-blake3-aes-128-gcm", } { t.Run(method16+"-inbound", func(t *testing.T) { testShadowsocksInboundWithShadowsocksRust(t, method16, mkBase64(t, 16)) }) t.Run(method16+"-outbound", func(t *testing.T) { testShadowsocksOutboundWithShadowsocksRust(t, method16, mkBase64(t, 16)) }) t.Run(method16+"-self", func(t *testing.T) { testShadowsocksSelf(t, method16, mkBase64(t, 16)) }) } for _, method32 := range []string{ "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305", } { t.Run(method32+"-inbound", func(t *testing.T) { testShadowsocksInboundWithShadowsocksRust(t, method32, mkBase64(t, 32)) }) t.Run(method32+"-outbound", func(t *testing.T) { testShadowsocksOutboundWithShadowsocksRust(t, method32, mkBase64(t, 32)) }) t.Run(method32+"-self", func(t *testing.T) { testShadowsocksSelf(t, method32, mkBase64(t, 32)) }) } } func TestShadowsocks2022EIH(t *testing.T) { for _, method16 := range []string{ "2022-blake3-aes-128-gcm", } { t.Run(method16, func(t *testing.T) { testShadowsocks2022EIH(t, method16, mkBase64(t, 16)) }) } for _, method32 := range []string{ "2022-blake3-aes-256-gcm", } { t.Run(method32, func(t *testing.T) { testShadowsocks2022EIH(t, method32, mkBase64(t, 32)) }) } } func testShadowsocksInboundWithShadowsocksRust(t *testing.T, method string, password string) { startDockerContainer(t, DockerOptions{ Image: ImageShadowsocksRustClient, EntryPoint: "sslocal", Ports: []uint16{serverPort, clientPort}, Cmd: []string{"-s", F.ToString("127.0.0.1:", serverPort), "-b", F.ToString("0.0.0.0:", clientPort), "-m", method, "-k", password, "-U"}, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Method: method, Password: password, }, }, }, }) testSuit(t, clientPort, testPort) } func testShadowsocksOutboundWithShadowsocksRust(t *testing.T, method string, password string) { startDockerContainer(t, DockerOptions{ Image: ImageShadowsocksRustServer, EntryPoint: "ssserver", Ports: []uint16{serverPort, testPort}, Cmd: []string{"-s", F.ToString("0.0.0.0:", serverPort), "-m", method, "-k", password, "-U"}, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: method, Password: password, }, }, }, }) testSuit(t, clientPort, testPort) } func testShadowsocksSelf(t *testing.T, method string, password string) { startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Method: method, Password: password, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeShadowsocks, Tag: "ss-out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: method, Password: password, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestShadowsocksUoT(t *testing.T) { method := shadowaead_2022.List[0] password := mkBase64(t, 16) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Method: method, Password: password, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeShadowsocks, Tag: "ss-out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: method, Password: password, UDPOverTCP: &option.UDPOverTCPOptions{ Enabled: true, }, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func testShadowsocks2022EIH(t *testing.T, method string, password string) { startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeShadowsocks, ShadowsocksOptions: option.ShadowsocksInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Method: method, Password: password, Users: []option.ShadowsocksUser{ { Password: password, }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeShadowsocks, Tag: "ss-out", ShadowsocksOptions: option.ShadowsocksOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, Method: method, Password: password + ":" + password, }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "ss-out", }, }, }, }, }) testSuit(t, clientPort, testPort) } func mkBase64(t *testing.T, length int) string { psk := make([]byte, length) _, err := rand.Read(psk) require.NoError(t, err) return base64.StdEncoding.EncodeToString(psk) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/v2ray_api_test.go
Bcore/windows/resources/sing-box-main/test/v2ray_api_test.go
package main import ( "context" "net/netip" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/experimental/v2rayapi" "github.com/sagernet/sing-box/option" "github.com/stretchr/testify/require" ) func TestV2RayAPI(t *testing.T) { i := startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, Tag: "out", }, }, Experimental: &option.ExperimentalOptions{ V2RayAPI: &option.V2RayAPIOptions{ Listen: "127.0.0.1:8080", Stats: &option.V2RayStatsServiceOptions{ Enabled: true, Inbounds: []string{"in"}, Outbounds: []string{"out"}, }, }, }, }) testSuit(t, clientPort, testPort) statsService := i.Router().V2RayServer().StatsService() require.NotNil(t, statsService) response, err := statsService.(v2rayapi.StatsServiceServer).QueryStats(context.Background(), &v2rayapi.QueryStatsRequest{Regexp: true, Patterns: []string{".*"}}) require.NoError(t, err) count := response.Stat[0].Value require.Equal(t, len(response.Stat), 4) for _, stat := range response.Stat { require.Equal(t, count, stat.Value) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/mux_cool_test.go
Bcore/windows/resources/sing-box-main/test/mux_cool_test.go
package main import ( "net/netip" "os" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/spyzhov/ajson" "github.com/stretchr/testify/require" ) func TestMuxCoolServer(t *testing.T) { userId := newUUID() content, err := os.ReadFile("config/vmess-mux-client.json") require.NoError(t, err) config, err := ajson.Unmarshal(content) require.NoError(t, err) config.MustKey("inbounds").MustIndex(0).MustKey("port").SetNumeric(float64(clientPort)) outbound := config.MustKey("outbounds").MustIndex(0).MustKey("settings").MustKey("vnext").MustIndex(0) outbound.MustKey("port").SetNumeric(float64(serverPort)) user := outbound.MustKey("users").MustIndex(0) user.MustKey("id").SetString(userId.String()) content, err = ajson.Marshal(config) require.NoError(t, err) startDockerContainer(t, DockerOptions{ Image: ImageV2RayCore, Ports: []uint16{serverPort, testPort}, EntryPoint: "v2ray", Cmd: []string{"run"}, Stdin: content, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: userId.String(), }, }, }, }, }, }) testSuitSimple(t, clientPort, testPort) } func TestMuxCoolClient(t *testing.T) { user := newUUID() content, err := os.ReadFile("config/vmess-server.json") require.NoError(t, err) config, err := ajson.Unmarshal(content) require.NoError(t, err) inbound := config.MustKey("inbounds").MustIndex(0) inbound.MustKey("port").SetNumeric(float64(serverPort)) inbound.MustKey("settings").MustKey("clients").MustIndex(0).MustKey("id").SetString(user.String()) content, err = ajson.Marshal(config) require.NoError(t, err) startDockerContainer(t, DockerOptions{ Image: ImageXRayCore, Ports: []uint16{serverPort, testPort}, EntryPoint: "xray", Stdin: content, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeVMess, VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: user.String(), PacketEncoding: "xudp", }, }, }, }) testSuitSimple(t, clientPort, testPort) } func TestMuxCoolSelf(t *testing.T) { user := newUUID() startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: user.String(), }, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeDirect, }, { Type: C.TypeVMess, Tag: "vmess-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: user.String(), PacketEncoding: "xudp", }, }, }, Route: &option.RouteOptions{ Rules: []option.Rule{ { DefaultOptions: option.DefaultRule{ Inbound: []string{"mixed-in"}, Outbound: "vmess-out", }, }, }, }, }) testSuitSimple(t, clientPort, testPort) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/test/v2ray_grpc_test.go
Bcore/windows/resources/sing-box-main/test/v2ray_grpc_test.go
package main import ( "net/netip" "os" "testing" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/gofrs/uuid/v5" "github.com/spyzhov/ajson" "github.com/stretchr/testify/require" ) func TestV2RayGRPCInbound(t *testing.T) { t.Run("origin", func(t *testing.T) { testV2RayGRPCInbound(t, false) }) t.Run("lite", func(t *testing.T) { testV2RayGRPCInbound(t, true) }) } func testV2RayGRPCInbound(t *testing.T, forceLite bool) { userId, err := uuid.DefaultGenerator.NewV4() require.NoError(t, err) _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeVMess, VMessOptions: option.VMessInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: serverPort, }, Users: []option.VMessUser{ { Name: "sekai", UUID: userId.String(), }, }, InboundTLSOptionsContainer: option.InboundTLSOptionsContainer{ TLS: &option.InboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, KeyPath: keyPem, }, }, Transport: &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeGRPC, GRPCOptions: option.V2RayGRPCOptions{ ServiceName: "TunService", ForceLite: forceLite, }, }, }, }, }, }) content, err := os.ReadFile("config/vmess-grpc-client.json") require.NoError(t, err) config, err := ajson.Unmarshal(content) require.NoError(t, err) config.MustKey("inbounds").MustIndex(0).MustKey("port").SetNumeric(float64(clientPort)) outbound := config.MustKey("outbounds").MustIndex(0).MustKey("settings").MustKey("vnext").MustIndex(0) outbound.MustKey("port").SetNumeric(float64(serverPort)) user := outbound.MustKey("users").MustIndex(0) user.MustKey("id").SetString(userId.String()) content, err = ajson.Marshal(config) require.NoError(t, err) startDockerContainer(t, DockerOptions{ Image: ImageV2RayCore, Ports: []uint16{serverPort, testPort}, EntryPoint: "v2ray", Cmd: []string{"run"}, Stdin: content, Bind: map[string]string{ certPem: "/path/to/certificate.crt", keyPem: "/path/to/private.key", }, }) testSuitSimple(t, clientPort, testPort) } func TestV2RayGRPCOutbound(t *testing.T) { t.Run("origin", func(t *testing.T) { testV2RayGRPCOutbound(t, false) }) t.Run("lite", func(t *testing.T) { testV2RayGRPCOutbound(t, true) }) } func testV2RayGRPCOutbound(t *testing.T, forceLite bool) { userId, err := uuid.DefaultGenerator.NewV4() require.NoError(t, err) _, certPem, keyPem := createSelfSignedCertificate(t, "example.org") content, err := os.ReadFile("config/vmess-grpc-server.json") require.NoError(t, err) config, err := ajson.Unmarshal(content) require.NoError(t, err) inbound := config.MustKey("inbounds").MustIndex(0) inbound.MustKey("port").SetNumeric(float64(serverPort)) inbound.MustKey("settings").MustKey("clients").MustIndex(0).MustKey("id").SetString(userId.String()) content, err = ajson.Marshal(config) require.NoError(t, err) startDockerContainer(t, DockerOptions{ Image: ImageV2RayCore, Ports: []uint16{serverPort, testPort}, EntryPoint: "v2ray", Cmd: []string{"run"}, Stdin: content, Env: []string{"V2RAY_VMESS_AEAD_FORCED=false"}, Bind: map[string]string{ certPem: "/path/to/certificate.crt", keyPem: "/path/to/private.key", }, }) startInstance(t, option.Options{ Inbounds: []option.Inbound{ { Type: C.TypeMixed, Tag: "mixed-in", MixedOptions: option.HTTPMixedInboundOptions{ ListenOptions: option.ListenOptions{ Listen: option.NewListenAddress(netip.IPv4Unspecified()), ListenPort: clientPort, }, }, }, }, Outbounds: []option.Outbound{ { Type: C.TypeVMess, Tag: "vmess-out", VMessOptions: option.VMessOutboundOptions{ ServerOptions: option.ServerOptions{ Server: "127.0.0.1", ServerPort: serverPort, }, UUID: userId.String(), Security: "zero", OutboundTLSOptionsContainer: option.OutboundTLSOptionsContainer{ TLS: &option.OutboundTLSOptions{ Enabled: true, ServerName: "example.org", CertificatePath: certPem, }, }, Transport: &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeGRPC, GRPCOptions: option.V2RayGRPCOptions{ ServiceName: "TunService", ForceLite: forceLite, }, }, }, }, }, }) testSuit(t, clientPort, testPort) } func TestV2RayGRPCLite(t *testing.T) { t.Run("server", func(t *testing.T) { testV2RayTransportSelfWith(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeGRPC, GRPCOptions: option.V2RayGRPCOptions{ ServiceName: "TunService", ForceLite: true, }, }, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeGRPC, GRPCOptions: option.V2RayGRPCOptions{ ServiceName: "TunService", }, }) }) t.Run("client", func(t *testing.T) { testV2RayTransportSelfWith(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeGRPC, GRPCOptions: option.V2RayGRPCOptions{ ServiceName: "TunService", }, }, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeGRPC, GRPCOptions: option.V2RayGRPCOptions{ ServiceName: "TunService", ForceLite: true, }, }) }) t.Run("self", func(t *testing.T) { testV2RayTransportSelfWith(t, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeGRPC, GRPCOptions: option.V2RayGRPCOptions{ ServiceName: "TunService", ForceLite: true, }, }, &option.V2RayTransportOptions{ Type: C.V2RayTransportTypeGRPC, GRPCOptions: option.V2RayGRPCOptions{ ServiceName: "TunService", ForceLite: true, }, }) }) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/experimental.go
Bcore/windows/resources/sing-box-main/option/experimental.go
package option type ExperimentalOptions struct { CacheFile *CacheFileOptions `json:"cache_file,omitempty"` ClashAPI *ClashAPIOptions `json:"clash_api,omitempty"` V2RayAPI *V2RayAPIOptions `json:"v2ray_api,omitempty"` Debug *DebugOptions `json:"debug,omitempty"` } type CacheFileOptions struct { Enabled bool `json:"enabled,omitempty"` Path string `json:"path,omitempty"` CacheID string `json:"cache_id,omitempty"` StoreFakeIP bool `json:"store_fakeip,omitempty"` StoreRDRC bool `json:"store_rdrc,omitempty"` RDRCTimeout Duration `json:"rdrc_timeout,omitempty"` } type ClashAPIOptions struct { ExternalController string `json:"external_controller,omitempty"` ExternalUI string `json:"external_ui,omitempty"` ExternalUIDownloadURL string `json:"external_ui_download_url,omitempty"` ExternalUIDownloadDetour string `json:"external_ui_download_detour,omitempty"` Secret string `json:"secret,omitempty"` DefaultMode string `json:"default_mode,omitempty"` ModeList []string `json:"-"` AccessControlAllowOrigin Listable[string] `json:"access_control_allow_origin,omitempty"` AccessControlAllowPrivateNetwork bool `json:"access_control_allow_private_network,omitempty"` // Deprecated: migrated to global cache file CacheFile string `json:"cache_file,omitempty"` // Deprecated: migrated to global cache file CacheID string `json:"cache_id,omitempty"` // Deprecated: migrated to global cache file StoreMode bool `json:"store_mode,omitempty"` // Deprecated: migrated to global cache file StoreSelected bool `json:"store_selected,omitempty"` // Deprecated: migrated to global cache file StoreFakeIP bool `json:"store_fakeip,omitempty"` } type V2RayAPIOptions struct { Listen string `json:"listen,omitempty"` Stats *V2RayStatsServiceOptions `json:"stats,omitempty"` } type V2RayStatsServiceOptions struct { Enabled bool `json:"enabled,omitempty"` Inbounds []string `json:"inbounds,omitempty"` Outbounds []string `json:"outbounds,omitempty"` Users []string `json:"users,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/json.go
Bcore/windows/resources/sing-box-main/option/json.go
package option import ( "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" "github.com/sagernet/sing/common/json/badjson" ) func ToMap(v any) (*badjson.JSONObject, error) { inputContent, err := json.Marshal(v) if err != nil { return nil, err } var content badjson.JSONObject err = content.UnmarshalJSON(inputContent) if err != nil { return nil, err } return &content, nil } func MergeObjects(objects ...any) (*badjson.JSONObject, error) { var content badjson.JSONObject for _, object := range objects { objectMap, err := ToMap(object) if err != nil { return nil, err } content.PutAll(objectMap) } return &content, nil } func MarshallObjects(objects ...any) ([]byte, error) { objects = common.FilterNotNil(objects) if len(objects) == 1 { return json.Marshal(objects[0]) } content, err := MergeObjects(objects...) if err != nil { return nil, err } return content.MarshalJSON() } func UnmarshallExcluded(inputContent []byte, parentObject any, object any) error { parentContent, err := ToMap(parentObject) if err != nil { return err } var content badjson.JSONObject err = content.UnmarshalJSON(inputContent) if err != nil { return err } for _, key := range parentContent.Keys() { content.Remove(key) } if object == nil { if content.IsEmpty() { return nil } return E.New("unexpected key: ", content.Keys()[0]) } inputContent, err = content.MarshalJSON() if err != nil { return err } return json.UnmarshalDisallowUnknownFields(inputContent, object) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/hysteria.go
Bcore/windows/resources/sing-box-main/option/hysteria.go
package option type HysteriaInboundOptions struct { ListenOptions Up string `json:"up,omitempty"` UpMbps int `json:"up_mbps,omitempty"` Down string `json:"down,omitempty"` DownMbps int `json:"down_mbps,omitempty"` Obfs string `json:"obfs,omitempty"` Users []HysteriaUser `json:"users,omitempty"` ReceiveWindowConn uint64 `json:"recv_window_conn,omitempty"` ReceiveWindowClient uint64 `json:"recv_window_client,omitempty"` MaxConnClient int `json:"max_conn_client,omitempty"` DisableMTUDiscovery bool `json:"disable_mtu_discovery,omitempty"` InboundTLSOptionsContainer } type HysteriaUser struct { Name string `json:"name,omitempty"` Auth []byte `json:"auth,omitempty"` AuthString string `json:"auth_str,omitempty"` } type HysteriaOutboundOptions struct { DialerOptions ServerOptions Up string `json:"up,omitempty"` UpMbps int `json:"up_mbps,omitempty"` Down string `json:"down,omitempty"` DownMbps int `json:"down_mbps,omitempty"` Obfs string `json:"obfs,omitempty"` Auth []byte `json:"auth,omitempty"` AuthString string `json:"auth_str,omitempty"` ReceiveWindowConn uint64 `json:"recv_window_conn,omitempty"` ReceiveWindow uint64 `json:"recv_window,omitempty"` DisableMTUDiscovery bool `json:"disable_mtu_discovery,omitempty"` Network NetworkList `json:"network,omitempty"` OutboundTLSOptionsContainer }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/tls_acme.go
Bcore/windows/resources/sing-box-main/option/tls_acme.go
package option import ( C "github.com/sagernet/sing-box/constant" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" ) type InboundACMEOptions struct { Domain Listable[string] `json:"domain,omitempty"` DataDirectory string `json:"data_directory,omitempty"` DefaultServerName string `json:"default_server_name,omitempty"` Email string `json:"email,omitempty"` Provider string `json:"provider,omitempty"` DisableHTTPChallenge bool `json:"disable_http_challenge,omitempty"` DisableTLSALPNChallenge bool `json:"disable_tls_alpn_challenge,omitempty"` AlternativeHTTPPort uint16 `json:"alternative_http_port,omitempty"` AlternativeTLSPort uint16 `json:"alternative_tls_port,omitempty"` ExternalAccount *ACMEExternalAccountOptions `json:"external_account,omitempty"` DNS01Challenge *ACMEDNS01ChallengeOptions `json:"dns01_challenge,omitempty"` } type ACMEExternalAccountOptions struct { KeyID string `json:"key_id,omitempty"` MACKey string `json:"mac_key,omitempty"` } type _ACMEDNS01ChallengeOptions struct { Provider string `json:"provider,omitempty"` AliDNSOptions ACMEDNS01AliDNSOptions `json:"-"` CloudflareOptions ACMEDNS01CloudflareOptions `json:"-"` } type ACMEDNS01ChallengeOptions _ACMEDNS01ChallengeOptions func (o ACMEDNS01ChallengeOptions) MarshalJSON() ([]byte, error) { var v any switch o.Provider { case C.DNSProviderAliDNS: v = o.AliDNSOptions case C.DNSProviderCloudflare: v = o.CloudflareOptions case "": return nil, E.New("missing provider type") default: return nil, E.New("unknown provider type: " + o.Provider) } return MarshallObjects((_ACMEDNS01ChallengeOptions)(o), v) } func (o *ACMEDNS01ChallengeOptions) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_ACMEDNS01ChallengeOptions)(o)) if err != nil { return err } var v any switch o.Provider { case C.DNSProviderAliDNS: v = &o.AliDNSOptions case C.DNSProviderCloudflare: v = &o.CloudflareOptions default: return E.New("unknown provider type: " + o.Provider) } err = UnmarshallExcluded(bytes, (*_ACMEDNS01ChallengeOptions)(o), v) if err != nil { return err } return nil } type ACMEDNS01AliDNSOptions struct { AccessKeyID string `json:"access_key_id,omitempty"` AccessKeySecret string `json:"access_key_secret,omitempty"` RegionID string `json:"region_id,omitempty"` } type ACMEDNS01CloudflareOptions struct { APIToken string `json:"api_token,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/udp_over_tcp.go
Bcore/windows/resources/sing-box-main/option/udp_over_tcp.go
package option import ( "github.com/sagernet/sing/common/json" "github.com/sagernet/sing/common/uot" ) type _UDPOverTCPOptions struct { Enabled bool `json:"enabled,omitempty"` Version uint8 `json:"version,omitempty"` } type UDPOverTCPOptions _UDPOverTCPOptions func (o UDPOverTCPOptions) MarshalJSON() ([]byte, error) { switch o.Version { case 0, uot.Version: return json.Marshal(o.Enabled) default: return json.Marshal(_UDPOverTCPOptions(o)) } } func (o *UDPOverTCPOptions) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, &o.Enabled) if err == nil { return nil } return json.UnmarshalDisallowUnknownFields(bytes, (*_UDPOverTCPOptions)(o)) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/inbound.go
Bcore/windows/resources/sing-box-main/option/inbound.go
package option import ( "time" C "github.com/sagernet/sing-box/constant" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" ) type _Inbound struct { Type string `json:"type"` Tag string `json:"tag,omitempty"` TunOptions TunInboundOptions `json:"-"` RedirectOptions RedirectInboundOptions `json:"-"` TProxyOptions TProxyInboundOptions `json:"-"` DirectOptions DirectInboundOptions `json:"-"` SocksOptions SocksInboundOptions `json:"-"` HTTPOptions HTTPMixedInboundOptions `json:"-"` MixedOptions HTTPMixedInboundOptions `json:"-"` ShadowsocksOptions ShadowsocksInboundOptions `json:"-"` VMessOptions VMessInboundOptions `json:"-"` TrojanOptions TrojanInboundOptions `json:"-"` NaiveOptions NaiveInboundOptions `json:"-"` HysteriaOptions HysteriaInboundOptions `json:"-"` ShadowTLSOptions ShadowTLSInboundOptions `json:"-"` VLESSOptions VLESSInboundOptions `json:"-"` TUICOptions TUICInboundOptions `json:"-"` Hysteria2Options Hysteria2InboundOptions `json:"-"` } type Inbound _Inbound func (h *Inbound) RawOptions() (any, error) { var rawOptionsPtr any switch h.Type { case C.TypeTun: rawOptionsPtr = &h.TunOptions case C.TypeRedirect: rawOptionsPtr = &h.RedirectOptions case C.TypeTProxy: rawOptionsPtr = &h.TProxyOptions case C.TypeDirect: rawOptionsPtr = &h.DirectOptions case C.TypeSOCKS: rawOptionsPtr = &h.SocksOptions case C.TypeHTTP: rawOptionsPtr = &h.HTTPOptions case C.TypeMixed: rawOptionsPtr = &h.MixedOptions case C.TypeShadowsocks: rawOptionsPtr = &h.ShadowsocksOptions case C.TypeVMess: rawOptionsPtr = &h.VMessOptions case C.TypeTrojan: rawOptionsPtr = &h.TrojanOptions case C.TypeNaive: rawOptionsPtr = &h.NaiveOptions case C.TypeHysteria: rawOptionsPtr = &h.HysteriaOptions case C.TypeShadowTLS: rawOptionsPtr = &h.ShadowTLSOptions case C.TypeVLESS: rawOptionsPtr = &h.VLESSOptions case C.TypeTUIC: rawOptionsPtr = &h.TUICOptions case C.TypeHysteria2: rawOptionsPtr = &h.Hysteria2Options case "": return nil, E.New("missing inbound type") default: return nil, E.New("unknown inbound type: ", h.Type) } return rawOptionsPtr, nil } func (h Inbound) MarshalJSON() ([]byte, error) { rawOptions, err := h.RawOptions() if err != nil { return nil, err } return MarshallObjects((_Inbound)(h), rawOptions) } func (h *Inbound) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_Inbound)(h)) if err != nil { return err } rawOptions, err := h.RawOptions() if err != nil { return err } err = UnmarshallExcluded(bytes, (*_Inbound)(h), rawOptions) if err != nil { return err } return nil } type InboundOptions struct { SniffEnabled bool `json:"sniff,omitempty"` SniffOverrideDestination bool `json:"sniff_override_destination,omitempty"` SniffTimeout Duration `json:"sniff_timeout,omitempty"` DomainStrategy DomainStrategy `json:"domain_strategy,omitempty"` UDPDisableDomainUnmapping bool `json:"udp_disable_domain_unmapping,omitempty"` } type ListenOptions struct { Listen *ListenAddress `json:"listen,omitempty"` ListenPort uint16 `json:"listen_port,omitempty"` TCPFastOpen bool `json:"tcp_fast_open,omitempty"` TCPMultiPath bool `json:"tcp_multi_path,omitempty"` UDPFragment *bool `json:"udp_fragment,omitempty"` UDPFragmentDefault bool `json:"-"` UDPTimeout UDPTimeoutCompat `json:"udp_timeout,omitempty"` ProxyProtocol bool `json:"proxy_protocol,omitempty"` ProxyProtocolAcceptNoHeader bool `json:"proxy_protocol_accept_no_header,omitempty"` Detour string `json:"detour,omitempty"` InboundOptions } type UDPTimeoutCompat Duration func (c UDPTimeoutCompat) MarshalJSON() ([]byte, error) { return json.Marshal((time.Duration)(c).String()) } func (c *UDPTimeoutCompat) UnmarshalJSON(data []byte) error { var valueNumber int64 err := json.Unmarshal(data, &valueNumber) if err == nil { *c = UDPTimeoutCompat(time.Second * time.Duration(valueNumber)) return nil } return json.Unmarshal(data, (*Duration)(c)) } type ListenOptionsWrapper interface { TakeListenOptions() ListenOptions ReplaceListenOptions(options ListenOptions) } func (o *ListenOptions) TakeListenOptions() ListenOptions { return *o } func (o *ListenOptions) ReplaceListenOptions(options ListenOptions) { *o = options }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/time_unit.go
Bcore/windows/resources/sing-box-main/option/time_unit.go
package option import ( "errors" "time" ) // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. const durationDay = 24 * time.Hour var unitMap = map[string]uint64{ "ns": uint64(time.Nanosecond), "us": uint64(time.Microsecond), "µs": uint64(time.Microsecond), // U+00B5 = micro symbol "μs": uint64(time.Microsecond), // U+03BC = Greek letter mu "ms": uint64(time.Millisecond), "s": uint64(time.Second), "m": uint64(time.Minute), "h": uint64(time.Hour), "d": uint64(durationDay), } // ParseDuration parses a duration string. // A duration string is a possibly signed sequence of // decimal numbers, each with optional fraction and a unit suffix, // such as "300ms", "-1.5h" or "2h45m". // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". func ParseDuration(s string) (Duration, error) { // [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+ orig := s var d uint64 neg := false // Consume [-+]? if s != "" { c := s[0] if c == '-' || c == '+' { neg = c == '-' s = s[1:] } } // Special case: if all that is left is "0", this is zero. if s == "0" { return 0, nil } if s == "" { return 0, errors.New("time: invalid duration " + quote(orig)) } for s != "" { var ( v, f uint64 // integers before, after decimal point scale float64 = 1 // value = v + f/scale ) var err error // The next character must be [0-9.] if !(s[0] == '.' || '0' <= s[0] && s[0] <= '9') { return 0, errors.New("time: invalid duration " + quote(orig)) } // Consume [0-9]* pl := len(s) v, s, err = leadingInt(s) if err != nil { return 0, errors.New("time: invalid duration " + quote(orig)) } pre := pl != len(s) // whether we consumed anything before a period // Consume (\.[0-9]*)? post := false if s != "" && s[0] == '.' { s = s[1:] pl := len(s) f, scale, s = leadingFraction(s) post = pl != len(s) } if !pre && !post { // no digits (e.g. ".s" or "-.s") return 0, errors.New("time: invalid duration " + quote(orig)) } // Consume unit. i := 0 for ; i < len(s); i++ { c := s[i] if c == '.' || '0' <= c && c <= '9' { break } } if i == 0 { return 0, errors.New("time: missing unit in duration " + quote(orig)) } u := s[:i] s = s[i:] unit, ok := unitMap[u] if !ok { return 0, errors.New("time: unknown unit " + quote(u) + " in duration " + quote(orig)) } if v > 1<<63/unit { // overflow return 0, errors.New("time: invalid duration " + quote(orig)) } v *= unit if f > 0 { // float64 is needed to be nanosecond accurate for fractions of hours. // v >= 0 && (f*unit/scale) <= 3.6e+12 (ns/h, h is the largest unit) v += uint64(float64(f) * (float64(unit) / scale)) if v > 1<<63 { // overflow return 0, errors.New("time: invalid duration " + quote(orig)) } } d += v if d > 1<<63 { return 0, errors.New("time: invalid duration " + quote(orig)) } } if neg { return -Duration(d), nil } if d > 1<<63-1 { return 0, errors.New("time: invalid duration " + quote(orig)) } return Duration(d), nil } var errLeadingInt = errors.New("time: bad [0-9]*") // never printed // leadingInt consumes the leading [0-9]* from s. func leadingInt[bytes []byte | string](s bytes) (x uint64, rem bytes, err error) { i := 0 for ; i < len(s); i++ { c := s[i] if c < '0' || c > '9' { break } if x > 1<<63/10 { // overflow return 0, rem, errLeadingInt } x = x*10 + uint64(c) - '0' if x > 1<<63 { // overflow return 0, rem, errLeadingInt } } return x, s[i:], nil } // leadingFraction consumes the leading [0-9]* from s. // It is used only for fractions, so does not return an error on overflow, // it just stops accumulating precision. func leadingFraction(s string) (x uint64, scale float64, rem string) { i := 0 scale = 1 overflow := false for ; i < len(s); i++ { c := s[i] if c < '0' || c > '9' { break } if overflow { continue } if x > (1<<63-1)/10 { // It's possible for overflow to give a positive number, so take care. overflow = true continue } y := x*10 + uint64(c) - '0' if y > 1<<63 { overflow = true continue } x = y scale *= 10 } return x, scale, s[i:] } // These are borrowed from unicode/utf8 and strconv and replicate behavior in // that package, since we can't take a dependency on either. const ( lowerhex = "0123456789abcdef" runeSelf = 0x80 runeError = '\uFFFD' ) func quote(s string) string { buf := make([]byte, 1, len(s)+2) // slice will be at least len(s) + quotes buf[0] = '"' for i, c := range s { if c >= runeSelf || c < ' ' { // This means you are asking us to parse a time.Duration or // time.Location with unprintable or non-ASCII characters in it. // We don't expect to hit this case very often. We could try to // reproduce strconv.Quote's behavior with full fidelity but // given how rarely we expect to hit these edge cases, speed and // conciseness are better. var width int if c == runeError { width = 1 if i+2 < len(s) && s[i:i+3] == string(runeError) { width = 3 } } else { width = len(string(c)) } for j := 0; j < width; j++ { buf = append(buf, `\x`...) buf = append(buf, lowerhex[s[i+j]>>4]) buf = append(buf, lowerhex[s[i+j]&0xF]) } } else { if c == '"' || c == '\\' { buf = append(buf, '\\') } buf = append(buf, string(c)...) } } buf = append(buf, '"') return string(buf) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/ntp.go
Bcore/windows/resources/sing-box-main/option/ntp.go
package option type NTPOptions struct { Enabled bool `json:"enabled,omitempty"` Interval Duration `json:"interval,omitempty"` WriteToSystem bool `json:"write_to_system,omitempty"` ServerOptions DialerOptions }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/rule_set.go
Bcore/windows/resources/sing-box-main/option/rule_set.go
package option import ( "reflect" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/domain" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" "github.com/sagernet/sing/common/json" "go4.org/netipx" ) type _RuleSet struct { Type string `json:"type,omitempty"` Tag string `json:"tag"` Format string `json:"format,omitempty"` InlineOptions PlainRuleSet `json:"-"` LocalOptions LocalRuleSet `json:"-"` RemoteOptions RemoteRuleSet `json:"-"` } type RuleSet _RuleSet func (r RuleSet) MarshalJSON() ([]byte, error) { var v any switch r.Type { case "", C.RuleSetTypeInline: r.Type = "" v = r.InlineOptions case C.RuleSetTypeLocal: v = r.LocalOptions case C.RuleSetTypeRemote: v = r.RemoteOptions default: return nil, E.New("unknown rule-set type: " + r.Type) } return MarshallObjects((_RuleSet)(r), v) } func (r *RuleSet) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_RuleSet)(r)) if err != nil { return err } if r.Tag == "" { return E.New("missing tag") } if r.Type != C.RuleSetTypeInline { switch r.Format { case "": return E.New("missing format") case C.RuleSetFormatSource, C.RuleSetFormatBinary: default: return E.New("unknown rule-set format: " + r.Format) } } else { r.Format = "" } var v any switch r.Type { case "", C.RuleSetTypeInline: r.Type = C.RuleSetTypeInline v = &r.InlineOptions case C.RuleSetTypeLocal: v = &r.LocalOptions case C.RuleSetTypeRemote: v = &r.RemoteOptions default: return E.New("unknown rule-set type: " + r.Type) } err = UnmarshallExcluded(bytes, (*_RuleSet)(r), v) if err != nil { return err } return nil } type LocalRuleSet struct { Path string `json:"path,omitempty"` } type RemoteRuleSet struct { URL string `json:"url"` DownloadDetour string `json:"download_detour,omitempty"` UpdateInterval Duration `json:"update_interval,omitempty"` } type _HeadlessRule struct { Type string `json:"type,omitempty"` DefaultOptions DefaultHeadlessRule `json:"-"` LogicalOptions LogicalHeadlessRule `json:"-"` } type HeadlessRule _HeadlessRule func (r HeadlessRule) MarshalJSON() ([]byte, error) { var v any switch r.Type { case C.RuleTypeDefault: r.Type = "" v = r.DefaultOptions case C.RuleTypeLogical: v = r.LogicalOptions default: return nil, E.New("unknown rule type: " + r.Type) } return MarshallObjects((_HeadlessRule)(r), v) } func (r *HeadlessRule) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_HeadlessRule)(r)) if err != nil { return err } var v any switch r.Type { case "", C.RuleTypeDefault: r.Type = C.RuleTypeDefault v = &r.DefaultOptions case C.RuleTypeLogical: v = &r.LogicalOptions default: return E.New("unknown rule type: " + r.Type) } err = UnmarshallExcluded(bytes, (*_HeadlessRule)(r), v) if err != nil { return err } return nil } func (r HeadlessRule) IsValid() bool { switch r.Type { case C.RuleTypeDefault, "": return r.DefaultOptions.IsValid() case C.RuleTypeLogical: return r.LogicalOptions.IsValid() default: panic("unknown rule type: " + r.Type) } } type DefaultHeadlessRule struct { QueryType Listable[DNSQueryType] `json:"query_type,omitempty"` Network Listable[string] `json:"network,omitempty"` Domain Listable[string] `json:"domain,omitempty"` DomainSuffix Listable[string] `json:"domain_suffix,omitempty"` DomainKeyword Listable[string] `json:"domain_keyword,omitempty"` DomainRegex Listable[string] `json:"domain_regex,omitempty"` SourceIPCIDR Listable[string] `json:"source_ip_cidr,omitempty"` IPCIDR Listable[string] `json:"ip_cidr,omitempty"` SourcePort Listable[uint16] `json:"source_port,omitempty"` SourcePortRange Listable[string] `json:"source_port_range,omitempty"` Port Listable[uint16] `json:"port,omitempty"` PortRange Listable[string] `json:"port_range,omitempty"` ProcessName Listable[string] `json:"process_name,omitempty"` ProcessPath Listable[string] `json:"process_path,omitempty"` ProcessPathRegex Listable[string] `json:"process_path_regex,omitempty"` PackageName Listable[string] `json:"package_name,omitempty"` WIFISSID Listable[string] `json:"wifi_ssid,omitempty"` WIFIBSSID Listable[string] `json:"wifi_bssid,omitempty"` Invert bool `json:"invert,omitempty"` DomainMatcher *domain.Matcher `json:"-"` SourceIPSet *netipx.IPSet `json:"-"` IPSet *netipx.IPSet `json:"-"` AdGuardDomain Listable[string] `json:"-"` AdGuardDomainMatcher *domain.AdGuardMatcher `json:"-"` } func (r DefaultHeadlessRule) IsValid() bool { var defaultValue DefaultHeadlessRule defaultValue.Invert = r.Invert return !reflect.DeepEqual(r, defaultValue) } type LogicalHeadlessRule struct { Mode string `json:"mode"` Rules []HeadlessRule `json:"rules,omitempty"` Invert bool `json:"invert,omitempty"` } func (r LogicalHeadlessRule) IsValid() bool { return len(r.Rules) > 0 && common.All(r.Rules, HeadlessRule.IsValid) } type _PlainRuleSetCompat struct { Version int `json:"version"` Options PlainRuleSet `json:"-"` } type PlainRuleSetCompat _PlainRuleSetCompat func (r PlainRuleSetCompat) MarshalJSON() ([]byte, error) { var v any switch r.Version { case C.RuleSetVersion1, C.RuleSetVersion2: v = r.Options default: return nil, E.New("unknown rule-set version: ", r.Version) } return MarshallObjects((_PlainRuleSetCompat)(r), v) } func (r *PlainRuleSetCompat) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_PlainRuleSetCompat)(r)) if err != nil { return err } var v any switch r.Version { case C.RuleSetVersion1, C.RuleSetVersion2: v = &r.Options case 0: return E.New("missing rule-set version") default: return E.New("unknown rule-set version: ", r.Version) } err = UnmarshallExcluded(bytes, (*_PlainRuleSetCompat)(r), v) if err != nil { return err } return nil } func (r PlainRuleSetCompat) Upgrade() (PlainRuleSet, error) { switch r.Version { case C.RuleSetVersion1, C.RuleSetVersion2: default: return PlainRuleSet{}, E.New("unknown rule-set version: " + F.ToString(r.Version)) } return r.Options, nil } type PlainRuleSet struct { Rules []HeadlessRule `json:"rules,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/vmess.go
Bcore/windows/resources/sing-box-main/option/vmess.go
package option type VMessInboundOptions struct { ListenOptions Users []VMessUser `json:"users,omitempty"` InboundTLSOptionsContainer Multiplex *InboundMultiplexOptions `json:"multiplex,omitempty"` Transport *V2RayTransportOptions `json:"transport,omitempty"` } type VMessUser struct { Name string `json:"name"` UUID string `json:"uuid"` AlterId int `json:"alterId,omitempty"` } type VMessOutboundOptions struct { DialerOptions ServerOptions UUID string `json:"uuid"` Security string `json:"security"` AlterId int `json:"alter_id,omitempty"` GlobalPadding bool `json:"global_padding,omitempty"` AuthenticatedLength bool `json:"authenticated_length,omitempty"` Network NetworkList `json:"network,omitempty"` OutboundTLSOptionsContainer PacketEncoding string `json:"packet_encoding,omitempty"` Multiplex *OutboundMultiplexOptions `json:"multiplex,omitempty"` Transport *V2RayTransportOptions `json:"transport,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/multiplex.go
Bcore/windows/resources/sing-box-main/option/multiplex.go
package option type InboundMultiplexOptions struct { Enabled bool `json:"enabled,omitempty"` Padding bool `json:"padding,omitempty"` Brutal *BrutalOptions `json:"brutal,omitempty"` } type OutboundMultiplexOptions struct { Enabled bool `json:"enabled,omitempty"` Protocol string `json:"protocol,omitempty"` MaxConnections int `json:"max_connections,omitempty"` MinStreams int `json:"min_streams,omitempty"` MaxStreams int `json:"max_streams,omitempty"` Padding bool `json:"padding,omitempty"` Brutal *BrutalOptions `json:"brutal,omitempty"` } type BrutalOptions struct { Enabled bool `json:"enabled,omitempty"` UpMbps int `json:"up_mbps,omitempty"` DownMbps int `json:"down_mbps,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/shadowsocks.go
Bcore/windows/resources/sing-box-main/option/shadowsocks.go
package option type ShadowsocksInboundOptions struct { ListenOptions Network NetworkList `json:"network,omitempty"` Method string `json:"method"` Password string `json:"password,omitempty"` Users []ShadowsocksUser `json:"users,omitempty"` Destinations []ShadowsocksDestination `json:"destinations,omitempty"` Multiplex *InboundMultiplexOptions `json:"multiplex,omitempty"` } type ShadowsocksUser struct { Name string `json:"name"` Password string `json:"password"` } type ShadowsocksDestination struct { Name string `json:"name"` Password string `json:"password"` ServerOptions } type ShadowsocksOutboundOptions struct { DialerOptions ServerOptions Method string `json:"method"` Password string `json:"password"` Plugin string `json:"plugin,omitempty"` PluginOptions string `json:"plugin_opts,omitempty"` Network NetworkList `json:"network,omitempty"` UDPOverTCP *UDPOverTCPOptions `json:"udp_over_tcp,omitempty"` Multiplex *OutboundMultiplexOptions `json:"multiplex,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/group.go
Bcore/windows/resources/sing-box-main/option/group.go
package option type SelectorOutboundOptions struct { Outbounds []string `json:"outbounds"` Default string `json:"default,omitempty"` InterruptExistConnections bool `json:"interrupt_exist_connections,omitempty"` } type URLTestOutboundOptions struct { Outbounds []string `json:"outbounds"` URL string `json:"url,omitempty"` Interval Duration `json:"interval,omitempty"` Tolerance uint16 `json:"tolerance,omitempty"` IdleTimeout Duration `json:"idle_timeout,omitempty"` InterruptExistConnections bool `json:"interrupt_exist_connections,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/types.go
Bcore/windows/resources/sing-box-main/option/types.go
package option import ( "net/http" "net/netip" "strings" "time" "github.com/sagernet/sing-dns" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" "github.com/sagernet/sing/common/json" N "github.com/sagernet/sing/common/network" mDNS "github.com/miekg/dns" ) type ListenAddress netip.Addr func NewListenAddress(addr netip.Addr) *ListenAddress { address := ListenAddress(addr) return &address } func (a ListenAddress) MarshalJSON() ([]byte, error) { addr := netip.Addr(a) if !addr.IsValid() { return nil, nil } return json.Marshal(addr.String()) } func (a *ListenAddress) UnmarshalJSON(content []byte) error { var value string err := json.Unmarshal(content, &value) if err != nil { return err } addr, err := netip.ParseAddr(value) if err != nil { return err } *a = ListenAddress(addr) return nil } func (a *ListenAddress) Build() netip.Addr { if a == nil { return netip.AddrFrom4([4]byte{127, 0, 0, 1}) } return (netip.Addr)(*a) } type AddrPrefix netip.Prefix func (a AddrPrefix) MarshalJSON() ([]byte, error) { prefix := netip.Prefix(a) if prefix.Bits() == prefix.Addr().BitLen() { return json.Marshal(prefix.Addr().String()) } else { return json.Marshal(prefix.String()) } } func (a *AddrPrefix) UnmarshalJSON(content []byte) error { var value string err := json.Unmarshal(content, &value) if err != nil { return err } prefix, prefixErr := netip.ParsePrefix(value) if prefixErr == nil { *a = AddrPrefix(prefix) return nil } addr, addrErr := netip.ParseAddr(value) if addrErr == nil { *a = AddrPrefix(netip.PrefixFrom(addr, addr.BitLen())) return nil } return prefixErr } func (a AddrPrefix) Build() netip.Prefix { return netip.Prefix(a) } type NetworkList string func (v *NetworkList) UnmarshalJSON(content []byte) error { var networkList []string err := json.Unmarshal(content, &networkList) if err != nil { var networkItem string err = json.Unmarshal(content, &networkItem) if err != nil { return err } networkList = []string{networkItem} } for _, networkName := range networkList { switch networkName { case N.NetworkTCP, N.NetworkUDP: break default: return E.New("unknown network: " + networkName) } } *v = NetworkList(strings.Join(networkList, "\n")) return nil } func (v NetworkList) Build() []string { if v == "" { return []string{N.NetworkTCP, N.NetworkUDP} } return strings.Split(string(v), "\n") } type Listable[T any] []T func (l Listable[T]) MarshalJSON() ([]byte, error) { arrayList := []T(l) if len(arrayList) == 1 { return json.Marshal(arrayList[0]) } return json.Marshal(arrayList) } func (l *Listable[T]) UnmarshalJSON(content []byte) error { err := json.UnmarshalDisallowUnknownFields(content, (*[]T)(l)) if err == nil { return nil } var singleItem T newError := json.UnmarshalDisallowUnknownFields(content, &singleItem) if newError != nil { return E.Errors(err, newError) } *l = []T{singleItem} return nil } type DomainStrategy dns.DomainStrategy func (s DomainStrategy) MarshalJSON() ([]byte, error) { var value string switch dns.DomainStrategy(s) { case dns.DomainStrategyAsIS: value = "" // value = "AsIS" case dns.DomainStrategyPreferIPv4: value = "prefer_ipv4" case dns.DomainStrategyPreferIPv6: value = "prefer_ipv6" case dns.DomainStrategyUseIPv4: value = "ipv4_only" case dns.DomainStrategyUseIPv6: value = "ipv6_only" default: return nil, E.New("unknown domain strategy: ", s) } return json.Marshal(value) } func (s *DomainStrategy) UnmarshalJSON(bytes []byte) error { var value string err := json.Unmarshal(bytes, &value) if err != nil { return err } switch value { case "", "as_is": *s = DomainStrategy(dns.DomainStrategyAsIS) case "prefer_ipv4": *s = DomainStrategy(dns.DomainStrategyPreferIPv4) case "prefer_ipv6": *s = DomainStrategy(dns.DomainStrategyPreferIPv6) case "ipv4_only": *s = DomainStrategy(dns.DomainStrategyUseIPv4) case "ipv6_only": *s = DomainStrategy(dns.DomainStrategyUseIPv6) default: return E.New("unknown domain strategy: ", value) } return nil } type Duration time.Duration func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal((time.Duration)(d).String()) } func (d *Duration) UnmarshalJSON(bytes []byte) error { var value string err := json.Unmarshal(bytes, &value) if err != nil { return err } duration, err := ParseDuration(value) if err != nil { return err } *d = Duration(duration) return nil } type DNSQueryType uint16 func (t DNSQueryType) String() string { typeName, loaded := mDNS.TypeToString[uint16(t)] if loaded { return typeName } return F.ToString(uint16(t)) } func (t DNSQueryType) MarshalJSON() ([]byte, error) { typeName, loaded := mDNS.TypeToString[uint16(t)] if loaded { return json.Marshal(typeName) } return json.Marshal(uint16(t)) } func (t *DNSQueryType) UnmarshalJSON(bytes []byte) error { var valueNumber uint16 err := json.Unmarshal(bytes, &valueNumber) if err == nil { *t = DNSQueryType(valueNumber) return nil } var valueString string err = json.Unmarshal(bytes, &valueString) if err == nil { queryType, loaded := mDNS.StringToType[valueString] if loaded { *t = DNSQueryType(queryType) return nil } } return E.New("unknown DNS query type: ", string(bytes)) } func DNSQueryTypeToString(queryType uint16) string { typeName, loaded := mDNS.TypeToString[queryType] if loaded { return typeName } return F.ToString(queryType) } type HTTPHeader map[string]Listable[string] func (h HTTPHeader) Build() http.Header { header := make(http.Header) for name, values := range h { for _, value := range values { header.Add(name, value) } } return header }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/v2ray_transport.go
Bcore/windows/resources/sing-box-main/option/v2ray_transport.go
package option import ( C "github.com/sagernet/sing-box/constant" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" ) type _V2RayTransportOptions struct { Type string `json:"type"` HTTPOptions V2RayHTTPOptions `json:"-"` WebsocketOptions V2RayWebsocketOptions `json:"-"` QUICOptions V2RayQUICOptions `json:"-"` GRPCOptions V2RayGRPCOptions `json:"-"` HTTPUpgradeOptions V2RayHTTPUpgradeOptions `json:"-"` } type V2RayTransportOptions _V2RayTransportOptions func (o V2RayTransportOptions) MarshalJSON() ([]byte, error) { var v any switch o.Type { case C.V2RayTransportTypeHTTP: v = o.HTTPOptions case C.V2RayTransportTypeWebsocket: v = o.WebsocketOptions case C.V2RayTransportTypeQUIC: v = o.QUICOptions case C.V2RayTransportTypeGRPC: v = o.GRPCOptions case C.V2RayTransportTypeHTTPUpgrade: v = o.HTTPUpgradeOptions case "": return nil, E.New("missing transport type") default: return nil, E.New("unknown transport type: " + o.Type) } return MarshallObjects((_V2RayTransportOptions)(o), v) } func (o *V2RayTransportOptions) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_V2RayTransportOptions)(o)) if err != nil { return err } var v any switch o.Type { case C.V2RayTransportTypeHTTP: v = &o.HTTPOptions case C.V2RayTransportTypeWebsocket: v = &o.WebsocketOptions case C.V2RayTransportTypeQUIC: v = &o.QUICOptions case C.V2RayTransportTypeGRPC: v = &o.GRPCOptions case C.V2RayTransportTypeHTTPUpgrade: v = &o.HTTPUpgradeOptions default: return E.New("unknown transport type: " + o.Type) } err = UnmarshallExcluded(bytes, (*_V2RayTransportOptions)(o), v) if err != nil { return err } return nil } type V2RayHTTPOptions struct { Host Listable[string] `json:"host,omitempty"` Path string `json:"path,omitempty"` Method string `json:"method,omitempty"` Headers HTTPHeader `json:"headers,omitempty"` IdleTimeout Duration `json:"idle_timeout,omitempty"` PingTimeout Duration `json:"ping_timeout,omitempty"` } type V2RayWebsocketOptions struct { Path string `json:"path,omitempty"` Headers HTTPHeader `json:"headers,omitempty"` MaxEarlyData uint32 `json:"max_early_data,omitempty"` EarlyDataHeaderName string `json:"early_data_header_name,omitempty"` } type V2RayQUICOptions struct{} type V2RayGRPCOptions struct { ServiceName string `json:"service_name,omitempty"` IdleTimeout Duration `json:"idle_timeout,omitempty"` PingTimeout Duration `json:"ping_timeout,omitempty"` PermitWithoutStream bool `json:"permit_without_stream,omitempty"` ForceLite bool `json:"-"` // for test } type V2RayHTTPUpgradeOptions struct { Host string `json:"host,omitempty"` Path string `json:"path,omitempty"` Headers HTTPHeader `json:"headers,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/tun_platform.go
Bcore/windows/resources/sing-box-main/option/tun_platform.go
package option type TunPlatformOptions struct { HTTPProxy *HTTPProxyOptions `json:"http_proxy,omitempty"` } type HTTPProxyOptions struct { Enabled bool `json:"enabled,omitempty"` ServerOptions BypassDomain Listable[string] `json:"bypass_domain,omitempty"` MatchDomain Listable[string] `json:"match_domain,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/config.go
Bcore/windows/resources/sing-box-main/option/config.go
package option import ( "bytes" "github.com/sagernet/sing/common/json" ) type _Options struct { RawMessage json.RawMessage `json:"-"` Schema string `json:"$schema,omitempty"` Log *LogOptions `json:"log,omitempty"` DNS *DNSOptions `json:"dns,omitempty"` NTP *NTPOptions `json:"ntp,omitempty"` Inbounds []Inbound `json:"inbounds,omitempty"` Outbounds []Outbound `json:"outbounds,omitempty"` Route *RouteOptions `json:"route,omitempty"` Experimental *ExperimentalOptions `json:"experimental,omitempty"` } type Options _Options func (o *Options) UnmarshalJSON(content []byte) error { decoder := json.NewDecoder(bytes.NewReader(content)) decoder.DisallowUnknownFields() err := decoder.Decode((*_Options)(o)) if err != nil { return err } o.RawMessage = content return nil } type LogOptions struct { Disabled bool `json:"disabled,omitempty"` Level string `json:"level,omitempty"` Output string `json:"output,omitempty"` Timestamp bool `json:"timestamp,omitempty"` DisableColor bool `json:"-"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/ssh.go
Bcore/windows/resources/sing-box-main/option/ssh.go
package option type SSHOutboundOptions struct { DialerOptions ServerOptions User string `json:"user,omitempty"` Password string `json:"password,omitempty"` PrivateKey Listable[string] `json:"private_key,omitempty"` PrivateKeyPath string `json:"private_key_path,omitempty"` PrivateKeyPassphrase string `json:"private_key_passphrase,omitempty"` HostKey Listable[string] `json:"host_key,omitempty"` HostKeyAlgorithms Listable[string] `json:"host_key_algorithms,omitempty"` ClientVersion string `json:"client_version,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/vless.go
Bcore/windows/resources/sing-box-main/option/vless.go
package option type VLESSInboundOptions struct { ListenOptions Users []VLESSUser `json:"users,omitempty"` InboundTLSOptionsContainer Multiplex *InboundMultiplexOptions `json:"multiplex,omitempty"` Transport *V2RayTransportOptions `json:"transport,omitempty"` } type VLESSUser struct { Name string `json:"name"` UUID string `json:"uuid"` Flow string `json:"flow,omitempty"` } type VLESSOutboundOptions struct { DialerOptions ServerOptions UUID string `json:"uuid"` Flow string `json:"flow,omitempty"` Network NetworkList `json:"network,omitempty"` OutboundTLSOptionsContainer Multiplex *OutboundMultiplexOptions `json:"multiplex,omitempty"` Transport *V2RayTransportOptions `json:"transport,omitempty"` PacketEncoding *string `json:"packet_encoding,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/naive.go
Bcore/windows/resources/sing-box-main/option/naive.go
package option import "github.com/sagernet/sing/common/auth" type NaiveInboundOptions struct { ListenOptions Users []auth.User `json:"users,omitempty"` Network NetworkList `json:"network,omitempty"` InboundTLSOptionsContainer }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/v2ray.go
Bcore/windows/resources/sing-box-main/option/v2ray.go
package option
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/option/dns.go
Bcore/windows/resources/sing-box-main/option/dns.go
package option import "net/netip" type DNSOptions struct { Servers []DNSServerOptions `json:"servers,omitempty"` Rules []DNSRule `json:"rules,omitempty"` Final string `json:"final,omitempty"` ReverseMapping bool `json:"reverse_mapping,omitempty"` FakeIP *DNSFakeIPOptions `json:"fakeip,omitempty"` DNSClientOptions } type DNSServerOptions struct { Tag string `json:"tag,omitempty"` Address string `json:"address"` AddressResolver string `json:"address_resolver,omitempty"` AddressStrategy DomainStrategy `json:"address_strategy,omitempty"` AddressFallbackDelay Duration `json:"address_fallback_delay,omitempty"` Strategy DomainStrategy `json:"strategy,omitempty"` Detour string `json:"detour,omitempty"` ClientSubnet *AddrPrefix `json:"client_subnet,omitempty"` } type DNSClientOptions struct { Strategy DomainStrategy `json:"strategy,omitempty"` DisableCache bool `json:"disable_cache,omitempty"` DisableExpire bool `json:"disable_expire,omitempty"` IndependentCache bool `json:"independent_cache,omitempty"` ClientSubnet *AddrPrefix `json:"client_subnet,omitempty"` } type DNSFakeIPOptions struct { Enabled bool `json:"enabled,omitempty"` Inet4Range *netip.Prefix `json:"inet4_range,omitempty"` Inet6Range *netip.Prefix `json:"inet6_range,omitempty"` }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false