Trim repo

This commit is contained in:
世界 2022-05-25 12:08:02 +08:00
parent 8697b84d59
commit d4b1e219c0
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
89 changed files with 121 additions and 10987 deletions

View file

@ -21,9 +21,13 @@ jobs:
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Install Golang
- name: Get latest go version
id: version
run: |
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
- name: Setup Go
uses: actions/setup-go@v2
with:
go-version: 1.18.1
go-version: ${{ steps.version.outputs.go_version }}
- name: Build
run: make
run: go build -v ./...

6
.gitignore vendored
View file

@ -1,8 +1,2 @@
/.idea/
/sing_*
/*.json
/Country.mmdb
/geosite.dat
/vendor/
/acme/
/bin/

View file

@ -1,12 +0,0 @@
.DEFAULT_GOAL := debug
clean:
rm -rf ./bin
debug:
go run ./cli/buildx --name ss-local --path ./cli/ss-local
go run ./cli/buildx --name ss-server --path ./cli/ss-server
release:
go run ./cli/buildx --name ss-local --path ./cli/ss-local --release
go run ./cli/buildx --name ss-server --path ./cli/ss-server --release

View file

@ -1,193 +0,0 @@
package main
import (
"archive/tar"
"io"
"os"
"os/exec"
"path/filepath"
"github.com/klauspost/compress/zip"
"github.com/sagernet/sing/common/log"
"github.com/spf13/cobra"
"github.com/ulikunitz/xz"
)
var logger = log.NewLogger("buildx")
var (
appName string
appPath string
outputDir string
buildRelease bool
)
func main() {
command := &cobra.Command{
Use: "buildx",
Run: build,
}
command.Flags().StringVar(&appName, "name", "", "binary name")
command.Flags().StringVar(&appPath, "path", "", "program path")
command.Flags().StringVar(&outputDir, "output", "bin", "output directory")
command.Flags().BoolVar(&buildRelease, "release", false, "build release archives")
if err := command.Execute(); err != nil {
logger.Fatal(err)
}
}
func build(cmd *cobra.Command, args []string) {
err := buildOne(appName, appPath, outputDir, buildRelease)
if err != nil {
logger.Fatal(err)
}
}
type goBuildTarget struct {
name string
os string
arch string
extEnv []string
}
func t(name string, os string, arch string, extEnv ...string) goBuildTarget {
return goBuildTarget{
name: name,
os: os,
arch: arch,
extEnv: extEnv,
}
}
var commonTargets = []goBuildTarget{
t("android-x86_64", "android", "amd64", "GOAMD64=v3"),
t("android-x86", "android", "386"),
t("android-arm64-v8a", "android", "arm64"),
t("android-armeabi-v7a", "android", "arm", "GOARM=7"),
t("linux-x86_64", "linux", "amd64", "GOAMD64=v3"),
t("linux-x86", "linux", "386"),
t("linux-arm64-v8a", "linux", "arm64"),
t("linux-armeabi-v7a", "linux", "arm", "GOARM=7"),
t("windows-x86_64", "windows", "amd64", "GOAMD64=v3"),
t("windows-x86", "windows", "386"),
t("windows-arm64-v8a", "windows", "arm64"),
t("darwin-x86_64", "darwin", "amd64", "GOAMD64=v3"),
t("darwin-arm64-v8a", "darwin", "arm64"),
}
func buildOne(app string, appPath string, outputDir string, release bool) error {
tmpDir, err := os.MkdirTemp("", "sing-build")
if err != nil {
return err
}
for _, t := range commonTargets {
logger.Info(">> ", app, "-", t.name)
env := t.extEnv
env = append(env, "GOOS+"+t.os)
env = append(env, "GOARCH="+t.arch)
env = append(env, "CGO_ENABLED=0")
if !release {
err = run("go", env, "build",
"-trimpath", "-ldflags", "-w -s -buildid=",
"-v", "-o", outputDir+"/"+app+"-"+t.name, appPath)
if err != nil {
return err
}
continue
}
cache := tmpDir + "/" + app + "-" + t.name
if t.os == "windows" {
cache += ".exe"
}
output := outputDir + "/" + app + "-" + t.name
err = run("go", env, "build",
"-trimpath", "-ldflags", "-w -s -buildid=",
"-v", "-o", cache, appPath)
if err != nil {
return err
}
binary, err := os.Open(cache)
if err != nil {
return err
}
binaryInfo, err := os.Stat(cache)
if err != nil {
return err
}
err = os.MkdirAll("bin", 0o755)
if err != nil {
return err
}
if t.os != "windows" {
binaryPackage, err := os.Create(output + ".tar.xz")
if err != nil {
return err
}
xzConfig := &xz.WriterConfig{
DictCap: 1 << 26,
CheckSum: xz.SHA256,
}
xzWrtier, err := xzConfig.NewWriter(binaryPackage)
if err != nil {
return err
}
tarWriter := tar.NewWriter(xzWrtier)
tarHeader, err := tar.FileInfoHeader(binaryInfo, "")
if err != nil {
return err
}
tarHeader.Name = filepath.Base(tarHeader.Name)
err = tarWriter.WriteHeader(tarHeader)
if err != nil {
return err
}
_, err = io.Copy(tarWriter, binary)
if err != nil {
return err
}
tarWriter.Close()
xzWrtier.Close()
binaryPackage.Close()
binary.Close()
} else {
binaryPackage, err := os.Create(output + ".zip")
if err != nil {
return err
}
zipHeader, err := zip.FileInfoHeader(binaryInfo)
if err != nil {
return err
}
zipHeader.Name = filepath.Base(zipHeader.Name)
zipWriter := zip.NewWriter(binaryPackage)
fileWriter, err := zipWriter.CreateHeader(zipHeader)
if err != nil {
return err
}
_, err = io.Copy(fileWriter, binary)
if err != nil {
return err
}
zipWriter.Close()
binaryPackage.Close()
binary.Close()
}
}
os.RemoveAll(tmpDir)
return nil
}
func run(name string, env []string, args ...string) error {
command := exec.Command(name, args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
command.Env = append(env, os.Environ()...)
return command.Run()
}

View file

@ -1 +0,0 @@
/config.json

View file

@ -1,6 +0,0 @@
{
"cloudflare_api_key": "",
"cloudflare_api_email": "",
"domain": "example.com",
"over_proxy": false
}

View file

@ -1,11 +0,0 @@
[Unit]
Description=DDNS Service
After=network.target
[Service]
ExecStart=/usr/local/bin/cloudflare-ddns -c /usr/local/etc/ddns.json
Restart=on-failure
RestartPreventExitStatus=23
[Install]
WantedBy=multi-user.target

View file

@ -1,160 +0,0 @@
//go:build linux
package main
import (
"context"
"encoding/json"
"io/ioutil"
"net/netip"
"strings"
"github.com/cloudflare/cloudflare-go"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
_ "github.com/sagernet/sing/common/log"
N "github.com/sagernet/sing/common/network"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/vishvananda/netlink"
)
var configPath string
func main() {
command := &cobra.Command{
Use: "cloudflare-ddns [-c config.json]",
Run: run,
Version: sing.VersionStr,
}
command.Flags().StringVarP(&configPath, "config", "c", "config.json", "set config path")
if err := command.Execute(); err != nil {
logrus.Fatal(err)
}
}
type Config struct {
APIKey string `json:"api_key"`
APIEmail string `json:"api_email"`
Domain string `json:"domain"`
OverProxy bool `json:"over_proxy"`
}
var (
domain string
overProxy bool
)
var (
flare *cloudflare.API
zone *cloudflare.Zone
)
func run(cmd *cobra.Command, args []string) {
c := new(Config)
cc, err := ioutil.ReadFile(configPath)
if err != nil {
logrus.Fatal(err)
}
err = json.Unmarshal(cc, c)
if err != nil {
logrus.Fatal(err)
}
domain = c.Domain
overProxy = c.OverProxy
flare, err = cloudflare.New(c.APIKey, c.APIEmail)
if err != nil {
logrus.Fatal(err)
}
zone, err = findZoneForDomain(domain)
if err != nil {
logrus.Fatal(err)
}
checkUpdate()
events := make(chan netlink.AddrUpdate, 1)
err = netlink.AddrSubscribe(events, nil)
if err != nil {
logrus.Fatal(err)
}
for event := range events {
addr, _ := netip.AddrFromSlice(event.LinkAddress.IP)
if !N.IsPublicAddr(addr) {
continue
}
checkUpdate()
}
}
func findZoneForDomain(domain string) (*cloudflare.Zone, error) {
zones, err := flare.ListZones(context.Background())
if err != nil {
return nil, err
}
for _, z := range zones {
if strings.HasSuffix(domain, z.Name) {
return &z, nil
}
}
return nil, E.New("unable to find zone for domain ", domain)
}
func checkUpdate() {
addrs, err := N.LocalPublicAddrs()
if err != nil {
logrus.Fatal(err)
}
addrMap := make(map[string]netip.Addr)
for _, addr := range addrs {
addrMap[addr.String()] = addr
}
if common.IsEmpty(addrs) {
logrus.Warn("this device has no public addresses!")
}
records, err := flare.DNSRecords(context.Background(), zone.ID, cloudflare.DNSRecord{
Name: domain,
})
if err != nil {
logrus.Fatal(err)
}
for _, record := range records {
if !(record.Type == "A" || record.Type == "AAAA") {
continue
}
if _, exists := addrMap[record.Content]; !exists || record.Proxied == nil && overProxy || record.Proxied != nil && *record.Proxied != overProxy {
logrus.Info("Deleting ", record.Type, " ", record.Content)
err = flare.DeleteDNSRecord(context.Background(), zone.ID, record.ID)
if err != nil {
logrus.Fatal(err)
}
} else {
delete(addrMap, record.Content)
}
}
for content, addr := range addrMap {
record := cloudflare.DNSRecord{
Name: domain,
Content: content,
Proxied: &overProxy,
TTL: 60,
}
if addr.Is4() {
record.Type = "A"
} else {
record.Type = "AAAA"
}
logrus.Info("Adding ", record)
_, err = flare.CreateDNSRecord(context.Background(), zone.ID, record)
if err != nil {
logrus.Fatal(err)
}
}
}

View file

@ -1,27 +0,0 @@
package main
import (
"crypto/rand"
"encoding/base64"
"io"
"os"
"strconv"
"github.com/sirupsen/logrus"
)
func main() {
var size int
if len(os.Args) > 1 {
size, _ = strconv.Atoi(os.Args[1])
}
if size == 0 {
size = 32
}
psk := make([]byte, size)
_, err := io.ReadFull(rand.Reader, psk)
if err != nil {
logrus.Fatal(err)
}
os.Stdout.WriteString(base64.StdEncoding.EncodeToString(psk))
}

View file

@ -1,213 +0,0 @@
package main
import (
"bytes"
"io/ioutil"
"os"
"strings"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/geosite"
_ "github.com/sagernet/sing/common/log"
N "github.com/sagernet/sing/common/network"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/ulikunitz/xz"
"github.com/v2fly/v2ray-core/v5/app/router/routercommon"
"google.golang.org/protobuf/proto"
)
var path string
func main() {
command := &cobra.Command{
Use: "geosite ...",
}
command.PersistentFlags().StringVarP(&path, "file", "f", "geosite.dat", "set resource path")
command.AddCommand(&cobra.Command{
Use: "list",
Short: "List codes",
PreRun: load,
Run: edit,
})
command.AddCommand(&cobra.Command{
Use: "keep",
Short: "Keep selected codes",
PreRun: load,
Run: keep,
Args: cobra.MinimumNArgs(1),
})
command.AddCommand(&cobra.Command{
Use: "add <v2ray | loyalsoldier | path | url> [code]...",
Short: "Add codes form external file or url",
PreRun: load0,
Run: add,
Args: cobra.MinimumNArgs(1),
})
if err := command.Execute(); err != nil {
logrus.Fatal(err)
}
}
var site map[string][]string
func load(cmd *cobra.Command, args []string) {
geoFile, err := os.Open(path)
if err != nil {
logrus.Fatal(E.Cause(err, "open geo resources"))
}
defer geoFile.Close()
site, err = geosite.Read(geoFile)
if err != nil {
logrus.Fatal(E.Cause(err, "read geo resources"))
}
}
func load0(cmd *cobra.Command, args []string) {
geoFile, err := os.Open(path)
if err == nil {
defer geoFile.Close()
site, err = geosite.Read(geoFile)
if err != nil {
logrus.Fatal(E.Cause(err, "read geo resources"))
}
}
site = make(map[string][]string)
}
func edit(cmd *cobra.Command, args []string) {
for code := range site {
println(strings.ToLower(code))
}
}
func keep(cmd *cobra.Command, args []string) {
kept := make(map[string][]string)
for _, code := range args {
code = strings.ToUpper(code)
if domains, exists := site[code]; exists {
kept[code] = domains
} else {
logrus.Fatal("code ", strings.ToLower(code), " do not exists!")
}
}
geoFile, err := os.Create(path)
if err != nil {
logrus.Fatal(err)
}
defer geoFile.Close()
err = geosite.Write(geoFile, kept)
if err != nil {
logrus.Fatal(err)
}
}
func add(cmd *cobra.Command, args []string) {
resource := args[0]
find:
switch resource {
case "v2ray":
for _, dir := range []string{
"/usr/share/v2ray",
"/usr/local/share/v2ray",
"/opt/share/v2ray",
} {
file := dir + "/geosite.dat"
if common.FileExists(file) {
resource = file
break find
}
}
resource = "https://github.com/v2fly/domain-list-community/releases/latest/download/dlc.dat.xz"
case "loyalsoldier":
resource = "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat"
}
var data []byte
var err error
if strings.HasPrefix(resource, "http://") || strings.HasPrefix(resource, "https://") {
logrus.Info("download ", resource)
data, err = N.Get(resource)
if err != nil {
logrus.Fatal(err)
}
} else {
logrus.Info("open ", resource)
file, err := os.Open(resource)
if err != nil {
logrus.Fatal(err)
}
data, err = ioutil.ReadAll(file)
file.Close()
if err != nil {
logrus.Fatal("read ", resource, ": ", err)
}
}
{
if strings.HasSuffix(resource, ".xz") {
decoder, err := xz.NewReader(bytes.NewReader(data))
if err == nil {
data, _ = ioutil.ReadAll(decoder)
}
}
}
loaded := make(map[string][]string)
{
geositeList := routercommon.GeoSiteList{}
err = proto.Unmarshal(data, &geositeList)
if err == nil {
for _, geoSite := range geositeList.Entry {
domains := make([]string, 0, len(geoSite.Domain))
for _, domain := range geoSite.Domain {
if domain.Type == routercommon.Domain_Full {
domains = append(domains, domain.Value)
} else if domain.Type == routercommon.Domain_RootDomain {
domains = append(domains, "+."+domain.Value)
} else if domain.Type == routercommon.Domain_Plain {
logrus.Warn("ignore match rule ", geoSite.CountryCode, " ", domain.Value)
} else {
domains = append(domains, "regexp:"+domain.Value)
}
}
loaded[strings.ToLower(geoSite.CountryCode)] = common.Uniq(domains)
}
goto finish
}
}
{
loaded, _ = geosite.Read(bytes.NewReader(data))
}
finish:
if len(loaded) == 0 {
logrus.Fatal("unknown resource format")
}
if len(args) > 1 {
for _, code := range args[1:] {
code = strings.ToLower(code)
if domains, exists := loaded[code]; exists {
site[code] = domains
} else {
logrus.Fatal("code ", code, " do not exists!")
}
}
} else {
for code, domains := range loaded {
site[code] = domains
}
}
for code, domains := range site {
site[code] = common.Uniq(domains)
}
geoFile, err := os.Create(path)
if err != nil {
logrus.Fatal(err)
}
defer geoFile.Close()
err = geosite.Write(geoFile, site)
if err != nil {
logrus.Fatal(err)
}
logrus.Info("saved ", path)
}

View file

@ -1,336 +0,0 @@
package main
import (
"archive/tar"
_ "embed"
"encoding/hex"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"github.com/klauspost/compress/zstd"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/log"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/u-root/u-root/pkg/ldd"
)
var logger = log.NewLogger("libpack")
var (
packageName string
executablePath string
outputPath string
)
func main() {
command := &cobra.Command{
Use: "libpack",
Version: sing.VersionStr,
Run: run0,
}
command.Flags().StringVarP(&executablePath, "input", "i", "", "input path (required)")
command.MarkFlagRequired("input")
command.Flags().StringVarP(&outputPath, "output", "o", "", "output path (default: input path)")
command.Flags().StringVarP(&packageName, "package", "p", "", "package name (default: executable name)")
if err := command.Execute(); err != nil {
logger.Fatal(err)
}
}
func run0(cmd *cobra.Command, args []string) {
err := run1()
if err != nil {
logger.Fatal(err)
}
}
var skipPaths = []string{
"/usr/lib",
"/usr/lib64",
}
func run1() error {
os.Setenv("LD_LIBRARY_PATH", os.ExpandEnv("$LD_LIBRARY_PATH:/usr/local/lib:$PWD"))
realPath, err := filepath.Abs(executablePath)
if err != nil {
return E.Cause(err, executablePath, " not found")
}
realName := filepath.Base(realPath)
if outputPath == "" {
outputPath = realPath
}
if packageName == "" {
packageName = realName
}
outputPath, err = filepath.Abs(outputPath)
if err != nil {
return err
}
cachePath, err := os.MkdirTemp("", "libpack")
if err != nil {
return err
}
defer os.RemoveAll(cachePath)
contentFile, err := os.Create(cachePath + "/content")
if err != nil {
return err
}
writer, err := zstd.NewWriter(contentFile, zstd.WithEncoderLevel(zstd.SpeedBestCompression))
if err != nil {
return err
}
var ldName string
tarWriter := tar.NewWriter(writer)
libs, err := ldd.Ldd([]string{realPath})
if err != nil {
return err
}
libs = common.Filter(libs, func(it *ldd.FileInfo) bool {
if strings.HasPrefix(it.Name(), "ld-") {
ldName = it.Name()
return false
}
for _, path := range skipPaths {
if strings.HasPrefix(it.FullName, path) {
logrus.Info(">> skipped ", it.FullName)
return false
}
}
return true
})
if ldName == "" {
for _, lib := range libs {
logrus.Info(lib.FullName)
}
logrus.Fatal("not a dynamically linked executable i thk")
}
sort.Slice(libs, func(i, j int) bool {
lName := filepath.Base(libs[i].FullName)
rName := filepath.Base(libs[j].FullName)
if lName == realName {
return false
} else if rName == realName {
return true
}
return lName > rName
})
for _, lib := range libs {
libName := filepath.Base(lib.FullName)
header, err := tar.FileInfoHeader(lib.FileInfo, "")
if err != nil {
return err
}
libFile, err := os.Open(lib.FullName)
if err != nil {
return err
}
if strings.HasPrefix(libName, "libc") {
logger.Info(">> ", libName)
header.Name = libName
err = tarWriter.WriteHeader(header)
if err != nil {
return err
}
_, err = io.CopyN(tarWriter, libFile, header.Size)
if err != nil {
return err
}
libFile.Close()
continue
} else {
cacheFile, err := os.Create(cachePath + "/" + libName)
if err != nil {
return err
}
_, err = io.CopyN(cacheFile, libFile, header.Size)
if err != nil {
return err
}
libFile.Close()
cacheFile.Close()
err = runAs(cachePath, "strip", "-s", libName)
if err != nil {
return err
}
cacheFile, err = os.Open(cachePath + "/" + libName)
if err != nil {
return err
}
libInfo, err := cacheFile.Stat()
if err != nil {
return err
}
if libName == realName {
libName = packageName
}
logger.Info(">> ", libName)
header.Name = libName
header.Size = libInfo.Size()
err = tarWriter.WriteHeader(header)
if err != nil {
return err
}
_, err = io.CopyN(tarWriter, cacheFile, header.Size)
if err != nil {
return err
}
cacheFile.Close()
}
}
err = tarWriter.Close()
if err != nil {
return err
}
err = writer.Close()
if err != nil {
return err
}
err = contentFile.Close()
if err != nil {
return err
}
hash, err := common.SHA224File(cachePath + "/content")
if err != nil {
return err
}
err = common.WriteFile(cachePath+"/main.go", []byte(`package main
import (
"archive/tar"
"bytes"
_ "embed"
"io"
"log"
"os"
"syscall"
"github.com/klauspost/compress/zstd"
"github.com/sagernet/sing/common"
)
//go:embed content
var content []byte
const (
execName = "`+packageName+`"
hash = "`+hex.EncodeToString(hash)+`"
)
var (
basePath = os.TempDir() + "/.sing/" + execName
dirPath = basePath + "/" + hash
execPath = dirPath + "/" + execName
)
func main() {
log.SetFlags(0)
err := os.Setenv("LD_LIBRARY_PATH", dirPath)
if err != nil {
log.Fatalln(err)
}
err = main0()
if err != nil {
log.Fatalln(err)
}
}
//noinspection GoBoolExpressions
func main0() error {
if !common.FileExists(dirPath + "/" + hash) {
os.RemoveAll(basePath)
}
if common.FileExists(execPath) {
return syscall.Exec(execPath, os.Args, os.Environ())
}
os.RemoveAll(basePath)
os.MkdirAll(dirPath, 0o755)
reader, err := zstd.NewReader(bytes.NewReader(content))
if err != nil {
return err
}
tarReader := tar.NewReader(reader)
for {
header, err := tarReader.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
if header.FileInfo().IsDir() {
os.MkdirAll(dirPath+"/"+header.Name, 0o755)
continue
}
libFile, err := os.OpenFile(dirPath+"/"+header.Name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)
if err != nil {
return err
}
_, err = io.CopyN(libFile, tarReader, header.Size)
if err != nil {
return err
}
libFile.Close()
}
reader.Close()
return syscall.Exec(execPath, os.Args, os.Environ())
}`))
if err != nil {
return err
}
err = common.WriteFile(cachePath+"/go.mod", []byte(`module output
go 1.18
require (
github.com/klauspost/compress latest
github.com/sagernet/sing latest
)`))
if err != nil {
return err
}
err = runAs(cachePath, "go", "mod", "tidy")
if err != nil {
return err
}
logrus.Info(">> ", outputPath)
err = runAs(cachePath, "go", "build", "-o", outputPath, "-trimpath", "-ldflags", "-s -w -buildid=", ".")
if err != nil {
return err
}
return nil
}
func runAs(dir string, name string, args ...string) error {
command := exec.Command(name, args...)
command.Dir = dir
command.Stdout = os.Stdout
command.Stderr = os.Stderr
command.Env = os.Environ()
command.Env = append(command.Env, "CGO_ENABLED=0")
return command.Run()
}

View file

@ -1,133 +0,0 @@
package main
import (
"encoding/binary"
"io"
"net"
"net/http"
"net/netip"
"os"
"runtime"
"github.com/lucas-clemente/quic-go/http3"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
_ "github.com/sagernet/sing/common/log"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/net/dns/dnsmessage"
)
func main() {
command := &cobra.Command{
Use: "dns-chk",
Run: run,
}
if err := command.Execute(); err != nil {
logrus.Fatal(err)
}
}
func run(cmd *cobra.Command, args []string) {
err := testSocksTCP()
if err != nil {
logrus.Fatal(err)
}
err = testSocksUDP()
if err != nil {
logrus.Fatal(err)
}
err = testQuic()
if err != nil {
logrus.Fatal(err)
}
}
func testSocksTCP() error {
tcpConn, err := net.Dial("tcp", "1.0.0.1:53")
if err != nil {
return err
}
message := &dnsmessage.Message{}
message.Header.ID = 1
message.Header.RecursionDesired = true
message.Questions = append(message.Questions, dnsmessage.Question{
Name: dnsmessage.MustNewName("google.com."),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
})
packet, err := message.Pack()
err = binary.Write(tcpConn, binary.BigEndian, uint16(len(packet)))
if err != nil {
return err
}
_, err = tcpConn.Write(packet)
if err != nil {
return err
}
var respLen uint16
err = binary.Read(tcpConn, binary.BigEndian, &respLen)
if err != nil {
return err
}
respBuf := buf.Make(int(respLen))
_, err = io.ReadFull(tcpConn, respBuf)
if err != nil {
return err
}
common.Must(message.Unpack(respBuf))
for _, answer := range message.Answers {
logrus.Info("tcp got answer: ", netip.AddrFrom4(answer.Body.(*dnsmessage.AResource).A))
}
tcpConn.Close()
return nil
}
func testSocksUDP() error {
udpConn, err := net.Dial("udp", "1.0.0.1:53")
if err != nil {
return err
}
message := &dnsmessage.Message{}
message.Header.ID = 1
message.Header.RecursionDesired = true
message.Questions = append(message.Questions, dnsmessage.Question{
Name: dnsmessage.MustNewName("google.com."),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
})
packet, err := message.Pack()
common.Must(err)
common.Must1(udpConn.Write(packet))
_buffer := buf.StackNew()
defer runtime.KeepAlive(_buffer)
buffer := common.Dup(_buffer)
common.Must1(buffer.ReadFrom(udpConn))
common.Must(message.Unpack(buffer.Bytes()))
for _, answer := range message.Answers {
logrus.Info("udp got answer: ", netip.AddrFrom4(answer.Body.(*dnsmessage.AResource).A))
}
udpConn.Close()
return nil
}
func testQuic() error {
client := &http.Client{
Transport: &http3.RoundTripper{},
}
qResponse, err := client.Get("https://cloudflare.com/cdn-cgi/trace")
if err != nil {
return err
}
qResponse.Write(os.Stderr)
return nil
}

View file

@ -1,287 +0,0 @@
package main
import (
"context"
"encoding/json"
"github.com/go-resty/resty/v2"
E "github.com/sagernet/sing/common/exceptions"
)
type NodeClient struct {
client *resty.Client
}
func NewNodeClient(baseURL string, token string, node string) *NodeClient {
r := resty.New()
r.SetBaseURL(baseURL)
r.SetQueryParams(map[string]string{
"node_id": node,
"token": token,
})
// r.SetDebug(true)
return &NodeClient{r}
}
type ShadowsocksUserList struct {
Port uint16
Method string
Users map[int]string // id password
}
type RawShadowsocksUserList struct {
Data []RawShadowsocksUser `json:"data"`
}
type RawShadowsocksUser struct {
Id int `json:"id"`
Port uint16 `json:"port"`
Cipher string `json:"cipher"`
Secret string `json:"secret"`
}
func (c *NodeClient) GetShadowsocksUserList(ctx context.Context) (*ShadowsocksUserList, error) {
resp, err := c.client.R().
SetContext(ctx).
SetResult(new(RawShadowsocksUserList)).
Get("/api/v1/server/ShadowsocksTidalab/user")
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, E.New("HTTP ", resp.StatusCode(), " ", resp.Body())
}
rawUserList := resp.Result().(*RawShadowsocksUserList)
userList := &ShadowsocksUserList{
Method: rawUserList.Data[0].Cipher,
Port: rawUserList.Data[0].Port,
Users: make(map[int]string),
}
for _, item := range rawUserList.Data {
if item.Cipher != userList.Method {
return nil, E.New("not unique method in item ", item.Id)
}
if item.Port != userList.Port {
return nil, E.New("not unique port in item ", item.Id)
}
userList.Users[item.Id] = item.Secret
}
return userList, nil
}
type TrojanUserList struct {
Users map[int]string // id password
}
type RawTrojanUserList struct {
Msg string `json:"msg"`
Data []RawTrojanUser `json:"data"`
}
type RawTrojanUser struct {
ID int `json:"id"`
T int `json:"t"`
U int64 `json:"u"`
D int64 `json:"d"`
TransferEnable int64 `json:"transfer_enable"`
TrojanUser struct {
Password string `json:"password"`
} `json:"trojan_user"`
}
func (c *NodeClient) GetTrojanUserList(ctx context.Context) (*TrojanUserList, error) {
resp, err := c.client.R().
SetContext(ctx).
SetResult(new(RawTrojanUserList)).
Get("/api/v1/server/TrojanTidalab/user")
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, E.New("HTTP ", resp.StatusCode(), " ", resp.String())
}
rawUserList := resp.Result().(*RawTrojanUserList)
userList := &TrojanUserList{
Users: make(map[int]string),
}
for _, item := range rawUserList.Data {
userList.Users[item.ID] = item.TrojanUser.Password
}
return userList, nil
}
type TrojanConfig struct {
LocalPort uint16
SNI string
}
type RawTrojanConfig struct {
LocalPort uint16 `json:"local_port"`
Ssl struct {
Sni string `json:"sni"`
} `json:"ssl"`
}
func (c *NodeClient) GetTrojanConfig(ctx context.Context) (*TrojanConfig, error) {
resp, err := c.client.R().
SetContext(ctx).
SetQueryParam("local_port", "1").
Get("/api/v1/server/TrojanTidalab/config")
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, E.New("HTTP ", resp.StatusCode(), " ", resp.String())
}
rawConfig := new(RawTrojanConfig)
err = json.Unmarshal(resp.Body(), rawConfig)
if err != nil {
return nil, E.Cause(err, "parse raw trojan config")
}
trojanConfig := new(TrojanConfig)
trojanConfig.LocalPort = rawConfig.LocalPort
trojanConfig.SNI = rawConfig.Ssl.Sni
return trojanConfig, nil
}
type VMessUserList struct {
AlterID int
Users map[int]string // id uuid
}
type RawVMessUserList struct {
Msg string `json:"msg"`
Data []RawVMessUser `json:"data"`
}
type RawVMessUser struct {
Id int `json:"id"`
T int `json:"t"`
U int64 `json:"u"`
D int64 `json:"d"`
TransferEnable int64 `json:"transfer_enable"`
V2RayUser struct {
Uuid string `json:"uuid"`
Email string `json:"email"`
AlterId int `json:"alter_id"`
Level int `json:"level"`
} `json:"v2ray_user"`
}
func (c *NodeClient) GetVMessUserList(ctx context.Context) (*VMessUserList, error) {
resp, err := c.client.R().
SetContext(ctx).
SetResult(new(RawVMessUserList)).
Get("/api/v1/server/Deepbwork/user")
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, E.New("HTTP ", resp.StatusCode(), " ", resp.String())
}
rawUserList := resp.Result().(*RawVMessUserList)
userList := &VMessUserList{
AlterID: rawUserList.Data[0].V2RayUser.AlterId,
Users: make(map[int]string),
}
for _, user := range rawUserList.Data {
userList.Users[user.Id] = user.V2RayUser.Uuid
}
return userList, nil
}
type VMessConfig struct {
Port uint16
Network string
Security string
}
type RawV2RayConfig struct {
Inbounds []struct {
Protocol string `json:"protocol"`
Port uint16 `json:"port"`
StreamSettings struct {
Network string `json:"network"`
Security string `json:"security,omitempty"`
} `json:"streamSettings,omitempty"`
} `json:"inbounds"`
}
func (c *NodeClient) GetVMessConfig(ctx context.Context) (*VMessConfig, error) {
resp, err := c.client.R().
SetContext(ctx).
SetQueryParam("local_port", "1").
Get("/api/v1/server/Deepbwork/config")
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, E.New("HTTP ", resp.StatusCode(), " ", resp.String())
}
rawConfig := new(RawV2RayConfig)
err = json.Unmarshal(resp.Body(), rawConfig)
if err != nil {
return nil, err
}
vmessConfig := new(VMessConfig)
vmessConfig.Port = rawConfig.Inbounds[0].Port
vmessConfig.Network = rawConfig.Inbounds[0].StreamSettings.Network
vmessConfig.Security = rawConfig.Inbounds[0].StreamSettings.Security
return vmessConfig, nil
}
type UserTraffic struct {
UID int `json:"user_id"`
Upload int64 `json:"u"`
Download int64 `json:"d"`
}
func (c *NodeClient) ReportShadowsocksTraffic(ctx context.Context, userTraffic []UserTraffic) error {
return c.reportTraffic(ctx, "/api/v1/server/ShadowsocksTidalab/submit", userTraffic)
}
func (c *NodeClient) ReportVMessTraffic(ctx context.Context, userTraffic []UserTraffic) error {
return c.reportTraffic(ctx, "/api/v1/server/Deepbwork/submit", userTraffic)
}
func (c *NodeClient) ReportTrojanTraffic(ctx context.Context, userTraffic []UserTraffic) error {
return c.reportTraffic(ctx, "/api/v1/server/TrojanTidalab/submit", userTraffic)
}
func (c *NodeClient) reportTraffic(ctx context.Context, path string, userTraffic []UserTraffic) error {
resp, err := c.client.R().
SetContext(ctx).
SetBody(userTraffic).
Post(path)
if err != nil {
return err
}
if !resp.IsSuccess() {
return E.New("HTTP ", resp.StatusCode(), " ", resp.String())
}
return nil
}

View file

@ -1,17 +0,0 @@
package main
import "github.com/sagernet/sing/common/acme"
type Config struct {
URL string `json:"url"`
Token string `json:"token"`
Nodes []Node `json:"nodes"`
Debug bool `json:"debug"`
ACME *acme.Settings `json:"acme"`
}
type Node struct {
ID int `json:"id"`
Type string `json:"type"`
Domain string `json:"domain"`
}

View file

@ -1,265 +0,0 @@
package main
import (
"context"
"crypto/tls"
"encoding/json"
"io/ioutil"
"net"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/acme"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
_ "github.com/sagernet/sing/common/log"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/protocol/trojan"
transTLS "github.com/sagernet/sing/transport/tls"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var configPath string
func main() {
command := &cobra.Command{
Use: "portal-v2board [-c config.json]",
Args: cobra.NoArgs,
Version: sing.VersionStr,
Run: run,
}
command.Flags().StringVarP(&configPath, "config", "c", "config.json", "set config path")
if err := command.Execute(); err != nil {
logrus.Fatal(err)
}
}
var acmeManager *acme.CertificateManager
func run(cmd *cobra.Command, args []string) {
data, err := ioutil.ReadFile(configPath)
if err != nil {
logrus.Fatal(E.Cause(err, "read config"))
}
config := new(Config)
err = json.Unmarshal(data, config)
if err != nil {
logrus.Fatal(E.Cause(err, "parse config"))
}
if config.Debug {
logrus.SetLevel(logrus.TraceLevel)
}
if len(config.Nodes) == 0 {
logrus.Fatal("empty nodes")
}
if config.ACME != nil && config.ACME.Enabled {
err = config.ACME.SetupEnvironment()
if err != nil {
logrus.Fatal(err)
}
acmeManager = acme.NewCertificateManager(config.ACME)
}
var instances []Instance
for _, node := range config.Nodes {
client := NewNodeClient(config.URL, config.Token, strconv.Itoa(node.ID))
switch node.Type {
case "trojan":
instances = append(instances, NewTrojanInstance(client, node))
default:
logrus.Fatal("unsupported node type ", node.Type, " (id: ", node.ID, ")")
}
}
for _, instance := range instances {
err = instance.Start()
if err != nil {
logrus.Fatal(err)
}
}
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
<-osSignals
for _, instance := range instances {
instance.Close()
}
}
type Instance interface {
Start() error
Close() error
}
type TrojanInstance struct {
*NodeClient
id int
domain string
listener net.Listener
tlsConfig tls.Config
service trojan.Service[int]
user UserManager
reloadTicker *time.Ticker
}
func NewTrojanInstance(client *NodeClient, node Node) *TrojanInstance {
t := &TrojanInstance{
NodeClient: client,
id: node.ID,
domain: node.Domain,
user: NewUserManager(),
}
t.service = trojan.NewService[int](t)
return t
}
func (i *TrojanInstance) Start() error {
err := i.reloadUsers()
if err != nil {
return err
}
trojanConfig, err := i.GetTrojanConfig(context.Background())
if err != nil {
return E.Cause(err, i.id, ": read trojan config")
}
if trojanConfig.SNI != "" {
i.domain = trojanConfig.SNI
}
if acmeManager != nil {
certificate, err := acmeManager.GetKeyPair(i.domain)
if err != nil {
return E.Cause(err, i.id, ": generate certificate")
}
i.tlsConfig.Certificates = []tls.Certificate{*certificate}
acmeManager.RegisterUpdateListener(i.domain, func(certificate *tls.Certificate) {
i.tlsConfig.Certificates = []tls.Certificate{*certificate}
})
}
tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
Port: int(trojanConfig.LocalPort),
})
if err != nil {
return E.Cause(err, i.id, ": listen at tcp:", trojanConfig.LocalPort, ", check server configuration!")
}
if common.IsEmpty(i.tlsConfig.Certificates) {
i.tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
return transTLS.GenerateCertificate(info.ServerName)
}
} else {
i.tlsConfig.GetCertificate = nil
}
i.listener = tls.NewListener(tcpListener, &i.tlsConfig)
logrus.Info(i.id, ": started at ", tcpListener.Addr())
go i.loopRequests()
i.reloadTicker = time.NewTicker(time.Minute)
go i.loopReload()
return nil
}
func (i *TrojanInstance) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
userCtx := ctx.(*trojan.Context[int])
conn = i.user.TrackConnection(userCtx.User, conn)
logrus.Info(i.id, ": user ", userCtx.User, " TCP ", metadata.Source, " ==> ", metadata.Destination)
destConn, err := N.SystemDialer.DialContext(context.Background(), "tcp", metadata.Destination)
if err != nil {
return err
}
return bufio.CopyConn(ctx, conn, destConn)
}
func (i *TrojanInstance) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
userCtx := ctx.(*trojan.Context[int])
conn = i.user.TrackPacketConnection(userCtx.User, conn)
logrus.Info(i.id, ": user ", userCtx.User, " UDP ", metadata.Source, " ==> ", metadata.Destination)
udpConn, err := net.ListenUDP("udp", nil)
if err != nil {
return err
}
return bufio.CopyNetPacketConn(ctx, conn, udpConn)
}
func (i *TrojanInstance) loopRequests() {
for {
conn, err := i.listener.Accept()
if err != nil {
logrus.Debug(E.Cause(err, i.id, ": listener exited"))
return
}
go func() {
hErr := i.service.NewConnection(context.Background(), conn, M.Metadata{
Protocol: "tls",
Source: M.SocksaddrFromNet(conn.RemoteAddr()),
})
if hErr != nil {
i.HandleError(hErr)
}
}()
}
}
func (i *TrojanInstance) loopReload() {
for range i.reloadTicker.C {
err := i.reloadUsers()
if err != nil {
i.HandleError(E.Cause(err, "reload user"))
}
traffics := i.user.ReadTraffics()
if len(traffics) > 0 {
err = i.ReportTrojanTraffic(context.Background(), traffics)
if err != nil {
i.HandleError(E.Cause(err, "report traffic"))
}
}
}
}
func (i *TrojanInstance) reloadUsers() error {
logrus.Debug(i.id, ": fetching users...")
userList, err := i.GetTrojanUserList(context.Background())
if err != nil {
return E.Cause(err, i.id, ": get user list")
}
if len(userList.Users) == 0 {
logrus.Warn(i.id, ": empty users")
}
i.service.ResetUsers()
for id, password := range userList.Users {
err = i.service.AddUser(id, password)
if err != nil {
logrus.Warn(E.Cause(err, i.id, ": add user"))
}
}
logrus.Debug(i.id, ": loaded ", len(userList.Users), " users")
return nil
}
func (i *TrojanInstance) HandleError(err error) {
common.Close(err)
if E.IsClosed(err) {
return
}
logrus.Warn(i.id, ": ", err)
}
func (i *TrojanInstance) Close() error {
i.reloadTicker.Stop()
return i.listener.Close()
}

View file

@ -1,134 +0,0 @@
package main
import (
"io"
"net"
"sync"
"sync/atomic"
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
type UserManager struct {
access sync.Mutex
users map[int]*User
}
type User struct {
Upload uint64
Download uint64
}
func NewUserManager() UserManager {
return UserManager{
users: make(map[int]*User),
}
}
func (m *UserManager) TrackConnection(userId int, conn net.Conn) net.Conn {
m.access.Lock()
defer m.access.Unlock()
var user *User
if u, loaded := m.users[userId]; loaded {
user = u
} else {
user = new(User)
m.users[userId] = user
}
return &TrackConn{conn, user}
}
func (m *UserManager) TrackPacketConnection(userId int, conn N.PacketConn) N.PacketConn {
m.access.Lock()
defer m.access.Unlock()
var user *User
if u, loaded := m.users[userId]; loaded {
user = u
} else {
user = new(User)
m.users[userId] = user
}
return &TrackPacketConn{conn, user}
}
func (m *UserManager) ReadTraffics() []UserTraffic {
m.access.Lock()
defer m.access.Unlock()
traffic := make([]UserTraffic, 0, len(m.users))
for userId, user := range m.users {
upload := atomic.SwapUint64(&user.Upload, 0)
download := atomic.SwapUint64(&user.Download, 0)
if upload == 0 && download == 0 {
continue
}
traffic = append(traffic, UserTraffic{
UID: userId,
Upload: int64(upload),
Download: int64(download),
})
}
return traffic
}
type TrackConn struct {
net.Conn
*User
}
func (c *TrackConn) Read(p []byte) (n int, err error) {
n, err = c.Conn.Read(p)
if n > 0 {
atomic.AddUint64(&c.Upload, uint64(n))
}
return
}
func (c *TrackConn) Write(p []byte) (n int, err error) {
n, err = c.Conn.Write(p)
if n > 0 {
atomic.AddUint64(&c.Download, uint64(n))
}
return
}
func (c *TrackConn) WriteTo(w io.Writer) (n int64, err error) {
n, err = io.Copy(w, c.Conn)
if n > 0 {
atomic.AddUint64(&c.Upload, uint64(n))
}
return
}
func (c *TrackConn) ReadFrom(r io.Reader) (n int64, err error) {
n, err = io.Copy(c.Conn, r)
if n > 0 {
atomic.AddUint64(&c.Download, uint64(n))
}
return
}
type TrackPacketConn struct {
N.PacketConn
*User
}
func (c *TrackPacketConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
destination, err := c.PacketConn.ReadPacket(buffer)
if err == nil {
atomic.AddUint64(&c.Upload, uint64(buffer.Len()))
}
return destination, err
}
func (c *TrackPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
n := buffer.Len()
err := c.PacketConn.WritePacket(buffer, destination)
if err == nil {
atomic.AddUint64(&c.Download, uint64(n))
}
return err
}

View file

@ -1,158 +0,0 @@
package main
import (
"context"
"crypto/tls"
"encoding/binary"
"io"
"net"
"net/http"
"net/netip"
"os"
"runtime"
"github.com/lucas-clemente/quic-go"
"github.com/lucas-clemente/quic-go/http3"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
_ "github.com/sagernet/sing/common/log"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/protocol/socks"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/net/dns/dnsmessage"
)
func main() {
command := &cobra.Command{
Use: "socks-chk [socks4/4a/5://]address:port",
Args: cobra.ExactArgs(1),
Run: run,
}
if err := command.Execute(); err != nil {
logrus.Fatal(err)
}
}
func run(cmd *cobra.Command, args []string) {
client, err := socks.NewClientFromURL(N.SystemDialer, args[0])
if err != nil {
logrus.Fatal(err)
}
err = testSocksTCP(client)
if err != nil {
logrus.Fatal(err)
}
err = testSocksUDP(client)
if err != nil {
logrus.Fatal(err)
}
err = testSocksQuic(client)
if err != nil {
logrus.Fatal(err)
}
}
func testSocksTCP(client *socks.Client) error {
tcpConn, err := client.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("1.0.0.1", 53))
if err != nil {
return err
}
message := &dnsmessage.Message{}
message.Header.ID = 1
message.Header.RecursionDesired = true
message.Questions = append(message.Questions, dnsmessage.Question{
Name: dnsmessage.MustNewName("google.com."),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
})
packet, err := message.Pack()
err = binary.Write(tcpConn, binary.BigEndian, uint16(len(packet)))
if err != nil {
return err
}
_, err = tcpConn.Write(packet)
if err != nil {
return err
}
var respLen uint16
err = binary.Read(tcpConn, binary.BigEndian, &respLen)
if err != nil {
return err
}
respBuf := buf.Make(int(respLen))
_, err = io.ReadFull(tcpConn, respBuf)
if err != nil {
return err
}
common.Must(message.Unpack(respBuf))
for _, answer := range message.Answers {
logrus.Info("tcp got answer: ", netip.AddrFrom4(answer.Body.(*dnsmessage.AResource).A))
}
tcpConn.Close()
return nil
}
func testSocksUDP(client *socks.Client) error {
udpConn, err := client.DialContext(context.Background(), "udp", M.ParseSocksaddrHostPort("1.0.0.1", 53))
if err != nil {
return err
}
message := &dnsmessage.Message{}
message.Header.ID = 1
message.Header.RecursionDesired = true
message.Questions = append(message.Questions, dnsmessage.Question{
Name: dnsmessage.MustNewName("google.com."),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
})
packet, err := message.Pack()
common.Must(err)
common.Must1(udpConn.Write(packet))
_buffer := buf.StackNew()
defer runtime.KeepAlive(_buffer)
buffer := common.Dup(_buffer)
common.Must1(buffer.ReadFrom(udpConn))
common.Must(message.Unpack(buffer.Bytes()))
for _, answer := range message.Answers {
logrus.Info("udp got answer: ", netip.AddrFrom4(answer.Body.(*dnsmessage.AResource).A))
}
udpConn.Close()
return nil
}
func testSocksQuic(client *socks.Client) error {
httpClient := &http.Client{
Transport: &http3.RoundTripper{
Dial: func(ctx context.Context, network, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) {
udpAddr, err := net.ResolveUDPAddr(network, addr)
if err != nil {
return nil, err
}
conn, err := client.DialContext(context.Background(), network, M.SocksaddrFromNet(udpAddr))
if err != nil {
return nil, err
}
return quic.DialEarlyContext(ctx, conn.(net.PacketConn), udpAddr, M.ParseSocksaddr(addr).AddrString(), tlsCfg, cfg)
},
},
}
qResponse, err := httpClient.Get("https://cloudflare.com/cdn-cgi/trace")
if err != nil {
return err
}
qResponse.Write(os.Stderr)
return nil
}

View file

@ -1,369 +0,0 @@
package main
import (
"context"
"encoding/json"
"io"
"io/ioutil"
"net"
"net/netip"
"os"
"os/signal"
"runtime"
"runtime/debug"
"strings"
"syscall"
"time"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/geoip"
"github.com/sagernet/sing/common/geosite"
_ "github.com/sagernet/sing/common/log"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/random"
"github.com/sagernet/sing/common/redir"
"github.com/sagernet/sing/common/rw"
"github.com/sagernet/sing/common/task"
"github.com/sagernet/sing/protocol/shadowsocks"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead_2022"
"github.com/sagernet/sing/protocol/shadowsocks/shadowimpl"
"github.com/sagernet/sing/protocol/shadowsocks/shadowstream"
"github.com/sagernet/sing/transport/mixed"
"github.com/sagernet/sing/transport/system"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const udpTimeout = 5 * 60
type flags struct {
Server string `json:"server"`
ServerPort uint16 `json:"server_port"`
Bind string `json:"local_address"`
LocalPort uint16 `json:"local_port"`
Password string `json:"password"`
Key string `json:"key"`
Method string `json:"method"`
TCPFastOpen bool `json:"fast_open"`
Verbose bool `json:"verbose"`
Transproxy string `json:"transproxy"`
FWMark int `json:"fwmark"`
Bypass string `json:"bypass"`
UseSystemRNG bool `json:"use_system_rng"`
ReducedSaltEntropy bool `json:"reduced_salt_entropy"`
ConfigFile string
}
func main() {
f := new(flags)
command := &cobra.Command{
Use: "ss-local",
Short: "shadowsocks client",
Version: sing.VersionStr,
Run: func(cmd *cobra.Command, args []string) {
run(cmd, f)
},
}
command.Flags().StringVarP(&f.Server, "server", "s", "", "Store the server’s hostname or IP.")
command.Flags().Uint16VarP(&f.ServerPort, "server-port", "p", 0, "Store the server’s port number.")
command.Flags().StringVarP(&f.Bind, "local-address", "b", "", "Store the local address.")
command.Flags().Uint16VarP(&f.LocalPort, "local-port", "l", 0, "Store the local port number.")
command.Flags().StringVarP(&f.Password, "password", "k", "", "Store the password. The server and the client should use the same password.")
command.Flags().StringVar(&f.Key, "key", "", "Store the key directly. The key should be encoded with URL-safe Base64.")
var supportedCiphers []string
supportedCiphers = append(supportedCiphers, shadowsocks.MethodNone)
supportedCiphers = append(supportedCiphers, shadowaead_2022.List...)
supportedCiphers = append(supportedCiphers, shadowaead.List...)
supportedCiphers = append(supportedCiphers, shadowstream.List...)
command.Flags().StringVarP(&f.Method, "encrypt-method", "m", "", "Store the cipher.\n\nSupported ciphers:\n\n"+strings.Join(supportedCiphers, "\n"))
command.Flags().BoolVar(&f.TCPFastOpen, "fast-open", false, `Enable TCP fast open.
Only available with Linux kernel > 3.7.0.`)
command.Flags().StringVarP(&f.Transproxy, "transproxy", "t", "", "Enable transparent proxy support. [possible values: redirect, tproxy]")
command.Flags().IntVar(&f.FWMark, "fwmark", 0, "Store outbound socket mark.")
command.Flags().StringVar(&f.Bypass, "bypass", "", "Store bypass country.")
command.Flags().StringVarP(&f.ConfigFile, "config", "c", "", "Use a configuration file.")
command.Flags().BoolVarP(&f.Verbose, "verbose", "v", false, "Enable verbose mode.")
command.Flags().BoolVar(&f.UseSystemRNG, "use-system-rng", false, "Use system random number generator.")
command.Flags().BoolVar(&f.ReducedSaltEntropy, "reduced-salt-entropy", false, "Remapping salt to printable chars.")
err := command.Execute()
if err != nil {
logrus.Fatal(err)
}
}
type client struct {
*mixed.Listener
*geosite.Matcher
server M.Socksaddr
method shadowsocks.Method
dialer net.Dialer
bypass string
}
func newClient(f *flags) (*client, error) {
if f.ConfigFile != "" {
configFile, err := ioutil.ReadFile(f.ConfigFile)
if err != nil {
return nil, E.Cause(err, "read config file")
}
flagsNew := new(flags)
err = json.Unmarshal(configFile, flagsNew)
if err != nil {
return nil, E.Cause(err, "decode config file")
}
if flagsNew.Server != "" && f.Server == "" {
f.Server = flagsNew.Server
}
if flagsNew.ServerPort != 0 && f.ServerPort == 0 {
f.ServerPort = flagsNew.ServerPort
}
if flagsNew.Bind != "" && f.Bind == "" {
f.Bind = flagsNew.Bind
}
if flagsNew.LocalPort != 0 && f.LocalPort == 0 {
f.LocalPort = flagsNew.LocalPort
}
if flagsNew.Password != "" && f.Password == "" {
f.Password = flagsNew.Password
}
if flagsNew.Key != "" && f.Key == "" {
f.Key = flagsNew.Key
}
if flagsNew.Method != "" && f.Method == "" {
f.Method = flagsNew.Method
}
if flagsNew.Transproxy != "" && f.Transproxy == "" {
f.Transproxy = flagsNew.Transproxy
}
if flagsNew.TCPFastOpen {
f.TCPFastOpen = true
}
if flagsNew.Verbose {
f.Verbose = true
}
}
if f.Verbose {
logrus.SetLevel(logrus.TraceLevel)
}
if f.Server == "" {
return nil, E.New("missing server address")
} else if f.ServerPort == 0 {
return nil, E.New("missing server port")
} else if f.Method == "" {
return nil, E.New("missing method")
}
c := &client{
server: M.ParseSocksaddrHostPort(f.Server, f.ServerPort),
bypass: f.Bypass,
dialer: net.Dialer{
Timeout: 5 * time.Second,
},
}
if f.Method == shadowsocks.MethodNone {
c.method = shadowsocks.NewNone()
} else {
var rng io.Reader
if f.UseSystemRNG {
rng = random.System
} else {
rng = random.System
}
if f.ReducedSaltEntropy {
rng = &shadowsocks.ReducedEntropyReader{Reader: rng}
}
method, err := shadowimpl.FetchMethod(f.Method, f.Key, f.Password, rng)
if err != nil {
return nil, err
}
c.method = method
}
c.dialer.Control = func(network, address string, c syscall.RawConn) error {
var rawFd uintptr
err := c.Control(func(fd uintptr) {
rawFd = fd
})
if err != nil {
return err
}
if f.FWMark > 0 {
err = redir.FWMark(rawFd, f.FWMark)
if err != nil {
return err
}
}
if f.TCPFastOpen {
err = system.TCPFastOpen(rawFd)
if err != nil {
return err
}
}
return nil
}
var transproxyMode redir.TransproxyMode
switch f.Transproxy {
case "redirect":
transproxyMode = redir.ModeRedirect
case "tproxy":
transproxyMode = redir.ModeTProxy
case "":
transproxyMode = redir.ModeDisabled
default:
return nil, E.New("unknown transproxy mode ", f.Transproxy)
}
var bind netip.Addr
if f.Bind != "" {
addr, err := netip.ParseAddr(f.Bind)
if err != nil {
return nil, E.Cause(err, "bad local address")
}
bind = addr
} else {
bind = netip.IPv6Unspecified()
}
c.Listener = mixed.NewListener(netip.AddrPortFrom(bind, f.LocalPort), nil, transproxyMode, udpTimeout, c)
if f.Bypass != "" {
err := geoip.LoadMMDB("Country.mmdb")
if err != nil {
return nil, E.Cause(err, "load Country.mmdb")
}
geodata, err := os.Open("geosite.dat")
if err != nil {
return nil, E.Cause(err, "geosite.dat not found")
}
site, err := geosite.ReadArray(geodata, f.Bypass)
if err != nil {
return nil, err
}
geositeMatcher, err := geosite.NewMatcher(site)
if err != nil {
return nil, err
}
c.Matcher = geositeMatcher
}
debug.FreeOSMemory()
return c, nil
}
func bypass(conn net.Conn, destination M.Socksaddr) error {
logrus.Info("BYPASS ", conn.RemoteAddr(), " ==> ", destination)
serverConn, err := net.Dial("tcp", destination.String())
if err != nil {
return err
}
defer common.Close(conn, serverConn)
return task.Run(context.Background(), func() error {
defer rw.CloseRead(conn)
defer rw.CloseWrite(serverConn)
return common.Error(io.Copy(serverConn, conn))
}, func() error {
defer rw.CloseRead(serverConn)
defer rw.CloseWrite(conn)
return common.Error(io.Copy(conn, serverConn))
})
}
func (c *client) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
if c.bypass != "" {
if metadata.Destination.Family().IsFqdn() {
if c.Match(metadata.Destination.Fqdn) {
return bypass(conn, metadata.Destination)
}
} else {
if geoip.Match(c.bypass, metadata.Destination.Addr.AsSlice()) {
return bypass(conn, metadata.Destination)
}
}
}
logrus.Info("outbound ", metadata.Protocol, " TCP ", conn.RemoteAddr(), " ==> ", metadata.Destination)
serverConn, err := c.dialer.DialContext(ctx, "tcp", c.server.String())
if err != nil {
return E.Cause(err, "connect to server")
}
_payload := buf.StackNew()
payload := common.Dup(_payload)
err = conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
if err != nil {
return err
}
_, err = payload.ReadFrom(conn)
if err != nil && !E.IsTimeout(err) {
return E.Cause(err, "read payload")
}
err = conn.SetReadDeadline(time.Time{})
if err != nil {
payload.Release()
return err
}
serverConn = c.method.DialEarlyConn(serverConn, metadata.Destination)
_, err = serverConn.Write(payload.Bytes())
if err != nil {
return E.Cause(err, "client handshake")
}
runtime.KeepAlive(_payload)
return bufio.CopyConn(ctx, serverConn, conn)
}
func (c *client) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
logrus.Info("outbound ", metadata.Protocol, " UDP ", metadata.Source, " ==> ", metadata.Destination)
udpConn, err := c.dialer.DialContext(ctx, "udp", c.server.String())
if err != nil {
return err
}
serverConn := c.method.DialPacketConn(udpConn)
return bufio.CopyPacketConn(ctx, serverConn, conn)
}
func run(cmd *cobra.Command, flags *flags) {
c, err := newClient(flags)
if err != nil {
logrus.StandardLogger().Log(logrus.FatalLevel, err, "\n\n")
cmd.Help()
os.Exit(1)
}
err = c.Start()
if err != nil {
logrus.Fatal(err)
}
logrus.Info("mixed server started at ", c.TCPListener.Addr())
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
<-osSignals
c.Close()
}
func (c *client) HandleError(err error) {
common.Close(err)
if E.IsClosed(err) {
return
}
logrus.Warn(err)
}

View file

@ -1,37 +0,0 @@
# ss-server
## Requirements
```
* Go 1.18
```
## Install
```shell
git clone https://github.com/SagerNet/sing
cd sing
cli/ss-server/install.sh
sudo systemctl enable ss
sudo systemctl start ss
```
## Log
```shell
sudo journalctl -u ss --output cat -f
```
## Update
```shell
cli/ss-server/update.sh
```
## Uninstall
```shell
cli/ss-server/uninstall.sh
```

View file

@ -1,7 +0,0 @@
{
"server": "::",
"server_port": 8080,
"method": "2022-blake3-aes-128-gcm",
"key": "psk",
"log_level": "info"
}

View file

@ -1,5 +0,0 @@
#!/usr/bin/env bash
sudo systemctl enable ss
sudo systemctl start ss
sudo journalctl -u ss --output cat -f

View file

@ -1,21 +0,0 @@
#!/usr/bin/env bash
export GOAMD64=v3
DIR=$(dirname "$0")
PROJECT=$DIR/../..
PATH="$PATH:$(go env GOPATH)/bin"
pushd $PROJECT
go install -v -trimpath -ldflags "-s -w -buildid=" ./cli/genpsk || exit 1
go install -v -trimpath -ldflags "-s -w -buildid=" ./cli/ss-server || exit 1
popd
sudo cp $(go env GOPATH)/bin/ss-server /usr/local/bin/ || exit 1
sudo mkdir -p /usr/local/etc/shadowsocks || exit 1
sudo cp $DIR/config.json /usr/local/etc/shadowsocks/config.json || exit 1
echo ">> /usr/local/etc/shadowsocks/config.json"
sudo sed -i "s|psk|$(genpsk 16)|" /usr/local/etc/shadowsocks/config.json || exit 1
sudo cat /usr/local/etc/shadowsocks/config.json || exit 1
sudo cp $DIR/ss.service /etc/systemd/system || exit 1
sudo systemctl daemon-reload

View file

@ -1,217 +0,0 @@
package main
import (
"context"
"encoding/base64"
"encoding/json"
"io/ioutil"
"net"
"net/netip"
"os"
"os/signal"
"syscall"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
_ "github.com/sagernet/sing/common/log"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/random"
"github.com/sagernet/sing/protocol/shadowsocks"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead_2022"
"github.com/sagernet/sing/transport/tcp"
"github.com/sagernet/sing/transport/udp"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const udpTimeout = 5 * 60
type flags struct {
Server string `json:"server"`
ServerPort uint16 `json:"server_port"`
Bind string `json:"local_address"`
LocalPort uint16 `json:"local_port"`
Password string `json:"password"`
Key string `json:"key"`
Method string `json:"method"`
LogLevel string `json:"log_level"`
}
var configPath string
func main() {
command := &cobra.Command{
Use: "ss-server [-c config.json]",
Short: "shadowsocks server",
Version: sing.VersionStr,
Run: run,
}
command.Flags().StringVarP(&configPath, "config", "c", "", "set a configuration file")
err := command.Execute()
if err != nil {
logrus.Fatal(err)
}
}
func run(cmd *cobra.Command, args []string) {
if configPath == "" {
configPath = "config.json"
}
configFile, err := ioutil.ReadFile(configPath)
if err != nil {
logrus.Fatal(E.Cause(err, "read config file"))
}
f := new(flags)
err = json.Unmarshal(configFile, f)
if err != nil {
logrus.Fatal(E.Cause(err, "parse config file"))
}
if f.LogLevel != "" {
level, err := logrus.ParseLevel(f.LogLevel)
if err != nil {
logrus.Fatal("unknown log level ", f.LogLevel)
}
logrus.SetLevel(level)
}
s, err := newServer(f)
if err != nil {
logrus.Fatal(err)
}
err = s.Start()
if err != nil {
logrus.Fatal(err)
}
logrus.Info("server started at ", s.tcpIn.TCPListener.Addr())
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
<-osSignals
s.Close()
}
type server struct {
tcpIn *tcp.Listener
udpIn *udp.Listener
service shadowsocks.Service
}
func (s *server) Start() error {
err := s.tcpIn.Start()
if err != nil {
return err
}
err = s.udpIn.Start()
return err
}
func (s *server) Close() error {
s.tcpIn.Close()
s.udpIn.Close()
return nil
}
func newServer(f *flags) (*server, error) {
s := new(server)
if f.Server == "" {
return nil, E.New("missing server address")
} else if f.ServerPort == 0 {
return nil, E.New("missing server port")
} else if f.Method == "" {
return nil, E.New("missing method")
}
if f.Method == shadowsocks.MethodNone {
s.service = shadowsocks.NewNoneService(udpTimeout, s)
} else if common.Contains(shadowaead.List, f.Method) {
var key []byte
if f.Key != "" {
kb, err := base64.StdEncoding.DecodeString(f.Key)
if err != nil {
return nil, E.Cause(err, "decode key")
}
key = kb
}
service, err := shadowaead.NewService(f.Method, key, f.Password, random.Default, udpTimeout, s)
if err != nil {
return nil, err
}
s.service = service
} else if common.Contains(shadowaead_2022.List, f.Method) {
var key []byte
if f.Key != "" {
kb, err := base64.StdEncoding.DecodeString(f.Key)
if err != nil {
return nil, E.Cause(err, "decode key")
}
key = kb
}
service, err := shadowaead_2022.NewService(f.Method, key, f.Password, random.Default, udpTimeout, s)
if err != nil {
return nil, err
}
s.service = service
} else {
return nil, E.New("unsupported method " + f.Method)
}
var bind netip.Addr
if f.Server != "" {
addr, err := netip.ParseAddr(f.Server)
if err != nil {
return nil, E.Cause(err, "bad server address")
}
bind = addr
} else {
bind = netip.IPv6Unspecified()
}
s.tcpIn = tcp.NewTCPListener(netip.AddrPortFrom(bind, f.ServerPort), s)
s.udpIn = udp.NewUDPListener(netip.AddrPortFrom(bind, f.ServerPort), s)
return s, nil
}
func (s *server) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
if metadata.Protocol != "shadowsocks" {
logrus.Trace("inbound raw TCP from ", metadata.Source)
return s.service.NewConnection(ctx, conn, metadata)
}
logrus.Info("inbound TCP ", conn.RemoteAddr(), " ==> ", metadata.Destination)
destConn, err := N.SystemDialer.DialContext(ctx, "tcp", metadata.Destination)
if err != nil {
return err
}
return bufio.CopyConn(ctx, conn, destConn)
}
func (s *server) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
logrus.Info("inbound UDP ", metadata.Source, " ==> ", metadata.Destination)
udpConn, err := net.ListenUDP("udp", nil)
if err != nil {
return err
}
return bufio.CopyNetPacketConn(ctx, conn, udpConn)
}
func (s *server) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
logrus.Trace("inbound raw UDP from ", metadata.Source)
return s.service.NewPacket(ctx, conn, buffer, metadata)
}
func (s *server) HandleError(err error) {
common.Close(err)
if E.IsClosed(err) {
return
}
logrus.Warn(err)
}

View file

@ -1,11 +0,0 @@
[Unit]
Description=Shadowsocks Service
After=network.target
[Service]
ExecStart=/usr/local/bin/ss-server -c /usr/local/etc/shadowsocks/config.json
Restart=on-failure
RestartPreventExitStatus=23
[Install]
WantedBy=multi-user.target

View file

@ -1,11 +0,0 @@
[Unit]
Description=Shadowsocks Service
After=network.target
[Service]
ExecStart=/usr/local/bin/ss-server -c /usr/local/etc/shadowsocks/%i.json
Restart=on-failure
RestartPreventExitStatus=23
[Install]
WantedBy=multi-user.target

View file

@ -1,8 +0,0 @@
#!/usr/bin/env bash
sudo systemctl stop ss
sudo systemctl stop 'ss@*'
sudo rm -rf /usr/local/bin/ss-server
sudo rm -rf /usr/local/etc/shadowsocks
sudo rm -rf /etc/systemd/system/ss.service
sudo systemctl daemon-reload

View file

@ -1,18 +0,0 @@
#!/usr/bin/env bash
export GOAMD64=v3
DIR=$(dirname "$0")
PROJECT=$DIR/../..
pushd $PROJECT
git fetch || exit 1
git reset origin/main --hard || exit 1
git clean -fdx || exit 1
go install -v -trimpath -ldflags "-s -w -buildid=" ./cli/ss-server || exit 1
popd
sudo systemctl stop ss
sudo cp $(go env GOPATH)/bin/ss-server /usr/local/bin || exit 1
sudo systemctl start ss
sudo journalctl -u ss --output cat -f

View file

@ -1,344 +0,0 @@
package main
import (
"context"
cTLS "crypto/tls"
"encoding/json"
"io/ioutil"
"net"
"net/netip"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/refraction-networking/utls"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
_ "github.com/sagernet/sing/common/log"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/redir"
"github.com/sagernet/sing/protocol/trojan"
"github.com/sagernet/sing/transport/mixed"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const udpTimeout = 5 * 60
type flags struct {
Server string `json:"server"`
ServerPort uint16 `json:"server_port"`
ServerName string `json:"server_name"`
Bind string `json:"local_address"`
LocalPort uint16 `json:"local_port"`
Password string `json:"password"`
Verbose bool `json:"verbose"`
Insecure bool `json:"insecure"`
ConfigFile string
}
func main() {
f := new(flags)
command := &cobra.Command{
Use: "trojan-local",
Short: "trojan client",
Version: sing.VersionStr,
Run: func(cmd *cobra.Command, args []string) {
run(cmd, f)
},
}
command.Flags().StringVarP(&f.Server, "server", "s", "", "Store the server’s hostname or IP.")
command.Flags().Uint16VarP(&f.ServerPort, "server-port", "p", 0, "Store the server’s port number.")
command.Flags().StringVarP(&f.ServerName, "server-name", "n", "", "Store the server name.")
command.Flags().StringVarP(&f.Bind, "local-address", "b", "", "Store the local address.")
command.Flags().Uint16VarP(&f.LocalPort, "local-port", "l", 0, "Store the local port number.")
command.Flags().StringVarP(&f.Password, "password", "k", "", "Store the password. The server and the client should use the same password.")
command.Flags().BoolVarP(&f.Insecure, "insecure", "i", false, "Store insecure.")
command.Flags().StringVarP(&f.ConfigFile, "config", "c", "", "Use a configuration file.")
command.Flags().BoolVarP(&f.Verbose, "verbose", "v", false, "Store verbose mode.")
err := command.Execute()
if err != nil {
logrus.Fatal(err)
}
}
func run(cmd *cobra.Command, f *flags) {
c, err := newClient(f)
if err != nil {
logrus.StandardLogger().Log(logrus.FatalLevel, err, "\n\n")
cmd.Help()
os.Exit(1)
}
err = c.Start()
if err != nil {
logrus.Fatal(err)
}
logrus.Info("mixed server started at ", c.TCPListener.Addr())
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
<-osSignals
c.Close()
}
type client struct {
*mixed.Listener
server M.Socksaddr
key [trojan.KeyLength]byte
sni string
insecure bool
dialer net.Dialer
}
func newClient(f *flags) (*client, error) {
if f.ConfigFile != "" {
configFile, err := ioutil.ReadFile(f.ConfigFile)
if err != nil {
return nil, E.Cause(err, "read config file")
}
flagsNew := new(flags)
err = json.Unmarshal(configFile, flagsNew)
if err != nil {
return nil, E.Cause(err, "decode config file")
}
if flagsNew.Server != "" && f.Server == "" {
f.Server = flagsNew.Server
}
if flagsNew.ServerPort != 0 && f.ServerPort == 0 {
f.ServerPort = flagsNew.ServerPort
}
if flagsNew.ServerName != "" && f.ServerName == "" {
f.ServerName = flagsNew.ServerName
}
if flagsNew.Bind != "" && f.Bind == "" {
f.Bind = flagsNew.Bind
}
if flagsNew.LocalPort != 0 && f.LocalPort == 0 {
f.LocalPort = flagsNew.LocalPort
}
if flagsNew.Password != "" && f.Password == "" {
f.Password = flagsNew.Password
}
if flagsNew.Insecure {
f.Insecure = true
}
if flagsNew.Verbose {
f.Verbose = true
}
}
if f.Verbose {
logrus.SetLevel(logrus.TraceLevel)
}
if f.Server == "" {
return nil, E.New("missing server address")
} else if f.ServerPort == 0 {
return nil, E.New("missing server port")
}
c := &client{
server: M.ParseSocksaddrHostPort(f.Server, f.ServerPort),
key: trojan.Key(f.Password),
sni: f.ServerName,
insecure: f.Insecure,
}
if c.sni == "" {
c.sni = f.Server
}
var bind netip.Addr
if f.Bind != "" {
addr, err := netip.ParseAddr(f.Bind)
if err != nil {
return nil, E.Cause(err, "bad local address")
}
bind = addr
} else {
bind = netip.IPv6Unspecified()
}
c.Listener = mixed.NewListener(netip.AddrPortFrom(bind, f.LocalPort), nil, redir.ModeDisabled, udpTimeout, c)
return c, nil
}
func (c *client) connect(ctx context.Context) (*cTLS.Conn, error) {
tcpConn, err := c.dialer.DialContext(ctx, "tcp", c.server.String())
if err != nil {
return nil, err
}
tlsConn := cTLS.Client(tcpConn, &cTLS.Config{
ServerName: c.sni,
InsecureSkipVerify: c.insecure,
})
return tlsConn, nil
}
func (c *client) connectUTLS(ctx context.Context) (*tls.UConn, error) {
tcpConn, err := c.dialer.DialContext(ctx, "tcp", c.server.String())
if err != nil {
return nil, err
}
tlsConn := tls.UClient(tcpConn, &tls.Config{
ServerName: c.sni,
InsecureSkipVerify: c.insecure,
}, tls.HelloCustom)
clientHelloSpec := tls.ClientHelloSpec{
CipherSuites: []uint16{
tls.GREASE_PLACEHOLDER,
tls.TLS_AES_128_GCM_SHA256,
tls.TLS_AES_256_GCM_SHA384,
tls.TLS_CHACHA20_POLY1305_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.DISABLED_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.DISABLED_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
tls.DISABLED_TLS_RSA_WITH_AES_256_CBC_SHA256,
tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
0xc008,
tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
},
CompressionMethods: []byte{
0x00, // compressionNone
},
Extensions: []tls.TLSExtension{
&tls.UtlsGREASEExtension{},
&tls.SNIExtension{},
&tls.UtlsExtendedMasterSecretExtension{},
&tls.RenegotiationInfoExtension{Renegotiation: tls.RenegotiateOnceAsClient},
&tls.SupportedCurvesExtension{Curves: []tls.CurveID{
tls.CurveID(tls.GREASE_PLACEHOLDER),
tls.X25519,
tls.CurveP256,
tls.CurveP384,
tls.CurveP521,
}},
&tls.SupportedPointsExtension{SupportedPoints: []byte{
0x00, // pointFormatUncompressed
}},
&tls.ALPNExtension{AlpnProtocols: []string{"h2", "http/1.1"}},
&tls.StatusRequestExtension{},
&tls.SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []tls.SignatureScheme{
tls.ECDSAWithP256AndSHA256,
tls.PSSWithSHA256,
tls.PKCS1WithSHA256,
tls.ECDSAWithP384AndSHA384,
tls.ECDSAWithSHA1,
tls.PSSWithSHA384,
tls.PSSWithSHA384,
tls.PKCS1WithSHA384,
tls.PSSWithSHA512,
tls.PKCS1WithSHA512,
tls.PKCS1WithSHA1,
}},
&tls.SCTExtension{},
&tls.KeyShareExtension{KeyShares: []tls.KeyShare{
{Group: tls.CurveID(tls.GREASE_PLACEHOLDER), Data: []byte{0}},
{Group: tls.X25519},
}},
&tls.PSKKeyExchangeModesExtension{Modes: []uint8{
tls.PskModeDHE,
}},
&tls.SupportedVersionsExtension{Versions: []uint16{
tls.GREASE_PLACEHOLDER,
tls.VersionTLS13,
tls.VersionTLS12,
tls.VersionTLS11,
tls.VersionTLS10,
}},
&tls.UtlsGREASEExtension{},
&tls.UtlsPaddingExtension{GetPaddingLen: tls.BoringPaddingStyle},
},
}
err = tlsConn.ApplyPreset(&clientHelloSpec)
if err != nil {
tcpConn.Close()
return nil, err
}
return tlsConn, nil
}
func (c *client) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
logrus.Info("outbound ", metadata.Protocol, " TCP ", conn.RemoteAddr(), " ==> ", metadata.Destination)
tlsConn, err := c.connect(ctx)
if err != nil {
return err
}
clientConn := trojan.NewClientConn(tlsConn, c.key, metadata.Destination)
err = conn.SetReadDeadline(time.Now().Add(300 * time.Millisecond))
if err != nil {
return err
}
_request := buf.StackNew()
request := common.Dup(_request)
_, err = request.ReadFrom(conn)
if err != nil && !E.IsTimeout(err) {
return E.Cause(err, "read payload")
}
err = conn.SetReadDeadline(time.Time{})
if err != nil {
return err
}
_, err = clientConn.Write(request.Bytes())
if err != nil {
return E.Cause(err, "client handshake")
}
runtime.KeepAlive(_request)
return bufio.CopyConn(ctx, clientConn, conn)
}
func (c *client) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
logrus.Info("outbound ", metadata.Protocol, " UDP ", metadata.Source, " ==> ", metadata.Destination)
tlsConn, err := c.connect(ctx)
if err != nil {
return err
}
/*err = trojan.ClientHandshakeRaw(tlsConn, c.key, trojan.CommandUDP, metadata.Destination, nil)
if err != nil {
return err
}
return socks.CopyPacketConn(ctx, &trojan.PacketConn{Conn: tlsConn}, conn)*/
clientConn := trojan.NewClientPacketConn(tlsConn, c.key)
return bufio.CopyPacketConn(ctx, clientConn, conn)
}
func (c *client) HandleError(err error) {
if E.IsClosed(err) {
return
}
logrus.Warn(err)
}

View file

@ -1,218 +0,0 @@
package main
import (
"context"
"crypto/tls"
"encoding/json"
"io/ioutil"
"net"
"net/netip"
"os"
"os/signal"
"syscall"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/acme"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
_ "github.com/sagernet/sing/common/log"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/protocol/trojan"
"github.com/sagernet/sing/transport/tcp"
transTLS "github.com/sagernet/sing/transport/tls"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const udpTimeout = 5 * 60
type flags struct {
Server string `json:"server"`
ServerPort uint16 `json:"server_port"`
ServerName string `json:"server_name"`
Bind string `json:"local_address"`
LocalPort uint16 `json:"local_port"`
Password string `json:"password"`
Verbose bool `json:"verbose"`
Insecure bool `json:"insecure"`
ACME *acme.Settings `json:"acme"`
ConfigFile string
}
func main() {
f := new(flags)
command := &cobra.Command{
Use: "trojan-local",
Short: "trojan client",
Version: sing.VersionStr,
Run: func(cmd *cobra.Command, args []string) {
run(cmd, f)
},
}
command.Flags().StringVarP(&f.Server, "server", "s", "", "Store the server’s hostname or IP.")
command.Flags().Uint16VarP(&f.ServerPort, "server-port", "p", 0, "Store the server’s port number.")
command.Flags().StringVarP(&f.Bind, "local-address", "b", "", "Store the local address.")
command.Flags().Uint16VarP(&f.LocalPort, "local-port", "l", 0, "Store the local port number.")
command.Flags().StringVarP(&f.Password, "password", "k", "", "Store the password. The server and the client should use the same password.")
command.Flags().BoolVarP(&f.Insecure, "insecure", "i", false, "Store insecure.")
command.Flags().StringVarP(&f.ConfigFile, "config", "c", "", "Use a configuration file.")
command.Flags().BoolVarP(&f.Verbose, "verbose", "v", false, "Store verbose mode.")
err := command.Execute()
if err != nil {
logrus.Fatal(err)
}
}
func run(cmd *cobra.Command, f *flags) {
c, err := newServer(f)
if err != nil {
logrus.StandardLogger().Log(logrus.FatalLevel, err, "\n\n")
cmd.Help()
os.Exit(1)
}
if f.ACME != nil && f.ACME.Enabled {
err = f.ACME.SetupEnvironment()
if err != nil {
logrus.Fatal(err)
}
acmeManager := acme.NewCertificateManager(f.ACME)
certificate, err := acmeManager.GetKeyPair(f.ServerName)
if err != nil {
logrus.Fatal(err)
}
c.tlsConfig.Certificates = []tls.Certificate{*certificate}
acmeManager.RegisterUpdateListener(f.ServerName, func(certificate *tls.Certificate) {
c.tlsConfig.Certificates = []tls.Certificate{*certificate}
})
}
err = c.tcpIn.Start()
if err != nil {
logrus.Fatal(err)
}
logrus.Info("server started at ", c.tcpIn.Addr())
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
<-osSignals
c.tcpIn.Close()
}
type server struct {
tcpIn *tcp.Listener
service trojan.Service[int]
tlsConfig tls.Config
}
func newServer(f *flags) (*server, error) {
s := new(server)
if f.ConfigFile != "" {
configFile, err := ioutil.ReadFile(f.ConfigFile)
if err != nil {
return nil, E.Cause(err, "read config file")
}
flagsNew := new(flags)
err = json.Unmarshal(configFile, flagsNew)
if err != nil {
return nil, E.Cause(err, "decode config file")
}
if flagsNew.Server != "" && f.Server == "" {
f.Server = flagsNew.Server
}
if flagsNew.ServerPort != 0 && f.ServerPort == 0 {
f.ServerPort = flagsNew.ServerPort
}
if flagsNew.ServerName != "" && f.ServerName == "" {
f.ServerName = flagsNew.ServerName
}
if flagsNew.Bind != "" && f.Bind == "" {
f.Bind = flagsNew.Bind
}
if flagsNew.LocalPort != 0 && f.LocalPort == 0 {
f.LocalPort = flagsNew.LocalPort
}
if flagsNew.Password != "" && f.Password == "" {
f.Password = flagsNew.Password
}
if flagsNew.Insecure {
f.Insecure = true
}
if flagsNew.ACME != nil {
f.ACME = flagsNew.ACME
}
if flagsNew.Verbose {
f.Verbose = true
}
}
if f.Verbose {
logrus.SetLevel(logrus.TraceLevel)
}
if f.Server == "" {
return nil, E.New("missing server address")
} else if f.ServerPort == 0 {
return nil, E.New("missing server port")
}
var bind netip.Addr
if f.Server != "" {
addr, err := netip.ParseAddr(f.Server)
if err != nil {
return nil, E.Cause(err, "bad server address")
}
bind = addr
} else {
bind = netip.IPv6Unspecified()
}
s.service = trojan.NewService[int](s)
common.Must(s.service.AddUser(0, f.Password))
s.tcpIn = tcp.NewTCPListener(netip.AddrPortFrom(bind, f.ServerPort), s)
return s, nil
}
func (s *server) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
if metadata.Protocol != "trojan" {
logrus.Trace("inbound raw TCP from ", metadata.Source)
if len(s.tlsConfig.Certificates) == 0 {
s.tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
return transTLS.GenerateCertificate(info.ServerName)
}
} else {
s.tlsConfig.GetCertificate = nil
}
return s.service.NewConnection(ctx, tls.Server(conn, &s.tlsConfig), metadata)
}
destConn, err := N.SystemDialer.DialContext(context.Background(), "tcp", metadata.Destination)
if err != nil {
return err
}
logrus.Info("inbound TCP ", conn.RemoteAddr(), " ==> ", metadata.Destination)
return bufio.CopyConn(ctx, conn, destConn)
}
func (s *server) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
logrus.Info("inbound UDP ", metadata.Source, " ==> ", metadata.Destination)
udpConn, err := net.ListenUDP("udp", nil)
if err != nil {
return err
}
return bufio.CopyNetPacketConn(ctx, conn, udpConn)
}
func (s *server) HandleError(err error) {
common.Close(err)
if E.IsClosed(err) {
return
}
logrus.Warn(err)
}

View file

@ -1,131 +0,0 @@
package main
import (
"context"
"net"
"net/netip"
"os"
"os/signal"
"syscall"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
_ "github.com/sagernet/sing/common/log"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/redir"
"github.com/sagernet/sing/common/uot"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/transport/mixed"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var (
verbose bool
transproxy string
)
func main() {
command := cobra.Command{
Use: "uot-local <bind> <upstream>",
Short: "SUoT client.",
Long: "SUoT client. \n\nconverts a normal socks server to a SUoT mixed server.",
Example: "uot-local 0.0.0.0:2080 127.0.0.1:1080",
Version: sing.VersionStr,
Args: cobra.ExactArgs(2),
Run: run,
}
command.Flags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose mode")
command.Flags().StringVarP(&transproxy, "transproxy", "t", "", "Enable transparent proxy support [possible values: redirect, tproxy]")
err := command.Execute()
if err != nil {
logrus.Fatal(err)
}
}
func run(cmd *cobra.Command, args []string) {
if verbose {
logrus.SetLevel(logrus.TraceLevel)
}
bind, err := netip.ParseAddrPort(args[0])
if err != nil {
logrus.Fatal("bad bind address: ", err)
}
_, err = netip.ParseAddrPort(args[1])
if err != nil {
logrus.Fatal("bad upstream address: ", err)
}
var transproxyMode redir.TransproxyMode
switch transproxy {
case "redirect":
transproxyMode = redir.ModeRedirect
case "tproxy":
transproxyMode = redir.ModeTProxy
case "":
transproxyMode = redir.ModeDisabled
default:
logrus.Fatal("unknown transproxy mode ", transproxy)
}
socks, err := socks.NewClientFromURL(N.SystemDialer, args[1])
if err != nil {
logrus.Fatal(err)
}
client := &localClient{upstream: socks}
client.Listener = mixed.NewListener(bind, nil, transproxyMode, 300, client)
err = client.Start()
if err != nil {
logrus.Fatal("start mixed server: ", err)
}
logrus.Info("mixed server started at ", client.TCPListener.Addr())
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
<-osSignals
client.Close()
}
type localClient struct {
*mixed.Listener
upstream *socks.Client
}
func (c *localClient) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
logrus.Info("inbound ", metadata.Protocol, " TCP ", metadata.Source, " ==> ", metadata.Destination)
upstream, err := c.upstream.DialContext(ctx, "tcp", metadata.Destination)
if err != nil {
return err
}
return bufio.CopyConn(context.Background(), conn, upstream)
}
func (c *localClient) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
logrus.Info("inbound ", metadata.Protocol, " UDP ", metadata.Source, " ==> ", metadata.Destination)
upstream, err := c.upstream.DialContext(ctx, "tcp", metadata.Destination)
if err != nil {
return err
}
return bufio.CopyPacketConn(ctx, conn, uot.NewClientConn(upstream))
}
func (c *localClient) OnError(err error) {
common.Close(err)
if E.IsClosed(err) {
return
}
logrus.Warn(err)
}

View file

@ -1,312 +0,0 @@
package acme
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/lego"
legoLog "github.com/go-acme/lego/v4/log"
"github.com/go-acme/lego/v4/registration"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/log"
)
func init() {
legoLog.Logger = log.NewLogger("acme")
}
type CertificateUpdateListener func(certificate *tls.Certificate)
type CertificateManager struct {
email string
path string
provider string
access sync.Mutex
callbacks map[string][]CertificateUpdateListener
renew *time.Ticker
}
func NewCertificateManager(settings *Settings) *CertificateManager {
m := &CertificateManager{
email: settings.Email,
path: settings.DataDirectory,
provider: settings.DNSProvider,
renew: time.NewTicker(time.Hour * 24),
}
if m.path == "" {
m.path = "acme"
}
go m.loopRenew()
return m
}
func (c *CertificateManager) GetKeyPair(domain string) (*tls.Certificate, error) {
if domain == "" {
return nil, E.New("acme: empty domain name")
}
dnsProvider, err := NewDNSChallengeProviderByName(c.provider)
if err != nil {
return nil, err
}
accountPath := c.path + "/account.json"
accountKeyPath := c.path + "/account.key"
privateKeyPath := c.path + "/" + domain + ".key"
certificatePath := c.path + "/" + domain + ".crt"
requestPath := c.path + "/" + domain + ".json"
if !common.FileExists(accountKeyPath) {
err = writeNewPrivateKey(accountKeyPath)
if err != nil {
return nil, err
}
}
accountKey, err := readPrivateKey(accountKeyPath)
if err != nil {
return nil, err
}
user := &acmeUser{
email: c.email,
privateKey: accountKey,
}
if common.FileExists(accountPath) {
var account registration.Resource
err = common.ReadJSON(accountPath, &account)
if err != nil {
return nil, err
}
user.registration = &account
}
config := lego.NewConfig(user)
config.Certificate.KeyType = certcrypto.RSA4096
client, err := lego.NewClient(config)
if err != nil {
return nil, err
}
err = client.Challenge.SetDNS01Provider(dnsProvider)
if err != nil {
return nil, err
}
if user.GetRegistration() == nil {
account, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
return nil, err
}
user.registration = account
err = common.WriteJSON(accountPath, account)
if err != nil {
return nil, err
}
}
var renew bool
keyPair, err := tls.LoadX509KeyPair(certificatePath, privateKeyPath)
if err == nil {
cert, err := x509.ParseCertificate(keyPair.Certificate[0])
if err == nil {
keyPair.Leaf = cert
expiresDays := cert.NotAfter.Sub(time.Now()).Hours() / 24
if expiresDays > 15 {
return &keyPair, nil
} else {
renew = true
}
}
}
if renew && common.FileExists(requestPath) {
var request Certificate
err = common.ReadJSON(requestPath, &request)
if err != nil {
return nil, err
}
newCert, err := client.Certificate.Renew((certificate.Resource)(request), true, false, "")
if err != nil {
return nil, err
}
err = common.WriteJSON(requestPath, (*Certificate)(newCert))
if err != nil {
return nil, err
}
certResponse, err := http.Get(newCert.CertURL)
if err != nil {
return nil, err
}
defer certResponse.Body.Close()
content, err := ioutil.ReadAll(certResponse.Body)
if err != nil {
return nil, err
}
if certResponse.StatusCode != 200 {
return nil, E.New("HTTP ", certResponse.StatusCode, ": ", string(content))
}
err = ioutil.WriteFile(certificatePath, content, 0o644)
if err != nil {
return nil, err
}
keyPair, err = tls.LoadX509KeyPair(certificatePath, privateKeyPath)
if err != nil {
return nil, err
}
goto finish
}
if !common.FileExists(certificatePath) {
if !common.FileExists(privateKeyPath) {
err = writeNewPrivateKey(privateKeyPath)
if err != nil {
return nil, err
}
}
privateKey, err := readPrivateKey(privateKeyPath)
if err != nil {
return nil, err
}
request := certificate.ObtainRequest{
Domains: []string{domain},
Bundle: true,
PrivateKey: privateKey,
}
certificates, err := client.Certificate.Obtain(request)
if err != nil {
return nil, err
}
err = common.WriteJSON(requestPath, (*Certificate)(certificates))
if err != nil {
return nil, err
}
certResponse, err := http.Get(certificates.CertURL)
if err != nil {
return nil, err
}
defer certResponse.Body.Close()
content, err := ioutil.ReadAll(certResponse.Body)
if err != nil {
return nil, err
}
if certResponse.StatusCode != 200 {
return nil, E.New("HTTP ", certResponse.StatusCode, ": ", string(content))
}
err = ioutil.WriteFile(certificatePath, content, 0o644)
if err != nil {
return nil, err
}
}
finish:
keyPair, err = tls.LoadX509KeyPair(certificatePath, privateKeyPath)
if err != nil {
return nil, err
}
c.access.Lock()
for _, listener := range c.callbacks[domain] {
listener(&keyPair)
}
c.access.Unlock()
return &keyPair, nil
}
func (c *CertificateManager) RegisterUpdateListener(domain string, listener CertificateUpdateListener) {
c.access.Lock()
defer c.access.Unlock()
if c.callbacks == nil {
c.callbacks = make(map[string][]CertificateUpdateListener)
}
c.callbacks[domain] = append(c.callbacks[domain], listener)
}
func (c *CertificateManager) loopRenew() {
for range c.renew.C {
c.access.Lock()
domains := make([]string, 0, len(c.callbacks))
for domain := range c.callbacks {
domains = append(domains, domain)
}
c.access.Unlock()
for _, domain := range domains {
_, _ = c.GetKeyPair(domain)
}
}
}
type acmeUser struct {
email string
privateKey crypto.PrivateKey
registration *registration.Resource
}
func (u *acmeUser) GetEmail() string {
return u.email
}
func (u *acmeUser) GetRegistration() *registration.Resource {
return u.registration
}
func (u *acmeUser) GetPrivateKey() crypto.PrivateKey {
return u.privateKey
}
func readPrivateKey(path string) (crypto.PrivateKey, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(content)
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return privateKey.(crypto.PrivateKey), nil
}
func writeNewPrivateKey(path string) error {
privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return err
}
pkcsBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return err
}
return common.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcsBytes}))
}
type Certificate struct {
Domain string `json:"domain"`
CertURL string `json:"certUrl"`
CertStableURL string `json:"certStableUrl"`
PrivateKey []byte `json:"private_key"`
Certificate []byte `json:"certificate"`
IssuerCertificate []byte `json:"issuer_certificate"`
CSR []byte `json:"csr"`
}

View file

@ -1,108 +0,0 @@
package cloudflare
import (
"context"
"strings"
"sync"
"github.com/cloudflare/cloudflare-go"
E "github.com/sagernet/sing/common/exceptions"
)
type metaClient struct {
clientEdit *cloudflare.API // needs Zone/DNS/Edit permissions
clientRead *cloudflare.API // needs Zone/Zone/Read permissions
zones map[string]string // caches calls to ZoneIDByName
zonesMu *sync.RWMutex
}
func newClient(config *Config) (*metaClient, error) {
// with AuthKey/AuthEmail we can access all available APIs
if config.AuthToken == "" {
client, err := cloudflare.New(config.AuthKey, config.AuthEmail, cloudflare.HTTPClient(config.HTTPClient))
if err != nil {
return nil, err
}
return &metaClient{
clientEdit: client,
clientRead: client,
zones: make(map[string]string),
zonesMu: &sync.RWMutex{},
}, nil
}
dns, err := cloudflare.NewWithAPIToken(config.AuthToken, cloudflare.HTTPClient(config.HTTPClient))
if err != nil {
return nil, err
}
if config.ZoneToken == "" || config.ZoneToken == config.AuthToken {
return &metaClient{
clientEdit: dns,
clientRead: dns,
zones: make(map[string]string),
zonesMu: &sync.RWMutex{},
}, nil
}
zone, err := cloudflare.NewWithAPIToken(config.ZoneToken, cloudflare.HTTPClient(config.HTTPClient))
if err != nil {
return nil, err
}
return &metaClient{
clientEdit: dns,
clientRead: zone,
zones: make(map[string]string),
zonesMu: &sync.RWMutex{},
}, nil
}
func (m *metaClient) CreateDNSRecord(ctx context.Context, zoneID string, rr cloudflare.DNSRecord) (*cloudflare.DNSRecordResponse, error) {
return m.clientEdit.CreateDNSRecord(ctx, zoneID, rr)
}
func (m *metaClient) DNSRecords(ctx context.Context, zoneID string, rr cloudflare.DNSRecord) ([]cloudflare.DNSRecord, error) {
return m.clientEdit.DNSRecords(ctx, zoneID, rr)
}
func (m *metaClient) DeleteDNSRecord(ctx context.Context, zoneID, recordID string) error {
return m.clientEdit.DeleteDNSRecord(ctx, zoneID, recordID)
}
func (m *metaClient) ZoneIDByName(fqdn string) (string, error) {
if fqdn[len(fqdn)-1] == '.' {
fqdn = fqdn[:len(fqdn)-1]
}
m.zonesMu.RLock()
for name, zoneId := range m.zones {
if strings.HasSuffix(fqdn, name) {
return zoneId, nil
}
}
m.zonesMu.RUnlock()
zones, err := m.clientRead.ListZones(context.Background())
if err != nil {
return "", err
}
m.zonesMu.Lock()
for _, zone := range zones {
m.zones[zone.Name] = zone.ID
}
m.zonesMu.Unlock()
for name, zoneId := range m.zones {
if strings.HasSuffix(fqdn, name) {
return zoneId, nil
}
}
return "", E.New("zone not found for domain ", fqdn)
}

View file

@ -1,185 +0,0 @@
// Package cloudflare implements a DNS provider for solving the DNS-01 challenge using cloudflare DNS.
package cloudflare
import (
"context"
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/cloudflare/cloudflare-go"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/log"
"github.com/go-acme/lego/v4/platform/config/env"
)
const (
minTTL = 120
)
// Config is used to configure the creation of the DNSProvider.
type Config struct {
AuthEmail string
AuthKey string
AuthToken string
ZoneToken string
TTL int
PropagationTimeout time.Duration
PollingInterval time.Duration
HTTPClient *http.Client
}
// NewDefaultConfig returns a default configuration for the DNSProvider.
func NewDefaultConfig() *Config {
return &Config{
TTL: env.GetOrDefaultInt("CLOUDFLARE_TTL", minTTL),
PropagationTimeout: env.GetOrDefaultSecond("CLOUDFLARE_PROPAGATION_TIMEOUT", 2*time.Minute),
PollingInterval: env.GetOrDefaultSecond("CLOUDFLARE_POLLING_INTERVAL", 2*time.Second),
HTTPClient: &http.Client{
Timeout: env.GetOrDefaultSecond("CLOUDFLARE_HTTP_TIMEOUT", 30*time.Second),
},
}
}
// DNSProvider implements the challenge.Provider interface.
type DNSProvider struct {
client *metaClient
config *Config
recordIDs map[string]string
recordIDsMu sync.Mutex
}
// NewDNSProvider returns a DNSProvider instance configured for Cloudflare.
// Credentials must be passed in as environment variables:
//
// Either provide CLOUDFLARE_EMAIL and CLOUDFLARE_API_KEY,
// or a CLOUDFLARE_DNS_API_TOKEN.
//
// For a more paranoid setup, provide CLOUDFLARE_DNS_API_TOKEN and CLOUDFLARE_ZONE_API_TOKEN.
//
// The email and API key should be avoided, if possible.
// Instead setup a API token with both Zone:Read and DNS:Edit permission, and pass the CLOUDFLARE_DNS_API_TOKEN environment variable.
// You can split the Zone:Read and DNS:Edit permissions across multiple API tokens:
// in this case pass both CLOUDFLARE_ZONE_API_TOKEN and CLOUDFLARE_DNS_API_TOKEN accordingly.
func NewDNSProvider() (*DNSProvider, error) {
values, err := env.GetWithFallback(
[]string{"CLOUDFLARE_EMAIL", "CF_API_EMAIL"},
[]string{"CLOUDFLARE_API_KEY", "CF_API_KEY"},
)
if err != nil {
var errT error
values, errT = env.GetWithFallback(
[]string{"CLOUDFLARE_DNS_API_TOKEN", "CF_DNS_API_TOKEN"},
[]string{"CLOUDFLARE_ZONE_API_TOKEN", "CF_ZONE_API_TOKEN", "CLOUDFLARE_DNS_API_TOKEN", "CF_DNS_API_TOKEN"},
)
if errT != nil {
// nolint:errorlint
return nil, fmt.Errorf("cloudflare: %v or %v", err, errT)
}
}
config := NewDefaultConfig()
config.AuthEmail = values["CLOUDFLARE_EMAIL"]
config.AuthKey = values["CLOUDFLARE_API_KEY"]
config.AuthToken = values["CLOUDFLARE_DNS_API_TOKEN"]
config.ZoneToken = values["CLOUDFLARE_ZONE_API_TOKEN"]
return NewDNSProviderConfig(config)
}
// NewDNSProviderConfig return a DNSProvider instance configured for Cloudflare.
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("cloudflare: the configuration of the DNS provider is nil")
}
if config.TTL < minTTL {
return nil, fmt.Errorf("cloudflare: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL)
}
client, err := newClient(config)
if err != nil {
return nil, fmt.Errorf("cloudflare: %w", err)
}
return &DNSProvider{
client: client,
config: config,
recordIDs: make(map[string]string),
}, nil
}
// Timeout returns the timeout and interval to use when checking for DNS propagation.
// Adjusting here to cope with spikes in propagation times.
func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
return d.config.PropagationTimeout, d.config.PollingInterval
}
// Present creates a TXT record to fulfill the dns-01 challenge.
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value := dns01.GetRecord(domain, keyAuth)
zoneID, err := d.client.ZoneIDByName(fqdn)
if err != nil {
return fmt.Errorf("cloudflare: failed to find zone %s: %w", fqdn, err)
}
dnsRecord := cloudflare.DNSRecord{
Type: "TXT",
Name: dns01.UnFqdn(fqdn),
Content: value,
TTL: d.config.TTL,
}
response, err := d.client.CreateDNSRecord(context.Background(), zoneID, dnsRecord)
if err != nil {
return fmt.Errorf("cloudflare: failed to create TXT record: %w", err)
}
if !response.Success {
return fmt.Errorf("cloudflare: failed to create TXT record: %+v %+v", response.Errors, response.Messages)
}
d.recordIDsMu.Lock()
d.recordIDs[token] = response.Result.ID
d.recordIDsMu.Unlock()
log.Infof("cloudflare: new record for %s, ID %s", domain, response.Result.ID)
return nil
}
// CleanUp removes the TXT record matching the specified parameters.
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
fqdn, _ := dns01.GetRecord(domain, keyAuth)
zoneID, err := d.client.ZoneIDByName(fqdn)
if err != nil {
return fmt.Errorf("cloudflare: failed to find zone %s: %w", fqdn, err)
}
// get the record's unique ID from when we created it
d.recordIDsMu.Lock()
recordID, ok := d.recordIDs[token]
d.recordIDsMu.Unlock()
if !ok {
return fmt.Errorf("cloudflare: unknown record ID for '%s'", fqdn)
}
err = d.client.DeleteDNSRecord(context.Background(), zoneID, recordID)
if err != nil {
log.Printf("cloudflare: failed to delete TXT record: %w", err)
}
// Delete record ID from map
d.recordIDsMu.Lock()
delete(d.recordIDs, token)
d.recordIDsMu.Unlock()
return nil
}

View file

@ -1,37 +0,0 @@
package acme
import (
"os"
"github.com/go-acme/lego/v4/challenge"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/acme/cloudflare"
E "github.com/sagernet/sing/common/exceptions"
)
type Settings struct {
Enabled bool `json:"enabled"`
DataDirectory string `json:"data_directory"`
Email string `json:"email"`
DNSProvider string `json:"dns_provider"`
DNSEnv *common.JSONMap `json:"dns_env"`
}
func (s *Settings) SetupEnvironment() error {
for envName, envValue := range s.DNSEnv.Data {
err := os.Setenv(envName, envValue.(string))
if err != nil {
return err
}
}
return nil
}
func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
switch name {
case "cloudflare":
return cloudflare.NewDNSProvider()
}
// return dns.NewDNSChallengeProviderByName(name)
return nil, E.New("unsupported dns provider ", name)
}

View file

@ -361,38 +361,3 @@ func (b Buffer) IsEmpty() bool {
func (b Buffer) IsFull() bool {
return b.end == b.Cap()
}
func (b Buffer) ToOwned() *Buffer {
var buffer *Buffer
if b.Len() > BufferSize {
buffer = As(make([]byte, b.Len()))
copy(buffer.data, b.Bytes())
} else {
buffer = New()
buffer.Write(b.Bytes())
}
return buffer
}
func (b Buffer) Copy() []byte {
buffer := make([]byte, b.Len())
copy(buffer, b.Bytes())
return buffer
}
func ForeachN(b []byte, size int) [][]byte {
total := len(b)
var index int
var retArr [][]byte
for {
nextIndex := index + size
if nextIndex < total {
retArr = append(retArr, b[index:nextIndex])
index = nextIndex
} else {
retArr = append(retArr, b[index:])
break
}
}
return retArr
}

View file

@ -4,9 +4,7 @@ import (
"context"
"io"
"net"
"os"
"runtime"
"time"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
@ -16,24 +14,6 @@ import (
"github.com/sagernet/sing/common/task"
)
type PacketConnStub struct{}
func (s *PacketConnStub) RemoteAddr() net.Addr {
return &common.DummyAddr{}
}
func (s *PacketConnStub) SetDeadline(t time.Time) error {
return os.ErrInvalid
}
func (s *PacketConnStub) SetReadDeadline(t time.Time) error {
return os.ErrInvalid
}
func (s *PacketConnStub) SetWriteDeadline(t time.Time) error {
return os.ErrInvalid
}
func Copy(dst io.Writer, src io.Reader) (n int64, err error) {
if wt, ok := src.(io.WriterTo); ok {
return wt.WriteTo(dst)

View file

@ -3,7 +3,6 @@ package common
import (
"context"
"io"
"strings"
"unsafe"
)
@ -93,22 +92,6 @@ func Done(ctx context.Context) bool {
}
}
func IsEmpty[T any](array []T) bool {
return len(array) == 0
}
func IsNotEmpty[T any](array []T) bool {
return len(array) > 0
}
func IsBlank(str string) bool {
return strings.TrimSpace(str) == ""
}
func IsNotBlank(str string) bool {
return strings.TrimSpace(str) != ""
}
func Error(_ any, err error) error {
return err
}
@ -154,10 +137,3 @@ func Close(closers ...any) error {
}
return retErr
}
func CloseError(closer any, err error) error {
if err == nil {
return nil
}
return Close(closer)
}

View file

@ -1,85 +0,0 @@
package common
import (
"io"
"net"
"time"
)
type ReadOnlyException struct{}
func (e *ReadOnlyException) Error() string {
return "read only connection"
}
type WriteOnlyException struct{}
func (e *WriteOnlyException) Error() string {
return "write only connection"
}
type readWriteConn struct {
io.Reader
io.Writer
}
func (r *readWriteConn) Close() error {
Close(r.Reader)
return nil
}
func (r *readWriteConn) LocalAddr() net.Addr {
return &DummyAddr{}
}
func (r *readWriteConn) RemoteAddr() net.Addr {
return &DummyAddr{}
}
func (r *readWriteConn) SetDeadline(t time.Time) error {
return nil
}
func (r *readWriteConn) SetReadDeadline(t time.Time) error {
return nil
}
func (r *readWriteConn) SetWriteDeadline(t time.Time) error {
return nil
}
type readConn struct {
readWriteConn
}
func (r *readConn) Write(b []byte) (n int, err error) {
return 0, &ReadOnlyException{}
}
type writeConn struct {
readWriteConn
io.Writer
}
func (w *writeConn) Read(p []byte) (n int, err error) {
return 0, &WriteOnlyException{}
}
func NewReadConn(reader io.Reader) net.Conn {
c := &readConn{}
c.Reader = reader
return c
}
func NewWritConn(writer io.Writer) net.Conn {
c := &writeConn{}
c.Writer = writer
return c
}
func NewReadWriteConn(reader io.Reader, writer io.Writer) net.Conn {
c := &readConn{}
c.Reader = reader
c.Writer = writer
return c
}

View file

@ -1,11 +0,0 @@
package common
type DummyAddr struct{}
func (d *DummyAddr) Network() string {
return "dummy"
}
func (d *DummyAddr) String() string {
return "dummy"
}

View file

@ -1,33 +0,0 @@
package geoip
import (
"net"
"strings"
"sync"
"github.com/oschwald/geoip2-golang"
)
var (
mmdb *geoip2.Reader
loadOnce sync.Once
loadErr error
)
func LoadMMDB(path string) error {
if loadErr != nil {
loadOnce = sync.Once{}
}
loadOnce.Do(func() {
mmdb, loadErr = geoip2.Open(path)
})
return loadErr
}
func Match(code string, ip net.IP) bool {
country, err := mmdb.Country(ip)
if err != nil {
return false
}
return strings.EqualFold(country.Country.IsoCode, code)
}

View file

@ -1,50 +0,0 @@
package geosite
import (
"regexp"
"strings"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/trieset"
)
type Matcher struct {
ds *trieset.DomainSet
regex []*regexp.Regexp
}
func (m *Matcher) Match(domain string) bool {
match := m.ds.Has(domain)
if match {
return match
}
if m.regex != nil {
for _, pattern := range m.regex {
match = pattern.MatchString(domain)
if match {
return match
}
}
}
return false
}
func NewMatcher(domains []string) (*Matcher, error) {
var regex []*regexp.Regexp
for i := range domains {
domain := domains[i]
if strings.HasPrefix(domain, "regexp:") {
domain = domain[7:]
pattern, err := regexp.Compile(domain)
if err != nil {
return nil, E.Cause(err, "compile regex rule ", domain)
}
regex = append(regex, pattern)
}
}
ds, err := trieset.New(domains)
if err != nil {
return nil, err
}
return &Matcher{ds, regex}, nil
}

View file

@ -1,238 +0,0 @@
package geosite
import (
"bytes"
"io"
"sort"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/rw"
)
func Write(writer io.Writer, geosite map[string][]string) error {
keys := make([]string, 0, len(geosite))
for code := range geosite {
keys = append(keys, code)
}
sort.Strings(keys)
content := &bytes.Buffer{}
index := make(map[string]int)
for _, code := range keys {
index[code] = content.Len()
for _, domain := range geosite[code] {
if err := rw.WriteVString(content, domain); err != nil {
return err
}
}
}
err := rw.WriteByte(writer, 0)
if err != nil {
return err
}
err = rw.WriteUVariant(writer, uint64(len(keys)))
if err != nil {
return err
}
for _, code := range keys {
err = rw.WriteVString(writer, code)
if err != nil {
return err
}
err = rw.WriteUVariant(writer, uint64(index[code]))
if err != nil {
return err
}
err = rw.WriteUVariant(writer, uint64(len(geosite[code])))
if err != nil {
return err
}
}
_, err = writer.Write(content.Bytes())
if err != nil {
return err
}
return nil
}
func Read(reader io.Reader, codes ...string) (map[string][]string, error) {
version, err := rw.ReadByte(reader)
if err != nil {
return nil, err
}
if version != 0 {
return nil, E.New("bad version")
}
length, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
keys := make([]string, length)
domainIndex := make(map[string]int)
domainLength := make(map[string]int)
for i := 0; i < int(length); i++ {
code, err := rw.ReadVString(reader)
if err != nil {
return nil, err
}
keys[i] = code
codeIndex, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
codeLength, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
domainIndex[code] = int(codeIndex)
domainLength[code] = int(codeLength)
}
site := make(map[string][]string)
for _, code := range keys {
if len(codes) == 0 || common.Contains(codes, code) {
domains := make([]string, domainLength[code])
for i := range domains {
domains[i], err = rw.ReadVString(reader)
if err != nil {
return nil, err
}
}
site[code] = domains
} else {
dLength := domainLength[code]
for i := 0; i < dLength; i++ {
_, err = rw.ReadVString(reader)
if err != nil {
return nil, err
}
}
}
}
return site, nil
}
func ReadSeek(reader io.ReadSeeker, codes ...string) (map[string][]string, error) {
version, err := rw.ReadByte(reader)
if err != nil {
return nil, err
}
if version != 0 {
return nil, E.New("bad version")
}
length, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
keys := make([]string, length)
domainIndex := make(map[string]int)
domainLength := make(map[string]int)
for i := 0; i < int(length); i++ {
code, err := rw.ReadVString(reader)
if err != nil {
return nil, err
}
keys[i] = code
codeIndex, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
codeLength, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
domainIndex[code] = int(codeIndex)
domainLength[code] = int(codeLength)
}
if len(codes) == 0 {
codes = keys
}
site := make(map[string][]string)
counter := &rw.ReadCounter{Reader: reader}
for _, code := range codes {
domains := make([]string, domainLength[code])
if _, exists := domainIndex[code]; !exists {
return nil, E.New("code ", code, " not exists!")
}
_, err = reader.Seek(int64(domainIndex[code])-counter.Count(), io.SeekCurrent)
if err != nil {
return nil, err
}
for i := range domains {
domains[i], err = rw.ReadVString(reader)
if err != nil {
return nil, err
}
}
site[code] = domains
}
return site, nil
}
func ReadArray(reader io.ReadSeeker, codes ...string) ([]string, error) {
version, err := rw.ReadByte(reader)
if err != nil {
return nil, err
}
if version != 0 {
return nil, E.New("bad version")
}
length, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
keys := make([]string, length)
domainIndex := make(map[string]int)
domainLength := make(map[string]int)
for i := 0; i < int(length); i++ {
code, err := rw.ReadVString(reader)
if err != nil {
return nil, err
}
keys[i] = code
codeIndex, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
codeLength, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
domainIndex[code] = int(codeIndex)
domainLength[code] = int(codeLength)
}
if len(codes) == 0 {
codes = keys
}
var domainL int
for _, code := range keys {
if _, exists := domainIndex[code]; !exists {
return nil, E.New("code ", code, " not exists!")
}
domainL += domainLength[code]
}
domains := make([]string, 0, domainL)
counter := &rw.ReadCounter{Reader: reader}
for _, code := range codes {
_, err := reader.Seek(int64(domainIndex[code])-counter.Count(), io.SeekCurrent)
if err != nil {
return nil, err
}
codeL := domainLength[code]
for i := 0; i < codeL; i++ {
domain, err := rw.ReadVString(reader)
if err != nil {
return nil, err
}
domains = append(domains, domain)
}
}
return domains, nil
}

View file

@ -1,84 +0,0 @@
package geosite
import (
"io"
"strings"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/rw"
)
type Reader struct {
reader io.ReadSeeker
counter *rw.ReadCounter
domainIndex map[string]int
domainLength map[string]int
cache map[string][]string
}
func NewReader(reader io.ReadSeeker) (*Reader, error) {
r := &Reader{
reader: reader,
counter: &rw.ReadCounter{Reader: reader},
domainIndex: map[string]int{},
domainLength: map[string]int{},
cache: map[string][]string{},
}
version, err := rw.ReadByte(reader)
if err != nil {
return nil, err
}
if version != 0 {
return nil, E.New("bad version")
}
length, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
for i := 0; i < int(length); i++ {
code, err := rw.ReadVString(reader)
if err != nil {
return nil, err
}
domainIndex, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
domainLength, err := rw.ReadUVariant(reader)
if err != nil {
return nil, err
}
r.domainIndex[code] = int(domainIndex)
r.domainLength[code] = int(domainLength)
}
return r, nil
}
func (r *Reader) Load(code string) ([]string, error) {
code = strings.ToLower(code)
if cache, ok := r.cache[code]; ok {
return cache, nil
}
index, exists := r.domainIndex[code]
if !exists {
return nil, E.New("code ", code, " not exists!")
}
_, err := r.reader.Seek(int64(index)-r.counter.Count(), io.SeekCurrent)
if err != nil {
return nil, err
}
r.counter.Reset()
dLength := r.domainLength[code]
domains := make([]string, dLength)
for i := 0; i < dLength; i++ {
domains[i], err = rw.ReadVString(r.counter)
if err != nil {
return nil, err
}
}
r.cache[code] = domains
return domains, nil
}

View file

@ -1,395 +0,0 @@
// Copyright 2016 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.
package gsync
import (
"sync"
"sync/atomic"
"unsafe"
)
// Map is like a Go map[interface{}]interface{} but is safe for concurrent use
// by multiple goroutines without additional locking or coordination.
// Loads, stores, and deletes run in amortized constant time.
//
// The Map type is specialized. Most code should use a plain Go map instead,
// with separate locking or coordination, for better type safety and to make it
// easier to maintain other invariants along with the map content.
//
// The Map type is optimized for two common use cases: (1) when the entry for a given
// key is only ever written once but read many times, as in caches that only grow,
// or (2) when multiple goroutines read, write, and overwrite entries for disjoint
// sets of keys. In these two cases, use of a Map may significantly reduce lock
// contention compared to a Go map paired with a separate Mutex or RWMutex.
//
// The zero Map is empty and ready for use. A Map must not be copied after first use.
type Map[K comparable, V any] struct {
mu sync.Mutex
// read contains the portion of the map's contents that are safe for
// concurrent access (with or without mu held).
//
// The read field itself is always safe to load, but must only be stored with
// mu held.
//
// Entries stored in read may be updated concurrently without mu, but updating
// a previously-expunged entry requires that the entry be copied to the dirty
// map and unexpunged with mu held.
read atomic.Value // readOnly
// dirty contains the portion of the map's contents that require mu to be
// held. To ensure that the dirty map can be promoted to the read map quickly,
// it also includes all of the non-expunged entries in the read map.
//
// Expunged entries are not stored in the dirty map. An expunged entry in the
// clean map must be unexpunged and added to the dirty map before a new value
// can be stored to it.
//
// If the dirty map is nil, the next write to the map will initialize it by
// making a shallow copy of the clean map, omitting stale entries.
dirty map[K]*entry[V]
// misses counts the number of loads since the read map was last updated that
// needed to lock mu to determine whether the key was present.
//
// Once enough misses have occurred to cover the cost of copying the dirty
// map, the dirty map will be promoted to the read map (in the unamended
// state) and the next store to the map will make a new dirty copy.
misses int
}
// readOnly is an immutable struct stored atomically in the Map.read field.
type readOnly[K comparable, V any] struct {
m map[K]*entry[V]
amended bool // true if the dirty map contains some key not in m.
}
// expunged is an arbitrary pointer that marks entries which have been deleted
// from the dirty map.
var expunged = unsafe.Pointer(new(any))
// An entry is a slot in the map corresponding to a particular key.
type entry[T any] struct {
// p points to the interface{} value stored for the entry.
//
// If p == nil, the entry has been deleted, and either m.dirty == nil or
// m.dirty[key] is e.
//
// If p == expunged, the entry has been deleted, m.dirty != nil, and the entry
// is missing from m.dirty.
//
// Otherwise, the entry is valid and recorded in m.read.m[key] and, if m.dirty
// != nil, in m.dirty[key].
//
// An entry can be deleted by atomic replacement with nil: when m.dirty is
// next created, it will atomically replace nil with expunged and leave
// m.dirty[key] unset.
//
// An entry's associated value can be updated by atomic replacement, provided
// p != expunged. If p == expunged, an entry's associated value can be updated
// only after first setting m.dirty[key] = e so that lookups using the dirty
// map find the entry.
p unsafe.Pointer // *interface{}
}
func newEntry[T any](i T) *entry[T] {
var anyValue any = i
return &entry[T]{p: unsafe.Pointer(&anyValue)}
}
// Load returns the value stored in the map for a key, or nil if no
// value is present.
// The ok result indicates whether value was found in the map.
func (m *Map[K, V]) Load(key K) (value V, ok bool) {
read, _ := m.read.Load().(readOnly[K, V])
e, ok := read.m[key]
if !ok && read.amended {
m.mu.Lock()
// Avoid reporting a spurious miss if m.dirty got promoted while we were
// blocked on m.mu. (If further loads of the same key will not miss, it's
// not worth copying the dirty map for this key.)
read, _ = m.read.Load().(readOnly[K, V])
e, ok = read.m[key]
if !ok && read.amended {
e, ok = m.dirty[key]
// Regardless of whether the entry was present, record a miss: this key
// will take the slow path until the dirty map is promoted to the read
// map.
m.missLocked()
}
m.mu.Unlock()
}
if !ok {
var defaultValue V
return defaultValue, false
}
return e.load()
}
func (e *entry[T]) load() (value T, ok bool) {
p := atomic.LoadPointer(&e.p)
if p == nil || p == expunged {
var defaultValue T
return defaultValue, false
}
return (*(*any)(p)).(T), true
}
// Store sets the value for a key.
func (m *Map[K, V]) Store(key K, value V) {
read, _ := m.read.Load().(readOnly[K, V])
if e, ok := read.m[key]; ok && e.tryStore(&value) {
return
}
m.mu.Lock()
read, _ = m.read.Load().(readOnly[K, V])
if e, ok := read.m[key]; ok {
if e.unexpungeLocked() {
// The entry was previously expunged, which implies that there is a
// non-nil dirty map and this entry is not in it.
m.dirty[key] = e
}
e.storeLocked(&value)
} else if e, ok := m.dirty[key]; ok {
e.storeLocked(&value)
} else {
if !read.amended {
// We're adding the first new key to the dirty map.
// Make sure it is allocated and mark the read-only map as incomplete.
m.dirtyLocked()
m.read.Store(readOnly[K, V]{m: read.m, amended: true})
}
m.dirty[key] = newEntry(value)
}
m.mu.Unlock()
}
// tryStore stores a value if the entry has not been expunged.
//
// If the entry is expunged, tryStore returns false and leaves the entry
// unchanged.
func (e *entry[T]) tryStore(i *T) bool {
for {
p := atomic.LoadPointer(&e.p)
if p == expunged {
return false
}
if atomic.CompareAndSwapPointer(&e.p, p, unsafe.Pointer(i)) {
return true
}
}
}
// unexpungeLocked ensures that the entry is not marked as expunged.
//
// If the entry was previously expunged, it must be added to the dirty map
// before m.mu is unlocked.
func (e *entry[T]) unexpungeLocked() (wasExpunged bool) {
return atomic.CompareAndSwapPointer(&e.p, expunged, nil)
}
// storeLocked unconditionally stores a value to the entry.
//
// The entry must be known not to be expunged.
func (e *entry[T]) storeLocked(i *T) {
atomic.StorePointer(&e.p, unsafe.Pointer(i))
}
// LoadOrStore returns the existing value for the key if present.
// Otherwise, it stores and returns the given value.
// The loaded result is true if the value was loaded, false if stored.
func (m *Map[K, V]) LoadOrStore(key K, value func() V) (actual V, loaded bool) {
// Avoid locking if it's a clean hit.
read, _ := m.read.Load().(readOnly[K, V])
if e, ok := read.m[key]; ok {
actual, loaded, ok := e.tryLoadOrStore(value)
if ok {
return actual, loaded
}
}
m.mu.Lock()
read, _ = m.read.Load().(readOnly[K, V])
if e, ok := read.m[key]; ok {
if e.unexpungeLocked() {
m.dirty[key] = e
}
actual, loaded, _ = e.tryLoadOrStore(value)
} else if e, ok := m.dirty[key]; ok {
actual, loaded, _ = e.tryLoadOrStore(value)
m.missLocked()
} else {
if !read.amended {
// We're adding the first new key to the dirty map.
// Make sure it is allocated and mark the read-only map as incomplete.
m.dirtyLocked()
m.read.Store(readOnly[K, V]{m: read.m, amended: true})
}
v := value()
m.dirty[key] = newEntry(v)
actual, loaded = v, false
}
m.mu.Unlock()
return actual, loaded
}
// tryLoadOrStore atomically loads or stores a value if the entry is not
// expunged.
//
// If the entry is expunged, tryLoadOrStore leaves the entry unchanged and
// returns with ok==false.
func (e *entry[T]) tryLoadOrStore(i func() T) (actual T, loaded, ok bool) {
p := atomic.LoadPointer(&e.p)
if p == expunged {
var defaultValue T
return defaultValue, false, false
}
if p != nil {
return (*(*any)(p)).(T), true, true
}
// Copy the interface after the first load to make this method more amenable
// to escape analysis: if we hit the "load" path or the entry is expunged, we
// shouldn't bother heap-allocating.
ic := i()
for {
if atomic.CompareAndSwapPointer(&e.p, nil, unsafe.Pointer(&ic)) {
return ic, false, true
}
p = atomic.LoadPointer(&e.p)
if p == expunged {
var defaultValue T
return defaultValue, false, false
}
if p != nil {
return (*(*any)(p)).(T), true, true
}
}
}
// LoadAndDelete deletes the value for a key, returning the previous value if any.
// The loaded result reports whether the key was present.
func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
read, _ := m.read.Load().(readOnly[K, V])
e, ok := read.m[key]
if !ok && read.amended {
m.mu.Lock()
read, _ = m.read.Load().(readOnly[K, V])
e, ok = read.m[key]
if !ok && read.amended {
e, ok = m.dirty[key]
delete(m.dirty, key)
// Regardless of whether the entry was present, record a miss: this key
// will take the slow path until the dirty map is promoted to the read
// map.
m.missLocked()
}
m.mu.Unlock()
}
if ok {
return e.delete()
}
var defaultValue V
return defaultValue, false
}
// Delete deletes the value for a key.
func (m *Map[K, V]) Delete(key K) {
m.LoadAndDelete(key)
}
func (e *entry[T]) delete() (value T, ok bool) {
for {
p := atomic.LoadPointer(&e.p)
if p == nil || p == expunged {
var defaultValue T
return defaultValue, false
}
if atomic.CompareAndSwapPointer(&e.p, p, nil) {
return (*(*any)(p)).(T), true
}
}
}
// Range calls f sequentially for each key and value present in the map.
// If f returns false, range stops the iteration.
//
// Range does not necessarily correspond to any consistent snapshot of the Map's
// contents: no key will be visited more than once, but if the value for any key
// is stored or deleted concurrently (including by f), Range may reflect any
// mapping for that key from any point during the Range call. Range does not
// block other methods on the receiver; even f itself may call any method on m.
//
// Range may be O(N) with the number of elements in the map even if f returns
// false after a constant number of calls.
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
// We need to be able to iterate over all of the keys that were already
// present at the start of the call to Range.
// If read.amended is false, then read.m satisfies that property without
// requiring us to hold m.mu for a long time.
read, _ := m.read.Load().(readOnly[K, V])
if read.amended {
// m.dirty contains keys not in read.m. Fortunately, Range is already O(N)
// (assuming the caller does not break out early), so a call to Range
// amortizes an entire copy of the map: we can promote the dirty copy
// immediately!
m.mu.Lock()
read, _ = m.read.Load().(readOnly[K, V])
if read.amended {
read = readOnly[K, V]{m: m.dirty}
m.read.Store(read)
m.dirty = nil
m.misses = 0
}
m.mu.Unlock()
}
for k, e := range read.m {
v, ok := e.load()
if !ok {
continue
}
if !f(k, v) {
break
}
}
}
func (m *Map[K, V]) missLocked() {
m.misses++
if m.misses < len(m.dirty) {
return
}
m.read.Store(readOnly[K, V]{m: m.dirty})
m.dirty = nil
m.misses = 0
}
func (m *Map[K, V]) dirtyLocked() {
if m.dirty != nil {
return
}
read, _ := m.read.Load().(readOnly[K, V])
m.dirty = make(map[K]*entry[V], len(read.m))
for k, e := range read.m {
if !e.tryExpungeLocked() {
m.dirty[k] = e
}
}
}
func (e *entry[T]) tryExpungeLocked() (isExpunged bool) {
p := atomic.LoadPointer(&e.p)
for p == nil {
if atomic.CompareAndSwapPointer(&e.p, nil, expunged) {
return true
}
p = atomic.LoadPointer(&e.p)
}
return p == expunged
}

View file

@ -1,50 +0,0 @@
package common
import (
"crypto/sha256"
"crypto/sha512"
"io"
"os"
)
func SHA224File(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
hash := sha256.New224()
_, err = io.Copy(hash, file)
if err != nil {
return nil, err
}
return hash.Sum(nil), nil
}
func SHA256File(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
hash := sha256.New()
_, err = io.Copy(hash, file)
if err != nil {
return nil, err
}
return hash.Sum(nil), nil
}
func SHA512File(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
hash := sha512.New()
_, err = io.Copy(hash, file)
if err != nil {
return nil, err
}
return hash.Sum(nil), nil
}

View file

@ -1,30 +0,0 @@
package common
import (
"encoding/json"
E "github.com/sagernet/sing/common/exceptions"
)
type JSONMap struct {
json.RawMessage
Data map[string]any
}
func (m *JSONMap) MarshalJSON() ([]byte, error) {
if m == nil {
return []byte("null"), nil
}
return json.Marshal(m.Data)
}
// UnmarshalJSON sets *m to a copy of data.
func (m *JSONMap) UnmarshalJSON(data []byte) error {
if m == nil {
return E.New("JSONMap: UnmarshalJSON on nil pointer")
}
if m.Data == nil {
m.Data = make(map[string]any)
}
return json.Unmarshal(data, &m.Data)
}

View file

@ -1,34 +0,0 @@
package log
import (
"strings"
"github.com/sirupsen/logrus"
)
func init() {
logrus.SetLevel(logrus.TraceLevel)
logrus.StandardLogger().Formatter.(*logrus.TextFormatter).ForceColors = true
logrus.AddHook(new(TaggedHook))
}
func NewLogger(tag string) *logrus.Entry {
return logrus.NewEntry(logrus.StandardLogger()).WithField("tag", tag)
}
type TaggedHook struct{}
func (h *TaggedHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (h *TaggedHook) Fire(entry *logrus.Entry) error {
if tagObj, loaded := entry.Data["tag"]; loaded {
tag := tagObj.(string)
delete(entry.Data, "tag")
entry.Message = strings.ReplaceAll(entry.Message, tag+": ", "")
entry.Message = "[" + tag + "]: " + entry.Message
}
return nil
}

View file

@ -1,31 +0,0 @@
//go:build debug
package log
import (
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/sirupsen/logrus"
)
var basePath string
func init() {
basePath, _ = filepath.Abs(".")
}
func init() {
logrus.StandardLogger().SetReportCaller(true)
logrus.StandardLogger().Formatter.(*logrus.TextFormatter).CallerPrettyfier = func(frame *runtime.Frame) (function string, file string) {
file = frame.File + ":" + strconv.Itoa(frame.Line)
if strings.HasPrefix(file, basePath) {
file = file[len(basePath)+1:]
}
file = " " + file
return
}
}

View file

@ -1,16 +1,7 @@
package metadata
import (
"context"
"net"
)
type Metadata struct {
Protocol string
Source Socksaddr
Destination Socksaddr
}
type TCPConnectionHandler interface {
NewConnection(ctx context.Context, conn net.Conn, metadata Metadata) error
}

View file

@ -45,6 +45,10 @@ type ExtendedConn interface {
net.Conn
}
type TCPConnectionHandler interface {
NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error
}
type NetPacketConn interface {
net.PacketConn
PacketConn

View file

@ -1,37 +1,13 @@
package random
import (
"crypto/rand"
"encoding/binary"
"io"
"sync"
"github.com/sagernet/sing/common"
"lukechampine.com/blake3"
)
var System = &Source{rand.Reader}
var Default = &Source{&SyncReader{Reader: Blake3KeyedHash()}}
func Blake3KeyedHash() io.Reader {
key := make([]byte, 32)
common.Must1(io.ReadFull(System, key))
h := blake3.New(1024, key)
return h.XOF()
}
type SyncReader struct {
io.Reader
sync.Mutex
}
func (r *SyncReader) Read(p []byte) (n int, err error) {
r.Lock()
defer r.Unlock()
return r.Reader.Read(p)
}
const (
rngMax = 1 << 63
rngMask = rngMax - 1
@ -59,3 +35,14 @@ func (s Source) Uint64() uint64 {
func (s Source) Seed(int64) {
}
type SyncReader struct {
io.Reader
sync.Mutex
}
func (r *SyncReader) Read(p []byte) (n int, err error) {
r.Lock()
defer r.Unlock()
return r.Reader.Read(p)
}

View file

@ -1,5 +1,6 @@
package replay
/*
import (
"sync"
"time"
@ -7,44 +8,43 @@ import (
"github.com/seiflotfy/cuckoofilter"
)
func NewCuckoo(interval int64) Filter {
filter := &cuckooFilter{}
filter.interval = interval
return filter
const defaultCapacity = 100000
func NewCuckoo(interval time.Duration) *CuckooFilter {
return &CuckooFilter{
poolA: cuckoo.NewFilter(defaultCapacity),
poolB: cuckoo.NewFilter(defaultCapacity),
lastSwap: time.Now(),
interval: interval,
}
}
type cuckooFilter struct {
lock sync.Mutex
type CuckooFilter struct {
access sync.Mutex
poolA *cuckoo.Filter
poolB *cuckoo.Filter
poolSwap bool
lastSwap int64
interval int64
lastSwap time.Time
interval time.Duration
}
func (filter *cuckooFilter) Check(sum []byte) bool {
const defaultCapacity = 100000
func (f *CuckooFilter) Check(sum []byte) bool {
f.access.Lock()
defer f.access.Unlock()
filter.lock.Lock()
defer filter.lock.Unlock()
now := time.Now()
now := time.Now().Unix()
if filter.lastSwap == 0 {
filter.lastSwap = now
filter.poolA = cuckoo.NewFilter(defaultCapacity)
filter.poolB = cuckoo.NewFilter(defaultCapacity)
}
elapsed := now - filter.lastSwap
if elapsed >= filter.interval {
if filter.poolSwap {
filter.poolA.Reset()
elapsed := now.Sub(f.lastSwap)
if elapsed >= f.interval {
if f.poolSwap {
f.poolA.Reset()
} else {
filter.poolB.Reset()
f.poolB.Reset()
}
filter.poolSwap = !filter.poolSwap
filter.lastSwap = now
f.poolSwap = !f.poolSwap
f.lastSwap = now
}
return filter.poolA.InsertUnique(sum) && filter.poolB.InsertUnique(sum)
return f.poolA.InsertUnique(sum) && f.poolB.InsertUnique(sum)
}
*/

47
common/replay/simple.go Normal file
View file

@ -0,0 +1,47 @@
package replay
import (
"sync"
"time"
)
type SimpleFilter struct {
access sync.Mutex
lastClean time.Time
timeout time.Duration
pool map[string]time.Time
}
func NewSimple(timeout time.Duration) Filter {
return &SimpleFilter{
lastClean: time.Now(),
pool: make(map[string]time.Time),
timeout: timeout,
}
}
func (f *SimpleFilter) Check(salt []byte) bool {
now := time.Now()
saltStr := string(salt)
f.access.Lock()
defer f.access.Unlock()
var exists bool
if now.Sub(f.lastClean) > f.timeout {
for oldSum, added := range f.pool {
if now.Sub(added) > f.timeout {
delete(f.pool, oldSum)
}
}
_, exists = f.pool[saltStr]
f.lastClean = now
} else {
if added, loaded := f.pool[saltStr]; loaded && now.Sub(added) <= f.timeout {
exists = true
}
}
if !exists {
f.pool[saltStr] = now
}
return !exists
}

View file

@ -1,27 +0,0 @@
package rw
import (
"io"
"runtime"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
)
func WriteVC(conn io.Writer, data ...[]byte) (int, error) {
if fd, err := common.TryFileDescriptor(conn); err == nil {
return WriteV(fd, data...)
}
var bufLen int
for _, dataItem := range data {
bufLen += len(dataItem)
}
_buffer := buf.Make(bufLen)
defer runtime.KeepAlive(_buffer)
buffer := common.Dup(_buffer)
var bufN int
for _, dataItem := range data {
bufN += copy(buffer[bufN:], dataItem)
}
return conn.Write(buffer)
}

View file

@ -7,16 +7,6 @@ import (
"github.com/sagernet/sing/common"
)
func After(task func() error, after func() error) func() error {
return func() error {
err := task()
if err != nil {
return err
}
return after()
}
}
func Run(ctx context.Context, tasks ...func() error) error {
ctx, cancel := context.WithCancel(ctx)
wg := &sync.WaitGroup{}

View file

@ -1,95 +0,0 @@
package trieset
import (
"bytes"
"errors"
"sort"
"strings"
"github.com/sagernet/sing/common"
)
// ErrInvalidDomain means insert domain is invalid
var ErrInvalidDomain = errors.New("invalid domain")
func reverse(s string) []byte {
bytes := []byte(s)
for i2, j := 0, len(bytes)-1; i2 < j; i2, j = i2+1, j-1 {
bytes[i2], bytes[j] = bytes[j], bytes[i2]
}
return bytes
}
type DomainSet struct {
set *Set
}
// Has query for a key and return whether it presents in the Set.
func (ds *DomainSet) Has(domain string) bool {
return ds.has(reverse(domain), 0, 0)
}
func (ds *DomainSet) has(key []byte, nodeId, bmIdx int) bool {
for i := 0; i < len(key); i++ {
c := key[i]
Outer:
for ; ; bmIdx++ {
if getBit(ds.set.labelBitmap, bmIdx) != 0 {
// no more labels in this node
return false
}
switch char := ds.set.labels[bmIdx-nodeId]; char {
case '.':
nodeId := countZeros(ds.set.labelBitmap, ds.set.ranks, bmIdx+1)
if getBit(ds.set.leaves, nodeId) != 0 && c == '.' {
return true
} else if char == c {
break Outer
}
case c:
break Outer
case '*':
idx := bytes.IndexByte(key[i:], '.')
nodeId := countZeros(ds.set.labelBitmap, ds.set.ranks, bmIdx+1)
if idx == -1 {
return getBit(ds.set.leaves, nodeId) != 0
}
bmIdx := selectIthOne(ds.set.labelBitmap, ds.set.ranks, ds.set.selects, nodeId-1) + 1
if ds.has(key[i+idx:], nodeId, bmIdx) {
return true
}
}
}
// go to next level
nodeId = countZeros(ds.set.labelBitmap, ds.set.ranks, bmIdx+1)
bmIdx = selectIthOne(ds.set.labelBitmap, ds.set.ranks, ds.set.selects, nodeId-1) + 1
}
return getBit(ds.set.leaves, nodeId) != 0
}
func New(domains []string) (*DomainSet, error) {
list := make([]string, 0, len(domains))
for _, domain := range domains {
if domain == "" || domain[len(domain)-1] == '.' || strings.HasPrefix(domain, "regexp:") {
continue
}
domain = string(reverse(domain))
if strings.HasSuffix(domain, "+") {
list = append(list, domain[:len(domain)-1])
list = append(list, domain[:len(domain)-2])
} else {
list = append(list, domain)
}
}
sort.Strings(list)
list = common.Uniq(list)
return &DomainSet{NewSet(list)}, nil
}

View file

@ -1,171 +0,0 @@
// Package trieset provides several succinct data types.
// https://github.com/openacid/succinct
package trieset
import (
"github.com/openacid/low/bitmap"
)
// Set is a succinct, sorted and static string set impl with compacted trie as
// storage. The space cost is about half lower than the original data.
//
// Implementation
//
// It stores sorted strings in a compacted trie(AKA prefix tree).
// A trie node has at most 256 outgoing labels.
// A label is just a single byte.
// E.g., [ab, abc, abcd, axy, buv] is represented with a trie like the following:
// (Numbers are node id)
//
// ^ -a-> 1 -b-> 3 $
// | | `c-> 6 $
// | | `d-> 9 $
// | `x-> 4 -y-> 7 $
// `b-> 2 -u-> 5 -v-> 8 $
//
// Internally it uses a packed []byte and a bitmap with `len([]byte)` bits to
// describe the outgoing labels of a node,:
// ^: ab 00
// 1: bx 00
// 2: u 0
// 3: c 0
// 4: y 0
// 5: v 0
// 6: d 0
// 7: ø
// 8: ø
// 9: ø
//
// In storage it packs labels together and bitmaps joined with separator `1`:
// labels(ignore space): "ab bx u c y v d"
// label bitmap: 0010010101010101111
//
// In this way every node has a `0` pointing to it(except the root node)
// and has a corresponding `1` for it:
// .-----.
// .--. | .---|-.
// |.-|--. | | .-|-|.
// || ↓ ↓ | | | ↓ ↓↓
// labels(ignore space): ab bx u c y v d øøø
// label bitmap: 0010010101010101111
// node-id: 0 1 2 3 4 5 6 789
// || | ↑ ↑ ↑ | ↑
// || `-|-|-' `---'
// |`---|-'
// `----'
// To walk from a parent node along a label to a child node, count the number of
// `0` upto the bit the label position, then find where the the corresponding
// `1` is:
// childNodeId = select1(rank0(i))
// In our impl, it is:
// nodeId = countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
// bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId-1) + 1
//
// Finally leaf nodes are indicated by another bitmap `leaves`, in which a `1`
// at i-th bit indicates the i-th node is a leaf:
// leaves: 0001001111
type Set struct {
leaves, labelBitmap []uint64
labels []byte
ranks, selects []int32
}
// NewSet creates a new *Set struct, from a slice of sorted strings.
func NewSet(keys []string) *Set {
ss := &Set{}
lIdx := 0
type qElt struct{ s, e, col int }
queue := []qElt{{0, len(keys), 0}}
for i := 0; i < len(queue); i++ {
elt := queue[i]
if elt.col == len(keys[elt.s]) {
// a leaf node
elt.s++
setBit(&ss.leaves, i, 1)
}
for j := elt.s; j < elt.e; {
frm := j
for ; j < elt.e && keys[j][elt.col] == keys[frm][elt.col]; j++ {
}
queue = append(queue, qElt{frm, j, elt.col + 1})
ss.labels = append(ss.labels, keys[frm][elt.col])
setBit(&ss.labelBitmap, lIdx, 0)
lIdx++
}
setBit(&ss.labelBitmap, lIdx, 1)
lIdx++
}
ss.init()
return ss
}
// Has query for a key and return whether it presents in the Set.
func (ss *Set) Has(key string) bool {
nodeId, bmIdx := 0, 0
for i := 0; i < len(key); i++ {
c := key[i]
for ; ; bmIdx++ {
if getBit(ss.labelBitmap, bmIdx) != 0 {
// no more labels in this node
return false
}
if ss.labels[bmIdx-nodeId] == c {
break
}
}
// go to next level
nodeId = countZeros(ss.labelBitmap, ss.ranks, bmIdx+1)
bmIdx = selectIthOne(ss.labelBitmap, ss.ranks, ss.selects, nodeId-1) + 1
}
return getBit(ss.leaves, nodeId) != 0
}
func setBit(bm *[]uint64, i int, v int) {
for i>>6 >= len(*bm) {
*bm = append(*bm, 0)
}
(*bm)[i>>6] |= uint64(v) << uint(i&63)
}
func getBit(bm []uint64, i int) uint64 {
return bm[i>>6] & (1 << uint(i&63))
}
// init builds pre-calculated cache to speed up rank() and select()
func (ss *Set) init() {
ss.selects, ss.ranks = bitmap.IndexSelect32R64(ss.labelBitmap)
}
// countZeros counts the number of "0" in a bitmap before the i-th bit(excluding
// the i-th bit) on behalf of rank index.
// E.g.:
// countZeros("010010", 4) == 3
// // 012345
func countZeros(bm []uint64, ranks []int32, i int) int {
a, _ := bitmap.Rank64(bm, ranks, int32(i))
return i - int(a)
}
// selectIthOne returns the index of the i-th "1" in a bitmap, on behalf of rank
// and select indexes.
// E.g.:
// selectIthOne("010010", 1) == 4
// // 012345
func selectIthOne(bm []uint64, ranks, selects []int32, i int) int {
a, _ := bitmap.Select32R64(bm, selects, ranks, int32(i))
return int(a)
}

View file

@ -1,422 +0,0 @@
package system
import (
"context"
"net"
"net/netip"
"os"
"runtime"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/cache"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/log"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/rw"
"github.com/sagernet/sing/common/tun"
"github.com/sagernet/sing/common/udpnat"
"gvisor.dev/gvisor/pkg/tcpip"
tcpipBuffer "gvisor.dev/gvisor/pkg/tcpip/buffer"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/header/parse"
"gvisor.dev/gvisor/pkg/tcpip/stack"
)
var logger = log.NewLogger("tun <system>")
type Stack struct {
tunFd uintptr
tunMtu int
inetAddress netip.Prefix
inet6Address netip.Prefix
handler tun.Handler
tunFile *os.File
tcpForwarder *net.TCPListener
tcpPort uint16
tcpSessions *cache.LruCache[netip.AddrPort, netip.AddrPort]
udpNat *udpnat.Service[netip.AddrPort]
}
func New(tunFd uintptr, tunMtu int, inetAddress netip.Prefix, inet6Address netip.Prefix, packetTimeout int64, handler tun.Handler) tun.Stack {
return &Stack{
tunFd: tunFd,
tunMtu: tunMtu,
inetAddress: inetAddress,
inet6Address: inet6Address,
handler: handler,
tunFile: os.NewFile(tunFd, "tun"),
tcpSessions: cache.New(
cache.WithAge[netip.AddrPort, netip.AddrPort](packetTimeout),
cache.WithUpdateAgeOnGet[netip.AddrPort, netip.AddrPort](),
),
udpNat: udpnat.New[netip.AddrPort](packetTimeout, handler),
}
}
func (t *Stack) Start() error {
var network string
var address net.TCPAddr
if !t.inet6Address.IsValid() {
network = "tcp4"
address.IP = t.inetAddress.Addr().AsSlice()
} else {
network = "tcp"
address.IP = net.IPv6zero
}
tcpListener, err := net.ListenTCP(network, &address)
if err != nil {
return err
}
t.tcpForwarder = tcpListener
go t.tcpLoop()
go t.tunLoop()
return nil
}
func (t *Stack) Close() error {
t.tcpForwarder.Close()
t.tunFile.Close()
return nil
}
func (t *Stack) tunLoop() {
_buffer := buf.Make(t.tunMtu)
defer runtime.KeepAlive(_buffer)
buffer := common.Dup(_buffer)
for {
n, err := t.tunFile.Read(buffer)
if err != nil {
t.handler.HandleError(err)
break
}
packet := buffer[:n]
t.deliverPacket(packet)
}
}
func (t *Stack) deliverPacket(packet []byte) {
var err error
switch header.IPVersion(packet) {
case header.IPv4Version:
ipHdr := header.IPv4(packet)
switch ipHdr.TransportProtocol() {
case header.TCPProtocolNumber:
err = t.processIPv4TCP(ipHdr, ipHdr.Payload())
case header.UDPProtocolNumber:
err = t.processIPv4UDP(ipHdr, ipHdr.Payload())
default:
_, err = t.tunFile.Write(packet)
}
case header.IPv6Version:
pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
Data: tcpipBuffer.View(packet).ToVectorisedView(),
})
proto, _, _, _, ok := parse.IPv6(pkt)
pkt.DecRef()
if !ok {
return
}
ipHdr := header.IPv6(packet)
switch proto {
case header.TCPProtocolNumber:
err = t.processIPv6TCP(ipHdr, ipHdr.Payload())
case header.UDPProtocolNumber:
err = t.processIPv6UDP(ipHdr, ipHdr.Payload())
default:
_, err = t.tunFile.Write(packet)
}
}
if err != nil {
t.handler.HandleError(err)
}
}
func (t *Stack) processIPv4TCP(ipHdr header.IPv4, tcpHdr header.TCP) error {
sourceAddress := ipHdr.SourceAddress()
destinationAddress := ipHdr.DestinationAddress()
sourcePort := tcpHdr.SourcePort()
destinationPort := tcpHdr.DestinationPort()
logger.Trace(sourceAddress, ":", sourcePort, " => ", destinationAddress, ":", destinationPort)
if sourcePort != t.tcpPort {
key := M.AddrPortFrom(net.IP(destinationAddress), sourcePort)
t.tcpSessions.LoadOrStore(key, func() netip.AddrPort {
return M.AddrPortFrom(net.IP(sourceAddress), destinationPort)
})
ipHdr.SetSourceAddress(destinationAddress)
ipHdr.SetDestinationAddress(tcpip.Address(t.inetAddress.Addr().AsSlice()))
tcpHdr.SetDestinationPort(t.tcpPort)
} else {
key := M.AddrPortFrom(net.IP(destinationAddress), destinationPort)
session, loaded := t.tcpSessions.Load(key)
if !loaded {
return E.New("unknown tcp session with source port ", destinationPort, " to destination address ", destinationAddress)
}
ipHdr.SetSourceAddress(destinationAddress)
tcpHdr.SetSourcePort(session.Port())
ipHdr.SetDestinationAddress(tcpip.Address(session.Addr().AsSlice()))
}
ipHdr.SetChecksum(0)
ipHdr.SetChecksum(^ipHdr.CalculateChecksum())
tcpHdr.SetChecksum(0)
tcpHdr.SetChecksum(^tcpHdr.CalculateChecksum(header.ChecksumCombine(
header.PseudoHeaderChecksum(header.TCPProtocolNumber, ipHdr.SourceAddress(), ipHdr.DestinationAddress(), uint16(len(tcpHdr))),
header.Checksum(tcpHdr.Payload(), 0),
)))
_, err := t.tunFile.Write(ipHdr)
return err
}
func (t *Stack) processIPv6TCP(ipHdr header.IPv6, tcpHdr header.TCP) error {
sourceAddress := ipHdr.SourceAddress()
destinationAddress := ipHdr.DestinationAddress()
sourcePort := tcpHdr.SourcePort()
destinationPort := tcpHdr.DestinationPort()
if sourcePort != t.tcpPort {
key := M.AddrPortFrom(net.IP(destinationAddress), sourcePort)
t.tcpSessions.LoadOrStore(key, func() netip.AddrPort {
return M.AddrPortFrom(net.IP(sourceAddress), destinationPort)
})
ipHdr.SetSourceAddress(destinationAddress)
ipHdr.SetDestinationAddress(tcpip.Address(t.inet6Address.Addr().AsSlice()))
tcpHdr.SetDestinationPort(t.tcpPort)
} else {
key := M.AddrPortFrom(net.IP(destinationAddress), destinationPort)
session, loaded := t.tcpSessions.Load(key)
if !loaded {
return E.New("unknown tcp session with source port ", destinationPort, " to destination address ", destinationAddress)
}
ipHdr.SetSourceAddress(destinationAddress)
tcpHdr.SetSourcePort(session.Port())
ipHdr.SetDestinationAddress(tcpip.Address(session.Addr().AsSlice()))
}
tcpHdr.SetChecksum(0)
tcpHdr.SetChecksum(^tcpHdr.CalculateChecksum(header.ChecksumCombine(
header.PseudoHeaderChecksum(header.TCPProtocolNumber, ipHdr.SourceAddress(), ipHdr.DestinationAddress(), uint16(len(tcpHdr))),
header.Checksum(tcpHdr.Payload(), 0),
)))
_, err := t.tunFile.Write(ipHdr)
return err
}
func (t *Stack) tcpLoop() {
for {
logger.Trace("tcp start")
tcpConn, err := t.tcpForwarder.AcceptTCP()
logger.Trace("tcp accept")
if err != nil {
t.handler.HandleError(err)
return
}
key := M.AddrPortFromNet(tcpConn.RemoteAddr())
session, ok := t.tcpSessions.Load(key)
if !ok {
tcpConn.Close()
logger.Warn("dropped unknown tcp session from ", key)
continue
}
var metadata M.Metadata
metadata.Protocol = "tun"
metadata.Source.Addr = session.Addr()
metadata.Source.Port = key.Port()
metadata.Destination.Addr = key.Addr()
metadata.Destination.Port = session.Port()
go t.processConn(tcpConn, metadata, key)
}
}
func (t *Stack) processConn(conn *net.TCPConn, metadata M.Metadata, key netip.AddrPort) {
err := t.handler.NewConnection(context.Background(), conn, metadata)
if err != nil {
t.handler.HandleError(err)
}
t.tcpSessions.Delete(key)
}
func (t *Stack) processIPv4UDP(ipHdr header.IPv4, hdr header.UDP) error {
var metadata M.Metadata
metadata.Protocol = "tun"
metadata.Source = M.SocksaddrFrom(net.IP(ipHdr.SourceAddress()), hdr.SourcePort())
metadata.Source = M.SocksaddrFrom(net.IP(ipHdr.DestinationAddress()), hdr.DestinationPort())
headerCache := buf.New()
_, err := headerCache.Write(ipHdr[:ipHdr.HeaderLength()+header.UDPMinimumSize])
if err != nil {
return err
}
logger.Trace("[UDP] ", metadata.Source, "=>", metadata.Destination)
t.udpNat.NewPacket(context.Background(), metadata.Source.AddrPort(), func() N.PacketWriter {
return &inetPacketWriter{
tun: t,
headerCache: headerCache,
sourceAddress: ipHdr.SourceAddress(),
destination: ipHdr.DestinationAddress(),
destinationPort: hdr.DestinationPort(),
}
}, buf.With(hdr), metadata)
return nil
}
type inetPacketWriter struct {
tun *Stack
headerCache *buf.Buffer
sourceAddress tcpip.Address
destination tcpip.Address
destinationPort uint16
}
func (w *inetPacketWriter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
index := w.headerCache.Len()
newHeader := w.headerCache.Extend(w.headerCache.Len())
copy(newHeader, w.headerCache.Bytes())
w.headerCache.Advance(index)
defer func() {
w.headerCache.FullReset()
w.headerCache.Resize(0, index)
}()
var newSourceAddress tcpip.Address
var newSourcePort uint16
if destination.IsValid() {
newSourceAddress = tcpip.Address(destination.Addr.AsSlice())
newSourcePort = destination.Port
} else {
newSourceAddress = w.destination
newSourcePort = w.destinationPort
}
newIpHdr := header.IPv4(newHeader)
newIpHdr.SetSourceAddress(newSourceAddress)
newIpHdr.SetTotalLength(uint16(int(w.headerCache.Len()) + buffer.Len()))
newIpHdr.SetChecksum(0)
newIpHdr.SetChecksum(^newIpHdr.CalculateChecksum())
udpHdr := header.UDP(w.headerCache.From(w.headerCache.Len() - header.UDPMinimumSize))
udpHdr.SetSourcePort(newSourcePort)
udpHdr.SetLength(uint16(header.UDPMinimumSize + buffer.Len()))
udpHdr.SetChecksum(0)
udpHdr.SetChecksum(^udpHdr.CalculateChecksum(header.Checksum(buffer.Bytes(), header.PseudoHeaderChecksum(header.UDPProtocolNumber, newSourceAddress, w.sourceAddress, uint16(header.UDPMinimumSize+buffer.Len())))))
replyVV := tcpipBuffer.VectorisedView{}
replyVV.AppendView(newHeader)
replyVV.AppendView(buffer.Bytes())
return w.tun.WriteVV(replyVV)
}
func (w *inetPacketWriter) Close() error {
w.headerCache.Release()
return nil
}
func (t *Stack) processIPv6UDP(ipHdr header.IPv6, hdr header.UDP) error {
var metadata M.Metadata
metadata.Protocol = "tun"
metadata.Source = M.SocksaddrFrom(net.IP(ipHdr.SourceAddress()), hdr.SourcePort())
metadata.Destination = M.SocksaddrFrom(net.IP(ipHdr.DestinationAddress()), hdr.DestinationPort())
headerCache := buf.New()
_, err := headerCache.Write(ipHdr[:uint16(len(ipHdr))-ipHdr.PayloadLength()+header.UDPMinimumSize])
if err != nil {
return err
}
t.udpNat.NewPacket(context.Background(), metadata.Source.AddrPort(), func() N.PacketWriter {
return &inet6PacketWriter{
tun: t,
headerCache: headerCache,
sourceAddress: ipHdr.SourceAddress(),
destination: ipHdr.DestinationAddress(),
destinationPort: hdr.DestinationPort(),
}
}, buf.With(hdr), metadata)
return nil
}
type inet6PacketWriter struct {
tun *Stack
headerCache *buf.Buffer
sourceAddress tcpip.Address
destination tcpip.Address
destinationPort uint16
}
func (w *inet6PacketWriter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
index := w.headerCache.Len()
newHeader := w.headerCache.Extend(w.headerCache.Len())
copy(newHeader, w.headerCache.Bytes())
w.headerCache.Advance(index)
defer func() {
w.headerCache.FullReset()
w.headerCache.Resize(0, index)
}()
var newSourceAddress tcpip.Address
var newSourcePort uint16
if destination.IsValid() {
newSourceAddress = tcpip.Address(destination.Addr.AsSlice())
newSourcePort = destination.Port
} else {
newSourceAddress = w.destination
newSourcePort = w.destinationPort
}
newIpHdr := header.IPv6(newHeader)
newIpHdr.SetSourceAddress(newSourceAddress)
newIpHdr.SetPayloadLength(uint16(header.UDPMinimumSize + buffer.Len()))
udpHdr := header.UDP(w.headerCache.From(w.headerCache.Len() - header.UDPMinimumSize))
udpHdr.SetSourcePort(newSourcePort)
udpHdr.SetLength(uint16(header.UDPMinimumSize + buffer.Len()))
udpHdr.SetChecksum(0)
udpHdr.SetChecksum(^udpHdr.CalculateChecksum(header.Checksum(buffer.Bytes(), header.PseudoHeaderChecksum(header.UDPProtocolNumber, newSourceAddress, w.sourceAddress, uint16(header.UDPMinimumSize+buffer.Len())))))
replyVV := tcpipBuffer.VectorisedView{}
replyVV.AppendView(newHeader)
replyVV.AppendView(buffer.Bytes())
return w.tun.WriteVV(replyVV)
}
func (t *Stack) WriteVV(vv tcpipBuffer.VectorisedView) error {
data := make([][]byte, 0, len(vv.Views()))
for _, view := range vv.Views() {
data = append(data, view)
}
return common.Error(rw.WriteV(t.tunFd, data...))
}
func (w *inet6PacketWriter) Close() error {
w.headerCache.Release()
return nil
}
type tcpipError struct {
Err tcpip.Error
}
func (e *tcpipError) Error() string {
return e.Err.String()
}

View file

@ -1,18 +0,0 @@
package tun
import (
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
type Handler interface {
M.TCPConnectionHandler
N.UDPConnectionHandler
E.Handler
}
type Stack interface {
Start() error
Close() error
}

View file

@ -1,171 +0,0 @@
package tun
/*
import (
"bytes"
"net"
"syscall"
"unsafe"
E "github.com/sagernet/sing/common/exceptions"
"golang.org/x/sys/unix"
)
const ifReqSize = unix.IFNAMSIZ + 64
func (t *Interface) Name() (string, error) {
if t.tunName != "" {
return t.tunName, nil
}
var ifr [ifReqSize]byte
_, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(t.tunFd), uintptr(unix.TUNGETIFF), uintptr(unsafe.Pointer(&ifr[0])))
if errno != 0 {
return "", errno
}
name := ifr[:]
if i := bytes.IndexByte(name, 0); i != -1 {
name = name[:i]
}
t.tunName = string(name)
return t.tunName, nil
}
func (t *Interface) MTU() (int, error) {
name, err := t.Name()
if err != nil {
return 0, err
}
fd, err := unix.Socket(
unix.AF_INET,
unix.SOCK_DGRAM,
0,
)
if err != nil {
return 0, err
}
defer unix.Close(fd)
var ifr [ifReqSize]byte
copy(ifr[:], name)
_, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(unix.SIOCGIFMTU), uintptr(unsafe.Pointer(&ifr[0])))
if errno != 0 {
return 0, errno
}
return int(*(*int32)(unsafe.Pointer(&ifr[unix.IFNAMSIZ]))), nil
}
func (t *Interface) SetMTU(mtu int) error {
name, err := t.Name()
if err != nil {
return err
}
fd, err := unix.Socket(
unix.AF_INET,
unix.SOCK_DGRAM,
0,
)
if err != nil {
return err
}
defer unix.Close(fd)
var ifr [ifReqSize]byte
copy(ifr[:], name)
*(*uint32)(unsafe.Pointer(&ifr[unix.IFNAMSIZ])) = uint32(mtu)
_, _, errno := unix.Syscall(
unix.SYS_IOCTL,
uintptr(fd),
uintptr(unix.SIOCSIFMTU),
uintptr(unsafe.Pointer(&ifr[0])),
)
if errno != 0 {
return errno
}
return nil
}
func (t *Interface) SetAddress() error {
name, err := t.Name()
if err != nil {
return err
}
fd, err := unix.Socket(
unix.AF_INET,
unix.SOCK_DGRAM,
0,
)
if err != nil {
return err
}
defer unix.Close(fd)
ifreq, err := unix.NewIfreq(name)
if err != nil {
return E.Cause(err, "failed to create ifreq for name ", name)
}
ifreq.SetInet4Addr(t.inetAddress.Addr().AsSlice())
err = unix.IoctlIfreq(fd, syscall.SIOCSIFADDR, ifreq)
if err == nil {
ifreq, _ = unix.NewIfreq(name)
ifreq.SetInet4Addr(net.CIDRMask(t.inetAddress.Bits(), 32))
err = unix.IoctlIfreq(fd, syscall.SIOCSIFNETMASK, ifreq)
}
if err != nil {
return E.Cause(err, "failed to set ipv4 address on ", name)
}
if t.inet6Address.IsValid() {
ifreq, _ = unix.NewIfreq(name)
err = unix.IoctlIfreq(fd, syscall.SIOCGIFINDEX, ifreq)
if err != nil {
return E.Cause(err, "failed to get interface index for ", name)
}
ifreq6 := in6_ifreq{
ifr6_addr: in6_addr{
addr: t.inet6Address.Addr().As16(),
},
ifr6_prefixlen: uint32(t.inet6Address.Bits()),
ifr6_ifindex: ifreq.Uint32(),
}
fd6, err := unix.Socket(
unix.AF_INET6,
unix.SOCK_DGRAM,
0,
)
if err != nil {
return err
}
defer unix.Close(fd6)
if _, _, errno := syscall.Syscall(
syscall.SYS_IOCTL,
uintptr(fd6),
uintptr(syscall.SIOCSIFADDR),
uintptr(unsafe.Pointer(&ifreq6)),
); errno != 0 {
return E.Cause(errno, "failed to set ipv6 address on ", name)
}
}
ifreq, _ = unix.NewIfreq(name)
err = unix.IoctlIfreq(fd, syscall.SIOCGIFFLAGS, ifreq)
if err == nil {
ifreq.SetUint16(ifreq.Uint16() | syscall.IFF_UP | syscall.IFF_RUNNING)
err = unix.IoctlIfreq(fd, syscall.SIOCSIFFLAGS, ifreq)
}
if err != nil {
return E.Cause(err, "failed to bring tun device up")
}
return nil
}
type in6_addr struct {
addr [16]byte
}
type in6_ifreq struct {
ifr6_addr in6_addr
ifr6_prefixlen uint32
ifr6_ifindex uint32
}
*/

View file

@ -36,8 +36,13 @@ func (c *ServerConn) Write(b []byte) (n int, err error) {
return c.inputWriter.Write(b)
}
type pipeAddr struct{}
func (pipeAddr) Network() string { return "pipe" }
func (pipeAddr) String() string { return "pipe" }
func (c *ServerConn) RemoteAddr() net.Addr {
return &common.DummyAddr{}
return pipeAddr{}
}
func (c *ServerConn) loopInput() {

View file

@ -1,41 +0,0 @@
package uot
import (
"net"
"runtime"
"testing"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"golang.org/x/net/dns/dnsmessage"
)
func TestServerConn(t *testing.T) {
udpConn, err := net.ListenUDP("udp", nil)
common.Must(err)
serverConn := NewServerConn(udpConn)
defer serverConn.Close()
clientConn := NewClientConn(serverConn)
message := &dnsmessage.Message{}
message.Header.ID = 1
message.Header.RecursionDesired = true
message.Questions = append(message.Questions, dnsmessage.Question{
Name: dnsmessage.MustNewName("google.com."),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
})
packet, err := message.Pack()
common.Must(err)
common.Must1(clientConn.WriteTo(packet, &net.UDPAddr{
IP: net.IPv4(8, 8, 8, 8),
Port: 53,
}))
_buffer := buf.StackNew()
defer runtime.KeepAlive(_buffer)
buffer := common.Dup(_buffer)
common.Must2(buffer.ReadPacketFrom(clientConn))
common.Must(message.Unpack(buffer.Bytes()))
for _, answer := range message.Answers {
t.Log("got answer :", answer.Body)
}
}

View file

@ -1,6 +0,0 @@
package sing
const (
Version = "v0.0.0-alpha.1"
VersionStr = "sing " + Version
)

View file

@ -1,12 +0,0 @@
//go:build debug
package sing
import (
"net/http"
_ "net/http/pprof"
)
func init() {
go http.ListenAndServe(":8964", nil)
}

58
go.mod
View file

@ -2,60 +2,4 @@ module github.com/sagernet/sing
go 1.18
require (
github.com/cloudflare/cloudflare-go v0.39.0
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d
github.com/go-acme/lego/v4 v4.6.0
github.com/go-resty/resty/v2 v2.7.0
github.com/klauspost/compress v1.15.4
github.com/lucas-clemente/quic-go v0.27.0
github.com/openacid/low v0.1.21
github.com/oschwald/geoip2-golang v1.7.0
github.com/refraction-networking/utls v1.1.0
github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb
github.com/sirupsen/logrus v1.8.1
github.com/spf13/cobra v1.4.0
github.com/u-root/u-root v0.8.1-0.20220504042106-94cc250573fb
github.com/ulikunitz/xz v0.5.10
github.com/v2fly/v2ray-core/v5 v5.0.6
github.com/vishvananda/netlink v1.2.0-beta
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a
golang.zx2c4.com/wireguard v0.0.0-20220407013110-ef5c587f782d
google.golang.org/protobuf v1.28.0
gvisor.dev/gvisor v0.0.0-20220428010907-8082b77961ba
lukechampine.com/blake3 v1.1.7
)
require (
github.com/adrg/xdg v0.4.0 // indirect
github.com/cenkalti/backoff/v4 v4.1.1 // indirect
github.com/cheekybits/genny v1.0.0 // indirect
github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140 // indirect
github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/btree v1.0.1 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/klauspost/cpuid/v2 v2.0.12 // indirect
github.com/marten-seemann/qpack v0.2.1 // indirect
github.com/marten-seemann/qtls-go1-16 v0.1.5 // indirect
github.com/marten-seemann/qtls-go1-17 v0.1.1 // indirect
github.com/marten-seemann/qtls-go1-18 v0.1.1 // indirect
github.com/miekg/dns v1.1.48 // indirect
github.com/nxadm/tail v1.4.8 // indirect
github.com/onsi/ginkgo v1.16.4 // indirect
github.com/oschwald/maxminddb-golang v1.9.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20220411224347-583f2d630306 // indirect
golang.org/x/tools v0.1.11-0.20220325154526-54af36eca237 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/square/go-jose.v2 v2.6.0 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
)
require golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a

892
go.sum
View file

@ -1,894 +1,2 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To=
cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4=
cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M=
cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE=
cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc=
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk=
cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk=
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw=
cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA=
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos=
cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk=
dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU=
dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4=
dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU=
git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg=
github.com/Azure/azure-sdk-for-go v32.4.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc=
github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24=
github.com/Azure/go-autorest/autorest v0.11.17/go.mod h1:eipySxLmqSyC5s5k1CLupqet0PSENBEDP93LQ9a8QYw=
github.com/Azure/go-autorest/autorest v0.11.19/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA=
github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A=
github.com/Azure/go-autorest/autorest/adal v0.9.11/go.mod h1:nBKAnTomx8gDtl+3ZCJv2v0KACFHWTB2drffI1B68Pk=
github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M=
github.com/Azure/go-autorest/autorest/azure/auth v0.5.8/go.mod h1:kxyKZTSfKh8OVFWPAgOgQ/frrJgeYQJPyR5fLFmXko4=
github.com/Azure/go-autorest/autorest/azure/cli v0.4.2/go.mod h1:7qkJkT+j6b+hIpzMOwPChJhTqS8VbsqqgULzMNRugoM=
github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74=
github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k=
github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcPR4o9jEImooCeWJcYV/zLE=
github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E=
github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8=
github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8=
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/OpenDNS/vegadns2client v0.0.0-20180418235048-a3fa4a771d87/go.mod h1:iGLljf5n9GjT6kc0HBvyI1nOKnGQbNB66VzSNbK5iks=
github.com/adrg/xdg v0.4.0 h1:RzRqFcjH4nE5C6oTAxhBtoE2IRyjBSa62SCbyPidvls=
github.com/adrg/xdg v0.4.0/go.mod h1:N6ag73EX4wyxeaoeHctc1mas01KZgsj5tYiAIwqJE/E=
github.com/akamai/AkamaiOPEN-edgegrid-golang v1.1.1/go.mod h1:kX6YddBkXqqywAe8c9LyvgTCyFuZCTMF4cRPQhc3Fy8=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/aliyun/alibaba-cloud-sdk-go v1.61.1183/go.mod h1:pUKYbK5JQ+1Dfxk80P0qxGqe5dkxDoabbZS7zOcouyA=
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/aws/aws-sdk-go v1.39.0/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g=
github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s=
github.com/c-bata/go-prompt v0.2.5/go.mod h1:vFnjEGDIIA/Lib7giyE4E9c50Lvl8j0S+7FVlAwDAVw=
github.com/cenkalti/backoff/v4 v4.1.1 h1:G2HAfAmvm/GcKan2oOQpBXOd2tT2G57ZnZGWa1PxPBQ=
github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cheekybits/genny v1.0.0 h1:uGGa4nei+j20rOSeDeP5Of12XVm7TGUd4dJA9RDitfE=
github.com/cheekybits/genny v1.0.0/go.mod h1:+tQajlRqAUrPI7DOSpB0XAqZYtQakVtB7wXkRAgjxjQ=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudflare/cloudflare-go v0.20.0/go.mod h1:sPWL/lIC6biLEdyGZwBQ1rGQKF1FhM7N60fuNiFdYTI=
github.com/cloudflare/cloudflare-go v0.39.0 h1:xXTTTBtbYDEsiltOMgcSuReDmnJEBq0CbFPtbrIkJkc=
github.com/cloudflare/cloudflare-go v0.39.0/go.mod h1:zwDLiwQbvubMqmIVbEuFDoiXE0dED/D4DFyT2yhNWf4=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpu/goacmedns v0.1.1/go.mod h1:MuaouqEhPAHxsbqjgnck5zeghuwBP1dLnPoobeGqugQ=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cyberdelia/templates v0.0.0-20141128023046-ca7fffd4298c/go.mod h1:GyV+0YP4qX0UQ7r2MoYZ+AvYDp12OF5yg4q8rGnyNh4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/deepmap/oapi-codegen v1.6.1/go.mod h1:ryDa9AgbELGeB+YEXE1dR53yAjHwFvE9iAUlWl9Al3M=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d h1:CPqTNIigGweVPT4CYb+OO2E6XyRKFOmvTHwWRLgCAlE=
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d/go.mod h1:QX5ZVULjAfZJux/W62Y91HvCh9hyW6enAwcrrv/sLj0=
github.com/dgryski/go-metro v0.0.0-20200812162917-85c65e2d0165/go.mod h1:c9O8+fpSOX1DM8cPNSkX/qsBWdkD4yd2dpciOWQjpBw=
github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140 h1:y7y0Oa6UawqTFPCDw9JG6pdKt4F9pAhHv0B7FMGaGD0=
github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140/go.mod h1:c9O8+fpSOX1DM8cPNSkX/qsBWdkD4yd2dpciOWQjpBw=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8=
github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE=
github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E=
github.com/dnsimple/dnsimple-go v0.70.1/go.mod h1:F9WHww9cC76hrnwGFfAfrqdW99j3MOYasQcIwTS/aUk=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/exoscale/egoscale v0.67.0/go.mod h1:wi0myUxPsV8SdEtdJHQJxFLL/wEw9fiw9Gs1PWRkvkM=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=
github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/getkin/kin-openapi v0.53.0/go.mod h1:7Yn5whZr5kJi6t+kShccXS8ae1APpYTW6yheSwk8Yi4=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=
github.com/go-acme/lego/v4 v4.6.0 h1:w1rQtE/YHY5SupCTRpRJQbaZ6bkySJJ0z+kl8p6pVJU=
github.com/go-acme/lego/v4 v4.6.0/go.mod h1:v19/zU0bumGNzvsbx07zQ6c9IxAvy55XIKhXCZio3NQ=
github.com/go-chi/chi/v5 v5.0.0/go.mod h1:BBug9lr0cqtdAhsu6R4AAdvufI0/XBzAQSsUqJpoZOs=
github.com/go-cmd/cmd v1.0.5/go.mod h1:y8q8qlK5wQibcw63djSl/ntiHUHXHGdCkPk0j4QeW4s=
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-resty/resty/v2 v2.1.1-0.20191201195748-d7b97669fe48/go.mod h1:dZGr0i9PLlaaTD4H/hoZIDjQ+r6xq8mgbRzHZf7f2J8=
github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY=
github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/gobs/pretty v0.0.0-20180724170744-09732c25a95b/go.mod h1:Xo4aNUOrJnVruqWQJBtW6+bTBDTniY8yZum5rF3b5jw=
github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golangci/lint-1 v0.0.0-20181222135242-d2cdd8c08219/go.mod h1:/X8TswGSh1pIozq4ZwCfxS0WA5JGXguxk94ar/4c87Y=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4=
github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-github/v32 v32.1.0/go.mod h1:rIEpZD9CTDQwDK9GDrtMTycQNA4JU3qBsCizh3q2WCI=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=
github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gophercloud/gophercloud v0.15.1-0.20210202035223-633d73521055/go.mod h1:wRtmUelyIIv3CSSDI47aUwbs075O6i+LY+pXsKCBsb4=
github.com/gophercloud/gophercloud v0.16.0/go.mod h1:wRtmUelyIIv3CSSDI47aUwbs075O6i+LY+pXsKCBsb4=
github.com/gophercloud/utils v0.0.0-20210216074907-f6de111f2eae/go.mod h1:wx8HMD8oQD0Ryhz6+6ykq75PJ79iPyEqYHfwZ4l7OsA=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw=
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-retryablehttp v0.7.0/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY=
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/iij/doapi v0.0.0-20190504054126-0bbf12d6d7df/go.mod h1:QMZY7/J/KSQEhKWFeDesPjMj+wCHReeknARU3wqlyN4=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/infobloxopen/infoblox-go-client v1.1.1/go.mod h1:BXiw7S2b9qJoM8MS40vfgCNB2NLHGusk1DtO16BD9zI=
github.com/jarcoal/httpmock v1.0.5/go.mod h1:ATjnClrvW/3tijVmpL/va5Z3aAyGvqU3gCT8nX0Txik=
github.com/jarcoal/httpmock v1.0.6/go.mod h1:ATjnClrvW/3tijVmpL/va5Z3aAyGvqU3gCT8nX0Txik=
github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.15.4 h1:1kn4/7MepF/CHmYub99/nNX8az0IJjfSOU/jbnTVfqQ=
github.com/klauspost/compress v1.15.4/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.0.12 h1:p9dKCg8i4gmOxtv35DvrYoWqYzQrvEVdjQ762Y0OqZE=
github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c=
github.com/kolo/xmlrpc v0.0.0-20200310150728-e0350524596b/go.mod h1:o03bZfuBwAXHetKXuInt4S7omeXUu62/A845kiycsSQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/labbsr0x/bindman-dns-webhook v1.0.2/go.mod h1:p6b+VCXIR8NYKpDr8/dg1HKfQoRHCdcsROXKvmoehKA=
github.com/labbsr0x/goh v1.0.1/go.mod h1:8K2UhVoaWXcCU7Lxoa2omWnC8gyW8px7/lmO61c027w=
github.com/labstack/echo/v4 v4.2.1/go.mod h1:AA49e0DZ8kk5jTOOCKNuPR6oTnBS0dYiM4FW1e6jwpg=
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
github.com/linode/linodego v0.31.1/go.mod h1:BR0gVkCJffEdIGJSl6bHR80Ty+Uvg/2jkjmrWaFectM=
github.com/liquidweb/go-lwApi v0.0.0-20190605172801-52a4864d2738/go.mod h1:0sYF9rMXb0vlG+4SzdiGMXHheCZxjguMq+Zb4S2BfBs=
github.com/liquidweb/go-lwApi v0.0.5/go.mod h1:0sYF9rMXb0vlG+4SzdiGMXHheCZxjguMq+Zb4S2BfBs=
github.com/liquidweb/liquidweb-cli v0.6.9/go.mod h1:cE1uvQ+x24NGUL75D0QagOFCG8Wdvmwu8aL9TLmA/eQ=
github.com/liquidweb/liquidweb-go v1.6.3/go.mod h1:SuXXp+thr28LnjEw18AYtWwIbWMHSUiajPQs8T9c/Rc=
github.com/lucas-clemente/quic-go v0.27.0 h1:v6WY87q9zD4dKASbG8hy/LpzAVNzEQzw8sEIeloJsc4=
github.com/lucas-clemente/quic-go v0.27.0/go.mod h1:AzgQoPda7N+3IqMMMkywBKggIFo2KT6pfnlrQ2QieeI=
github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/magiconair/properties v1.8.4/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/marten-seemann/qpack v0.2.1 h1:jvTsT/HpCn2UZJdP+UUB53FfUUgeOyG5K1ns0OJOGVs=
github.com/marten-seemann/qpack v0.2.1/go.mod h1:F7Gl5L1jIgN1D11ucXefiuJS9UMVP2opoCp2jDKb7wc=
github.com/marten-seemann/qtls-go1-16 v0.1.5 h1:o9JrYPPco/Nukd/HpOHMHZoBDXQqoNtUCmny98/1uqQ=
github.com/marten-seemann/qtls-go1-16 v0.1.5/go.mod h1:gNpI2Ol+lRS3WwSOtIUUtRwZEQMXjYK+dQSBFbethAk=
github.com/marten-seemann/qtls-go1-17 v0.1.1 h1:DQjHPq+aOzUeh9/lixAGunn6rIOQyWChPSI4+hgW7jc=
github.com/marten-seemann/qtls-go1-17 v0.1.1/go.mod h1:C2ekUKcDdz9SDWxec1N/MvcXBpaX9l3Nx67XaR84L5s=
github.com/marten-seemann/qtls-go1-18 v0.1.1 h1:qp7p7XXUFL7fpBvSS1sWD+uSqPvzNQK43DH+/qEkj0Y=
github.com/marten-seemann/qtls-go1-18 v0.1.1/go.mod h1:mJttiymBAByA49mhlNZZGrH5u1uXYZJ+RW28Py7f4m4=
github.com/matryer/moq v0.0.0-20190312154309-6cfb0558e1bd/go.mod h1:9ELz6aaclSIGnZBoaSLZ3NAl1VTufbOrXBPvtcy6WiQ=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-tty v0.0.0-20180219170247-931426f7535a/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE=
github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=
github.com/miekg/dns v1.1.48 h1:Ucfr7IIVyMBz4lRE8qmGUuZ4Wt3/ZGu9hmcMT3Uu4tQ=
github.com/miekg/dns v1.1.48/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
github.com/mitchellh/go-vnc v0.0.0-20150629162542-723ed9867aed/go.mod h1:3rdaFaCv4AyBgu5ALFM0+tSuHrBh6v692nyQe3ikrq0=
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/namedotcom/go v0.0.0-20180403034216-08470befbe04/go.mod h1:5sN+Lt1CaY4wsPvgQH/jsuJi4XO2ssZbdsIizr4CVC8=
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo=
github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM=
github.com/nrdcg/auroradns v1.0.1/go.mod h1:y4pc0i9QXYlFCWrhWrUSIETnZgrf4KuwjDIWmmXo3JI=
github.com/nrdcg/desec v0.6.0/go.mod h1:wybWg5cRrNmtXLYpUCPCLvz4jfFNEGZQEnoUiX9WqcY=
github.com/nrdcg/dnspod-go v0.4.0/go.mod h1:vZSoFSFeQVm2gWLMkyX61LZ8HI3BaqtHZWgPTGKr6KQ=
github.com/nrdcg/freemyip v0.2.0/go.mod h1:HjF0Yz0lSb37HD2ihIyGz9esyGcxbCrrGFLPpKevbx4=
github.com/nrdcg/goinwx v0.8.1/go.mod h1:tILVc10gieBp/5PMvbcYeXM6pVQ+c9jxDZnpaR1UW7c=
github.com/nrdcg/namesilo v0.2.1/go.mod h1:lwMvfQTyYq+BbjJd30ylEG4GPSS6PII0Tia4rRpRiyw=
github.com/nrdcg/porkbun v0.1.1/go.mod h1:JWl/WKnguWos4mjfp4YizvvToigk9qpQwrodOk+CPoA=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
github.com/onsi/ginkgo v1.16.2/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvwxz1E=
github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.13.0/go.mod h1:lRk9szgn8TxENtWd0Tp4c3wjlRfMTMH27I+3Je41yGY=
github.com/onsi/gomega v1.14.0 h1:ep6kpPVwmr/nTbklSx2nrLNSIO62DoYAhnPNIMhK8gI=
github.com/onsi/gomega v1.14.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0=
github.com/openacid/errors v0.8.1/go.mod h1:GUQEJJOJE3W9skHm8E8Y4phdl2LLEN8iD7c5gcGgdx0=
github.com/openacid/low v0.1.21 h1:Tr2GNu4N/+rGRYdOsEHOE89cxUIaDViZbVmKz29uKGo=
github.com/openacid/low v0.1.21/go.mod h1:q+MsKI6Pz2xsCkzV4BLj7NR5M4EX0sGz5AqotpZDVh0=
github.com/openacid/must v0.1.3/go.mod h1:luPiXCuJlEo3UUFQngVQokV0MPGryeYvtCbQPs3U1+I=
github.com/openacid/testkeys v0.1.6/go.mod h1:MfA7cACzBpbiwekivj8StqX0WIRmqlMsci1c37CA3Do=
github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=
github.com/oracle/oci-go-sdk v24.3.0+incompatible/go.mod h1:VQb79nF8Z2cwLkLS35ukwStZIg5F66tcBccjip/j888=
github.com/oschwald/geoip2-golang v1.7.0 h1:JW1r5AKi+vv2ujSxjKthySK3jo8w8oKWPyXsw+Qs/S8=
github.com/oschwald/geoip2-golang v1.7.0/go.mod h1:mdI/C7iK7NVMcIDDtf4bCKMJ7r0o7UwGeCo9eiitCMQ=
github.com/oschwald/maxminddb-golang v1.9.0 h1:tIk4nv6VT9OiPyrnDAfJS1s1xKDQMZOsGojab6EjC1Y=
github.com/oschwald/maxminddb-golang v1.9.0/go.mod h1:TK+s/Z2oZq0rSl4PSeAEoP0bgm82Cp5HyvYbt8K3zLY=
github.com/ovh/go-ovh v1.1.0/go.mod h1:AxitLZ5HBRPyUd+Zl60Ajaag+rNTdVXWIkzfrVuTXWA=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
github.com/pkg/term v1.1.0/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/pquerna/otp v1.3.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc=
github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rainycape/memcache v0.0.0-20150622160815-1031fa0ce2f2/go.mod h1:7tZKcyumwBO6qip7RNQ5r77yrssm9bfCowcLEBcU5IA=
github.com/refraction-networking/utls v1.1.0 h1:dKXJwSqni/t5csYJ+aQcEgqB7AMWYi6EUc9u3bEmjX0=
github.com/refraction-networking/utls v1.1.0/go.mod h1:tz9gX959MEFfFN5whTIocCLUG57WiILqtdVxI8c6Wj0=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sacloud/libsacloud v1.36.2/go.mod h1:P7YAOVmnIn3DKHqCZcUKYUXmSwGBm3yS7IBEjKVSrjg=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.7.0.20210127161313-bd30bebeac4f/go.mod h1:CJJ5VAbozOl0yEw7nHB9+7BXTJbIn6h7W+f6Gau5IP8=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb h1:XfLJSPIOUX+osiMraVgIrMR27uMXnRJWGm1+GL8/63U=
github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb/go.mod h1:bR6DqgcAl1zTcOX8/pE2Qkj9XO00eCNqmKb7lXP8EAg=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY=
github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM=
github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0=
github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=
github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ=
github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw=
github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI=
github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU=
github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag=
github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg=
github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw=
github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y=
github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg=
github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q=
github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ=
github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I=
github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0=
github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ=
github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk=
github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4=
github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/skratchdot/open-golang v0.0.0-20160302144031-75fb7ed4208c/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/assertions v1.0.1/go.mod h1:kHHU4qYBaI3q23Pp3VPrmWhuIUrLW/7eUrw0BU5VaoM=
github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM=
github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/smartystreets/gunit v1.0.4/go.mod h1:EH5qMBab2UclzXUcpR8b93eHsIlp9u+pDQIRp5DZNzQ=
github.com/softlayer/softlayer-go v1.0.3/go.mod h1:6HepcfAXROz0Rf63krk5hPZyHT6qyx2MNvYyHof7ik4=
github.com/softlayer/xmlrpc v0.0.0-20200409220501-5f089df7cb7e/go.mod h1:fKZCUVdirrxrBpwd9wb+lSoVixvpwAu8eHzbQB2tums=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE=
github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/afero v1.4.1/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q=
github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.287/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod v1.0.287/go.mod h1:CuOaLxOQr477GhMWAQPYQFUJrsZbW+ZqkAgP2uHDZXg=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/transip/gotransip/v6 v6.6.1/go.mod h1:pQZ36hWWRahCUXkFWlx9Hs711gLd8J4qdgLdRzmtY+g=
github.com/u-root/u-root v0.8.1-0.20220504042106-94cc250573fb h1:BtoOyojJgXlr/TOINOWxe+lgywETuKAalKCcPQi2up0=
github.com/u-root/u-root v0.8.1-0.20220504042106-94cc250573fb/go.mod h1:AAjVYNbjuRo6/5HRuoFEECNFjhgmRxXwTEdqLZW4IyQ=
github.com/uber-go/atomic v1.3.2/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g=
github.com/ulikunitz/xz v0.5.10 h1:t92gobL9l3HE202wg3rlk19F6X+JOxl9BBrCCMYEYd8=
github.com/ulikunitz/xz v0.5.10/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/urfave/cli v1.22.5/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/v2fly/v2ray-core/v5 v5.0.6 h1:YTE2Ax2T6BpiDw39iGe9RrvwtID0SbQzEYY/5f3ID/I=
github.com/v2fly/v2ray-core/v5 v5.0.6/go.mod h1:Rv8eq9KRQWZt177euFJb7i2MOqrzfokVmuHGhlfo/zw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU=
github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM=
github.com/vinyldns/go-vinyldns v0.9.16/go.mod h1:5qIJOdmzAnatKjurI+Tl4uTus7GJKJxb+zitufjHs3Q=
github.com/vishvananda/netlink v1.2.0-beta h1:CTNzkunO9iTkRaupF540+w47mexyQgNkA/ibnuKc39w=
github.com/vishvananda/netlink v1.2.0-beta/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho=
github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0=
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 h1:gga7acRE695APm9hlsSMoOoE65U4/TcqNj90mc69Rlg=
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0=
github.com/vultr/govultr/v2 v2.7.1/go.mod h1:BvOhVe6/ZpjwcoL6/unkdQshmbS9VGbowI4QT+3DGVU=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/ratelimit v0.0.0-20180316092928-c15da0234277/go.mod h1:2X8KaoNd1J0lZV+PxJk/5+DGbO/tpwLR1m++a7FnB/Y=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE=
golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw=
golang.org/x/crypto v0.0.0-20180621125126-a49355c7e3f8/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898 h1:SLP7Q4Di66FONjDJbCYrCRrh97focO6sLogHO7/g8F0=
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs=
golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 h1:NWy5+hlRbC7HK+PmcXVUmW1IMyFce7to56IUvhUFm7Y=
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180622082034-63fc586f45fe/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200826173525-f9321e4c35a6/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201110211018-35f3e6cf4a65/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20210611083556-38a9dc6acbc6/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20220411224347-583f2d630306 h1:+gHMid33q6pen7kv9xvT+JRinntgeXO2AeZVd0AWD3w=
golang.org/x/time v0.0.0-20220411224347-583f2d630306/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
golang.org/x/tools v0.0.0-20200410194907-79a7a3126eef/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.11-0.20220325154526-54af36eca237 h1:mAhaIX1KEgotq+ju3XYdXUHvll7bzJDTgiDzIAKDdPc=
golang.org/x/tools v0.1.11-0.20220325154526-54af36eca237/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.zx2c4.com/wireguard v0.0.0-20220407013110-ef5c587f782d h1:q4JksJ2n0fmbXC0Aj0eOs6E0AcPqnKglxWXWFqGD6x0=
golang.zx2c4.com/wireguard v0.0.0-20220407013110-ef5c587f782d/go.mod h1:bVQfyl2sCM/QIIGHpWbFGfHPuDvqnCNkT6MQLTCjO/U=
google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=
google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=
google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg=
google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA=
google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=
google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.57.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ns1/ns1-go.v2 v2.6.2/go.mod h1:GMnKY+ZuoJ+lVLL+78uSTjwTz2jMazq6AfGKQOYhsPk=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/square/go-jose.v2 v2.6.0 h1:NGk74WTnPKBNUhNzQX7PYcTLUjoq7mzKk2OKbvwk2iI=
gopkg.in/square/go-jose.v2 v2.6.0/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o=
gvisor.dev/gvisor v0.0.0-20220428010907-8082b77961ba h1:qJ6jWSTl9q+/y4l8QCNpkNnasX/sHzhVnPRysee8PzY=
gvisor.dev/gvisor v0.0.0-20220428010907-8082b77961ba/go.mod h1:tWwEcFvJavs154OdjFCw78axNrsDlz4Zh8jvPqwcpGI=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
lukechampine.com/blake3 v1.1.7 h1:GgRMhmdsuK8+ii6UZFDL8Nb+VyMwadAgcJyfYHxG6n0=
lukechampine.com/blake3 v1.1.7/go.mod h1:tkKEOtDkNtklkXtLNEOGNq5tcV90tJiA1vAA12R78LA=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
software.sslmate.com/src/go-pkcs12 v0.0.0-20210415151418-c5206de65a78/go.mod h1:B7Wf0Ya4DHF9Yw+qfZuJijQYkWicqDa+79Ytmmq3Kjg=
sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck=
sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0=

View file

@ -11,14 +11,17 @@ import (
"time"
_ "unsafe"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/auth"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/transport/tcp"
N "github.com/sagernet/sing/common/network"
)
type Handler interface {
tcp.Handler
N.TCPConnectionHandler
N.UDPConnectionHandler
E.Handler
}
func HandleRequest(ctx context.Context, request *http.Request, conn net.Conn, authenticator auth.Authenticator, handler Handler, metadata M.Metadata) error {
@ -88,7 +91,8 @@ func HandleRequest(ctx context.Context, request *http.Request, conn net.Conn, au
go func() {
err := handler.NewConnection(ctx, right, metadata)
if err != nil {
handler.HandleError(&tcp.Error{Conn: right, Cause: err})
common.Close(left, right)
handler.HandleError(err)
}
}()
return left, nil

View file

@ -1,241 +0,0 @@
package shadowsocks
import (
"context"
"io"
"net"
"net/netip"
"runtime"
"sync"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/rw"
"github.com/sagernet/sing/common/udpnat"
)
const MethodNone = "none"
type NoneMethod struct{}
func NewNone() Method {
return &NoneMethod{}
}
func (m *NoneMethod) Name() string {
return MethodNone
}
func (m *NoneMethod) KeyLength() int {
return 0
}
func (m *NoneMethod) DialConn(conn net.Conn, destination M.Socksaddr) (net.Conn, error) {
shadowsocksConn := &noneConn{
Conn: conn,
handshake: true,
destination: destination,
}
return shadowsocksConn, shadowsocksConn.clientHandshake()
}
func (m *NoneMethod) DialEarlyConn(conn net.Conn, destination M.Socksaddr) net.Conn {
return &noneConn{
Conn: conn,
destination: destination,
}
}
func (m *NoneMethod) DialPacketConn(conn net.Conn) N.NetPacketConn {
return &nonePacketConn{conn}
}
type noneConn struct {
net.Conn
access sync.Mutex
handshake bool
destination M.Socksaddr
}
func (c *noneConn) clientHandshake() error {
err := M.SocksaddrSerializer.WriteAddrPort(c.Conn, c.destination)
if err != nil {
return err
}
c.handshake = true
return nil
}
func (c *noneConn) Write(b []byte) (n int, err error) {
if c.handshake {
goto direct
}
c.access.Lock()
defer c.access.Unlock()
if c.handshake {
goto direct
}
{
if len(b) == 0 {
return 0, c.clientHandshake()
}
_buffer := buf.StackNew()
buffer := common.Dup(_buffer)
err = M.SocksaddrSerializer.WriteAddrPort(buffer, c.destination)
if err != nil {
return
}
bufN, _ := buffer.Write(b)
_, err = c.Conn.Write(buffer.Bytes())
runtime.KeepAlive(_buffer)
if err != nil {
return
}
if bufN < len(b) {
_, err = c.Conn.Write(b[bufN:])
if err != nil {
return
}
}
n = len(b)
}
direct:
return c.Conn.Write(b)
}
func (c *noneConn) ReadFrom(r io.Reader) (n int64, err error) {
if !c.handshake {
return rw.ReadFrom0(c, r)
}
return c.Conn.(io.ReaderFrom).ReadFrom(r)
}
func (c *noneConn) WriteTo(w io.Writer) (n int64, err error) {
return io.Copy(w, c.Conn)
}
func (c *noneConn) RemoteAddr() net.Addr {
return c.destination.TCPAddr()
}
type nonePacketConn struct {
net.Conn
}
func (c *nonePacketConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
_, err := buffer.ReadFrom(c)
if err != nil {
return M.Socksaddr{}, err
}
return M.SocksaddrSerializer.ReadAddrPort(buffer)
}
func (c *nonePacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
header := buf.With(buffer.ExtendHeader(M.SocksaddrSerializer.AddrPortLen(destination)))
err := M.SocksaddrSerializer.WriteAddrPort(header, destination)
if err != nil {
return err
}
return common.Error(buffer.WriteTo(c))
}
func (c *nonePacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
n, err = c.Read(p)
if err != nil {
return
}
buffer := buf.With(p[:n])
destination, err := M.SocksaddrSerializer.ReadAddrPort(buffer)
if err != nil {
return
}
addr = destination.UDPAddr()
n = copy(p, buffer.Bytes())
return
}
func (c *nonePacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
destination := M.SocksaddrFromNet(addr)
_buffer := buf.Make(M.SocksaddrSerializer.AddrPortLen(destination) + len(p))
defer runtime.KeepAlive(_buffer)
buffer := buf.With(common.Dup(_buffer))
err = M.SocksaddrSerializer.WriteAddrPort(buffer, destination)
if err != nil {
return
}
_, err = buffer.Write(p)
if err != nil {
return
}
return len(p), nil
}
type NoneService struct {
handler Handler
udp *udpnat.Service[netip.AddrPort]
}
func NewNoneService(udpTimeout int64, handler Handler) Service {
s := &NoneService{
handler: handler,
}
s.udp = udpnat.New[netip.AddrPort](udpTimeout, s)
return s
}
func (s *NoneService) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
destination, err := M.SocksaddrSerializer.ReadAddrPort(conn)
if err != nil {
return err
}
metadata.Protocol = "shadowsocks"
metadata.Destination = destination
return s.handler.NewConnection(ctx, conn, metadata)
}
func (s *NoneService) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
destination, err := M.SocksaddrSerializer.ReadAddrPort(buffer)
if err != nil {
return err
}
metadata.Protocol = "shadowsocks"
metadata.Destination = destination
s.udp.NewPacket(ctx, metadata.Source.AddrPort(), func() N.PacketWriter {
return &nonePacketWriter{conn, metadata.Source}
}, buffer, metadata)
return nil
}
type nonePacketWriter struct {
N.PacketConn
sourceAddr M.Socksaddr
}
func (s *nonePacketWriter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
header := buf.With(buffer.ExtendHeader(M.SocksaddrSerializer.AddrPortLen(destination)))
err := M.SocksaddrSerializer.WriteAddrPort(header, destination)
if err != nil {
return err
}
return s.PacketConn.WritePacket(buffer, s.sourceAddr)
}
func (s *NoneService) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
return s.handler.NewPacketConnection(ctx, conn, metadata)
}
func (s *NoneService) HandleError(err error) {
s.handler.HandleError(err)
}

View file

@ -1,64 +0,0 @@
package shadowsocks
import (
"crypto/md5"
"hash/crc32"
"io"
"math/rand"
"net"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
var (
ErrBadKey = E.New("bad key")
ErrMissingPassword = E.New("missing password")
)
type Method interface {
Name() string
KeyLength() int
DialConn(conn net.Conn, destination M.Socksaddr) (net.Conn, error)
DialEarlyConn(conn net.Conn, destination M.Socksaddr) net.Conn
DialPacketConn(conn net.Conn) N.NetPacketConn
}
func Key(password []byte, keySize int) []byte {
const md5Len = 16
cnt := (keySize-1)/md5Len + 1
m := make([]byte, cnt*md5Len)
sum := md5.Sum(password)
copy(m, sum[:])
// Repeatedly call md5 until bytes generated is enough.
// Each call to md5 uses data: prev md5 sum + password.
d := make([]byte, md5Len+len(password))
start := 0
for i := 1; i < cnt; i++ {
start += md5Len
copy(d, m[start-md5Len:start])
copy(d[md5Len:], password)
sum = md5.Sum(d)
copy(m[start:], sum[:])
}
return m[:keySize]
}
type ReducedEntropyReader struct {
io.Reader
}
func (r *ReducedEntropyReader) Read(p []byte) (n int, err error) {
n, err = r.Reader.Read(p)
if n > 6 {
const charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~\\\""
seed := rand.New(rand.NewSource(int64(crc32.ChecksumIEEE(p[:6]))))
for i := range p[:6] {
p[i] = charSet[seed.Intn(len(charSet))]
}
}
return
}

View file

@ -1,62 +0,0 @@
package shadowsocks
import (
"context"
"fmt"
"net"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
type Service interface {
M.TCPConnectionHandler
N.UDPHandler
}
type Handler interface {
M.TCPConnectionHandler
N.UDPConnectionHandler
E.Handler
}
type UserContext[U comparable] struct {
context.Context
User U
}
type ServerConnError struct {
net.Conn
Source M.Socksaddr
Cause error
}
func (e *ServerConnError) Close() error {
if conn, ok := common.Cast[*net.TCPConn](e.Conn); ok {
conn.SetLinger(0)
}
return e.Conn.Close()
}
func (e *ServerConnError) Unwrap() error {
return e.Cause
}
func (e *ServerConnError) Error() string {
return fmt.Sprint("shadowsocks: serve TCP from ", e.Source, ": ", e.Cause)
}
type ServerPacketError struct {
Source M.Socksaddr
Cause error
}
func (e *ServerPacketError) Unwrap() error {
return e.Cause
}
func (e *ServerPacketError) Error() string {
return fmt.Sprint("shadowsocks: serve UDP from ", e.Source, ": ", e.Cause)
}

View file

@ -1,413 +0,0 @@
package shadowaead
import (
"crypto/cipher"
"encoding/binary"
"io"
"github.com/sagernet/sing/common/buf"
)
// https://shadowsocks.org/en/wiki/AEAD-Ciphers.html
const (
MaxPacketSize = 16*1024 - 1
PacketLengthBufferSize = 2
)
const (
// NonceSize
// crypto/cipher.gcmStandardNonceSize
// golang.org/x/crypto/chacha20poly1305.NonceSize
NonceSize = 12
// Overhead
// crypto/cipher.gcmTagSize
// golang.org/x/crypto/chacha20poly1305.Overhead
Overhead = 16
)
type Reader struct {
upstream io.Reader
cipher cipher.AEAD
buffer []byte
nonce []byte
index int
cached int
}
func NewReader(upstream io.Reader, cipher cipher.AEAD, maxPacketSize int) *Reader {
return &Reader{
upstream: upstream,
cipher: cipher,
buffer: make([]byte, maxPacketSize+PacketLengthBufferSize+Overhead*2),
nonce: make([]byte, NonceSize),
}
}
func NewRawReader(upstream io.Reader, cipher cipher.AEAD, buffer []byte, nonce []byte) *Reader {
return &Reader{
upstream: upstream,
cipher: cipher,
buffer: buffer,
nonce: nonce,
}
}
func (r *Reader) Upstream() any {
return r.upstream
}
func (r *Reader) WriteTo(writer io.Writer) (n int64, err error) {
if r.cached > 0 {
writeN, writeErr := writer.Write(r.buffer[r.index : r.index+r.cached])
if writeErr != nil {
return int64(writeN), writeErr
}
n += int64(writeN)
}
for {
start := PacketLengthBufferSize + Overhead
_, err = io.ReadFull(r.upstream, r.buffer[:start])
if err != nil {
return
}
_, err = r.cipher.Open(r.buffer[:0], r.nonce, r.buffer[:start], nil)
if err != nil {
return
}
increaseNonce(r.nonce)
length := int(binary.BigEndian.Uint16(r.buffer[:PacketLengthBufferSize]))
end := length + Overhead
_, err = io.ReadFull(r.upstream, r.buffer[:end])
if err != nil {
return
}
_, err = r.cipher.Open(r.buffer[:0], r.nonce, r.buffer[:end], nil)
if err != nil {
return
}
increaseNonce(r.nonce)
writeN, writeErr := writer.Write(r.buffer[:length])
if writeErr != nil {
return int64(writeN), writeErr
}
n += int64(writeN)
}
}
func (r *Reader) readInternal() (err error) {
start := PacketLengthBufferSize + Overhead
_, err = io.ReadFull(r.upstream, r.buffer[:start])
if err != nil {
return err
}
_, err = r.cipher.Open(r.buffer[:0], r.nonce, r.buffer[:start], nil)
if err != nil {
return err
}
increaseNonce(r.nonce)
length := int(binary.BigEndian.Uint16(r.buffer[:PacketLengthBufferSize]))
end := length + Overhead
_, err = io.ReadFull(r.upstream, r.buffer[:end])
if err != nil {
return err
}
_, err = r.cipher.Open(r.buffer[:0], r.nonce, r.buffer[:end], nil)
if err != nil {
return err
}
increaseNonce(r.nonce)
r.cached = length
r.index = 0
return nil
}
func (r *Reader) ReadByte() (byte, error) {
if r.cached == 0 {
err := r.readInternal()
if err != nil {
return 0, err
}
}
index := r.index
r.index++
r.cached--
return r.buffer[index], nil
}
func (r *Reader) Read(b []byte) (n int, err error) {
if r.cached > 0 {
n = copy(b, r.buffer[r.index:r.index+r.cached])
r.cached -= n
r.index += n
return
}
start := PacketLengthBufferSize + Overhead
_, err = io.ReadFull(r.upstream, r.buffer[:start])
if err != nil {
return 0, err
}
_, err = r.cipher.Open(r.buffer[:0], r.nonce, r.buffer[:start], nil)
if err != nil {
return 0, err
}
increaseNonce(r.nonce)
length := int(binary.BigEndian.Uint16(r.buffer[:PacketLengthBufferSize]))
end := length + Overhead
if len(b) >= end {
data := b[:end]
_, err = io.ReadFull(r.upstream, data)
if err != nil {
return 0, err
}
_, err = r.cipher.Open(b[:0], r.nonce, data, nil)
if err != nil {
return 0, err
}
increaseNonce(r.nonce)
return length, nil
} else {
_, err = io.ReadFull(r.upstream, r.buffer[:end])
if err != nil {
return 0, err
}
_, err = r.cipher.Open(r.buffer[:0], r.nonce, r.buffer[:end], nil)
if err != nil {
return 0, err
}
increaseNonce(r.nonce)
n = copy(b, r.buffer[:length])
r.cached = length - n
r.index = n
return
}
}
func (r *Reader) Discard(n int) error {
for {
if r.cached >= n {
r.cached -= n
r.index += n
return nil
} else if r.cached > 0 {
n -= r.cached
r.cached = 0
r.index = 0
}
err := r.readInternal()
if err != nil {
return err
}
}
}
func (r *Reader) Cached() int {
return r.cached
}
func (r *Reader) CachedSlice() []byte {
return r.buffer[r.index : r.index+r.cached]
}
func (r *Reader) ReadWithLengthChunk(lengthChunk []byte) error {
_, err := r.cipher.Open(r.buffer[:0], r.nonce, lengthChunk, nil)
if err != nil {
return err
}
increaseNonce(r.nonce)
length := int(binary.BigEndian.Uint16(r.buffer[:PacketLengthBufferSize]))
end := length + Overhead
_, err = io.ReadFull(r.upstream, r.buffer[:end])
if err != nil {
return err
}
_, err = r.cipher.Open(r.buffer[:0], r.nonce, r.buffer[:end], nil)
if err != nil {
return err
}
increaseNonce(r.nonce)
r.cached = length
r.index = 0
return nil
}
func (r *Reader) ReadWithLength(length uint16) error {
end := length + Overhead
_, err := io.ReadFull(r.upstream, r.buffer[:end])
if err != nil {
return err
}
_, err = r.cipher.Open(r.buffer[:0], r.nonce, r.buffer[:end], nil)
if err != nil {
return err
}
increaseNonce(r.nonce)
r.cached = int(length)
r.index = 0
return nil
}
func (r *Reader) ReadChunk(chunk []byte) error {
bb, err := r.cipher.Open(r.buffer[:0], r.nonce, chunk, nil)
if err != nil {
return err
}
increaseNonce(r.nonce)
r.cached = len(bb)
r.index = 0
return nil
}
type Writer struct {
upstream io.Writer
cipher cipher.AEAD
maxPacketSize int
buffer []byte
nonce []byte
}
func NewWriter(upstream io.Writer, cipher cipher.AEAD, maxPacketSize int) *Writer {
return &Writer{
upstream: upstream,
cipher: cipher,
buffer: make([]byte, maxPacketSize+PacketLengthBufferSize+Overhead*2),
nonce: make([]byte, cipher.NonceSize()),
maxPacketSize: maxPacketSize,
}
}
func NewRawWriter(upstream io.Writer, cipher cipher.AEAD, maxPacketSize int, buffer []byte, nonce []byte) *Writer {
return &Writer{
upstream: upstream,
cipher: cipher,
maxPacketSize: maxPacketSize,
buffer: buffer,
nonce: nonce,
}
}
func (w *Writer) Upstream() any {
return w.upstream
}
func (w *Writer) ReadFrom(r io.Reader) (n int64, err error) {
for {
offset := Overhead + PacketLengthBufferSize
readN, readErr := r.Read(w.buffer[offset : offset+w.maxPacketSize])
if readErr != nil {
return 0, readErr
}
binary.BigEndian.PutUint16(w.buffer[:PacketLengthBufferSize], uint16(readN))
w.cipher.Seal(w.buffer[:0], w.nonce, w.buffer[:PacketLengthBufferSize], nil)
increaseNonce(w.nonce)
packet := w.cipher.Seal(w.buffer[offset:offset], w.nonce, w.buffer[offset:offset+readN], nil)
increaseNonce(w.nonce)
_, err = w.upstream.Write(w.buffer[:offset+len(packet)])
if err != nil {
return
}
n += int64(readN)
}
}
func (w *Writer) Write(p []byte) (n int, err error) {
if len(p) == 0 {
return
}
for _, data := range buf.ForeachN(p, w.maxPacketSize) {
binary.BigEndian.PutUint16(w.buffer[:PacketLengthBufferSize], uint16(len(data)))
w.cipher.Seal(w.buffer[:0], w.nonce, w.buffer[:PacketLengthBufferSize], nil)
increaseNonce(w.nonce)
offset := Overhead + PacketLengthBufferSize
packet := w.cipher.Seal(w.buffer[offset:offset], w.nonce, data, nil)
increaseNonce(w.nonce)
_, err = w.upstream.Write(w.buffer[:offset+len(packet)])
if err != nil {
return
}
n += len(data)
}
return
}
func (w *Writer) Buffer() *buf.Buffer {
return buf.With(w.buffer)
}
func (w *Writer) WriteChunk(buffer *buf.Buffer, chunk []byte) {
bb := w.cipher.Seal(buffer.Index(buffer.Len()), w.nonce, chunk, nil)
buffer.Extend(len(bb))
increaseNonce(w.nonce)
}
func (w *Writer) BufferedWriter(reversed int) *BufferedWriter {
return &BufferedWriter{
upstream: w,
reversed: reversed,
data: w.buffer[PacketLengthBufferSize+Overhead : len(w.buffer)-Overhead],
}
}
type BufferedWriter struct {
upstream *Writer
data []byte
reversed int
index int
}
func (w *BufferedWriter) UpstreamWriter() io.Writer {
return w.upstream
}
func (w *BufferedWriter) WriterReplaceable() bool {
return w.index == 0
}
func (w *BufferedWriter) Write(p []byte) (n int, err error) {
var index int
for {
cachedN := copy(w.data[w.reversed+w.index:], p[index:])
if cachedN == len(p[index:]) {
w.index += cachedN
return cachedN, nil
}
err = w.Flush()
if err != nil {
return
}
index += cachedN
}
}
func (w *BufferedWriter) Flush() error {
if w.index == 0 {
if w.reversed > 0 {
_, err := w.upstream.upstream.Write(w.upstream.buffer[:w.reversed])
w.reversed = 0
return err
}
return nil
}
buffer := w.upstream.buffer[w.reversed:]
binary.BigEndian.PutUint16(buffer[:PacketLengthBufferSize], uint16(w.index))
w.upstream.cipher.Seal(buffer[:0], w.upstream.nonce, buffer[:PacketLengthBufferSize], nil)
increaseNonce(w.upstream.nonce)
offset := Overhead + PacketLengthBufferSize
packet := w.upstream.cipher.Seal(buffer[offset:offset], w.upstream.nonce, buffer[offset:offset+w.index], nil)
increaseNonce(w.upstream.nonce)
_, err := w.upstream.upstream.Write(w.upstream.buffer[:w.reversed+offset+len(packet)])
w.reversed = 0
return err
}
func increaseNonce(nonce []byte) {
for i := range nonce {
nonce[i]++
if nonce[i] != 0 {
return
}
}
}

View file

@ -1,362 +0,0 @@
package shadowaead
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha1"
"io"
"net"
"runtime"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
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/rw"
"github.com/sagernet/sing/protocol/shadowsocks"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/hkdf"
)
var List = []string{
"aes-128-gcm",
"aes-192-gcm",
"aes-256-gcm",
"chacha20-ietf-poly1305",
"xchacha20-ietf-poly1305",
}
func New(method string, key []byte, password string, secureRNG io.Reader) (shadowsocks.Method, error) {
m := &Method{
name: method,
secureRNG: secureRNG,
}
switch method {
case "aes-128-gcm":
m.keySaltLength = 16
m.constructor = newAESGCM
case "aes-192-gcm":
m.keySaltLength = 24
m.constructor = newAESGCM
case "aes-256-gcm":
m.keySaltLength = 32
m.constructor = newAESGCM
case "chacha20-ietf-poly1305":
m.keySaltLength = 32
m.constructor = func(key []byte) cipher.AEAD {
cipher, err := chacha20poly1305.New(key)
common.Must(err)
return cipher
}
case "xchacha20-ietf-poly1305":
m.keySaltLength = 32
m.constructor = func(key []byte) cipher.AEAD {
cipher, err := chacha20poly1305.NewX(key)
common.Must(err)
return cipher
}
}
if len(key) == m.keySaltLength {
m.key = key
} else if len(key) > 0 {
return nil, shadowsocks.ErrBadKey
} else if password == "" {
return nil, shadowsocks.ErrMissingPassword
} else {
m.key = shadowsocks.Key([]byte(password), m.keySaltLength)
}
return m, nil
}
func Kdf(key, iv []byte, keyLength int) []byte {
info := []byte("ss-subkey")
subKey := buf.Make(keyLength)
kdf := hkdf.New(sha1.New, key, iv, common.Dup(info))
runtime.KeepAlive(info)
common.Must1(io.ReadFull(kdf, common.Dup(subKey)))
return subKey
}
func newAESGCM(key []byte) cipher.AEAD {
block, err := aes.NewCipher(key)
common.Must(err)
aead, err := cipher.NewGCM(block)
common.Must(err)
return aead
}
type Method struct {
name string
keySaltLength int
constructor func(key []byte) cipher.AEAD
key []byte
secureRNG io.Reader
}
func (m *Method) Name() string {
return m.name
}
func (m *Method) KeyLength() int {
return m.keySaltLength
}
func (m *Method) ReadRequest(upstream io.Reader) (io.Reader, error) {
_salt := buf.Make(m.keySaltLength)
defer runtime.KeepAlive(_salt)
salt := common.Dup(_salt)
_, err := io.ReadFull(upstream, salt)
if err != nil {
return nil, E.Cause(err, "read salt")
}
key := Kdf(m.key, salt, m.keySaltLength)
defer runtime.KeepAlive(key)
return NewReader(upstream, m.constructor(common.Dup(key)), MaxPacketSize), nil
}
func (m *Method) WriteResponse(upstream io.Writer) (io.Writer, error) {
_salt := buf.Make(m.keySaltLength)
defer runtime.KeepAlive(_salt)
salt := common.Dup(_salt)
common.Must1(io.ReadFull(m.secureRNG, salt))
_, err := upstream.Write(salt)
if err != nil {
return nil, err
}
key := Kdf(m.key, salt, m.keySaltLength)
return NewWriter(upstream, m.constructor(common.Dup(key)), MaxPacketSize), nil
}
func (m *Method) DialConn(conn net.Conn, destination M.Socksaddr) (net.Conn, error) {
shadowsocksConn := &clientConn{
Conn: conn,
method: m,
destination: destination,
}
return shadowsocksConn, shadowsocksConn.writeRequest(nil)
}
func (m *Method) DialEarlyConn(conn net.Conn, destination M.Socksaddr) net.Conn {
return &clientConn{
Conn: conn,
method: m,
destination: destination,
}
}
func (m *Method) DialPacketConn(conn net.Conn) N.NetPacketConn {
return &clientPacketConn{m, conn}
}
func (m *Method) EncodePacket(buffer *buf.Buffer) error {
key := Kdf(m.key, buffer.To(m.keySaltLength), m.keySaltLength)
c := m.constructor(common.Dup(key))
runtime.KeepAlive(key)
c.Seal(buffer.Index(m.keySaltLength), rw.ZeroBytes[:c.NonceSize()], buffer.From(m.keySaltLength), nil)
buffer.Extend(Overhead)
return nil
}
func (m *Method) DecodePacket(buffer *buf.Buffer) error {
if buffer.Len() < m.keySaltLength {
return E.New("bad packet")
}
key := Kdf(m.key, buffer.To(m.keySaltLength), m.keySaltLength)
c := m.constructor(common.Dup(key))
runtime.KeepAlive(key)
packet, err := c.Open(buffer.Index(m.keySaltLength), rw.ZeroBytes[:c.NonceSize()], buffer.From(m.keySaltLength), nil)
if err != nil {
return err
}
buffer.Advance(m.keySaltLength)
buffer.Truncate(len(packet))
return nil
}
type clientConn struct {
net.Conn
method *Method
destination M.Socksaddr
reader *Reader
writer *Writer
}
func (c *clientConn) writeRequest(payload []byte) error {
_salt := make([]byte, c.method.keySaltLength)
salt := common.Dup(_salt)
common.Must1(io.ReadFull(c.method.secureRNG, salt))
key := Kdf(c.method.key, salt, c.method.keySaltLength)
runtime.KeepAlive(_salt)
writer := NewWriter(
c.Conn,
c.method.constructor(common.Dup(key)),
MaxPacketSize,
)
runtime.KeepAlive(key)
header := writer.Buffer()
header.Write(salt)
bufferedWriter := writer.BufferedWriter(header.Len())
if len(payload) > 0 {
err := M.SocksaddrSerializer.WriteAddrPort(bufferedWriter, c.destination)
if err != nil {
return err
}
_, err = bufferedWriter.Write(payload)
if err != nil {
return err
}
} else {
err := M.SocksaddrSerializer.WriteAddrPort(bufferedWriter, c.destination)
if err != nil {
return err
}
}
err := bufferedWriter.Flush()
if err != nil {
return err
}
c.writer = writer
return nil
}
func (c *clientConn) readResponse() error {
if c.reader != nil {
return nil
}
_salt := buf.Make(c.method.keySaltLength)
defer runtime.KeepAlive(_salt)
salt := common.Dup(_salt)
_, err := io.ReadFull(c.Conn, salt)
if err != nil {
return err
}
key := Kdf(c.method.key, salt, c.method.keySaltLength)
defer runtime.KeepAlive(key)
c.reader = NewReader(
c.Conn,
c.method.constructor(common.Dup(key)),
MaxPacketSize,
)
return nil
}
func (c *clientConn) Read(p []byte) (n int, err error) {
if err = c.readResponse(); err != nil {
return
}
return c.reader.Read(p)
}
func (c *clientConn) WriteTo(w io.Writer) (n int64, err error) {
if err = c.readResponse(); err != nil {
return
}
return c.reader.WriteTo(w)
}
func (c *clientConn) Write(p []byte) (n int, err error) {
if c.writer != nil {
return c.writer.Write(p)
}
err = c.writeRequest(p)
if err != nil {
return
}
return len(p), nil
}
func (c *clientConn) ReadFrom(r io.Reader) (n int64, err error) {
if c.writer == nil {
return rw.ReadFrom0(c, r)
}
return c.writer.ReadFrom(r)
}
func (c *clientConn) Upstream() any {
return c.Conn
}
type clientPacketConn struct {
*Method
net.Conn
}
func (c *clientPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
header := buffer.ExtendHeader(c.keySaltLength + M.SocksaddrSerializer.AddrPortLen(destination))
common.Must1(io.ReadFull(c.secureRNG, header[:c.keySaltLength]))
err := M.SocksaddrSerializer.WriteAddrPort(buf.With(header[c.keySaltLength:]), destination)
if err != nil {
return err
}
err = c.EncodePacket(buffer)
if err != nil {
return err
}
return common.Error(c.Write(buffer.Bytes()))
}
func (c *clientPacketConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
n, err := c.Read(buffer.FreeBytes())
if err != nil {
return M.Socksaddr{}, err
}
buffer.Truncate(n)
err = c.DecodePacket(buffer)
if err != nil {
return M.Socksaddr{}, err
}
return M.SocksaddrSerializer.ReadAddrPort(buffer)
}
func (c *clientPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
n, err = c.Read(p)
if err != nil {
return
}
b := buf.With(p[:n])
err = c.DecodePacket(b)
if err != nil {
return
}
destination, err := M.SocksaddrSerializer.ReadAddrPort(b)
if err != nil {
return
}
addr = destination.UDPAddr()
n = copy(p, b.Bytes())
return
}
func (c *clientPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
_buffer := buf.StackNew()
defer runtime.KeepAlive(_buffer)
buffer := common.Dup(_buffer)
err = M.SocksaddrSerializer.WriteAddrPort(buffer, M.SocksaddrFromNet(addr))
if err != nil {
return
}
_, err = buffer.Write(p)
if err != nil {
return
}
err = c.EncodePacket(buffer)
if err != nil {
return
}
_, err = c.Write(buffer.Bytes())
if err != nil {
return
}
return len(p), nil
}
func (c *clientPacketConn) Upstream() any {
return c.Conn
}

View file

@ -1,247 +0,0 @@
package shadowaead
import (
"context"
"crypto/cipher"
"io"
"net"
"net/netip"
"runtime"
"sync"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
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/rw"
"github.com/sagernet/sing/common/udpnat"
"github.com/sagernet/sing/protocol/shadowsocks"
"golang.org/x/crypto/chacha20poly1305"
)
var ErrBadHeader = E.New("bad header")
type Service struct {
name string
keySaltLength int
constructor func(key []byte) cipher.AEAD
key []byte
secureRNG io.Reader
handler shadowsocks.Handler
udpNat *udpnat.Service[netip.AddrPort]
}
func NewService(method string, key []byte, password string, secureRNG io.Reader, udpTimeout int64, handler shadowsocks.Handler) (shadowsocks.Service, error) {
s := &Service{
name: method,
secureRNG: secureRNG,
handler: handler,
udpNat: udpnat.New[netip.AddrPort](udpTimeout, handler),
}
switch method {
case "aes-128-gcm":
s.keySaltLength = 16
s.constructor = newAESGCM
case "aes-192-gcm":
s.keySaltLength = 24
s.constructor = newAESGCM
case "aes-256-gcm":
s.keySaltLength = 32
s.constructor = newAESGCM
case "chacha20-ietf-poly1305":
s.keySaltLength = 32
s.constructor = func(key []byte) cipher.AEAD {
cipher, err := chacha20poly1305.New(key)
common.Must(err)
return cipher
}
case "xchacha20-ietf-poly1305":
s.keySaltLength = 32
s.constructor = func(key []byte) cipher.AEAD {
cipher, err := chacha20poly1305.NewX(key)
common.Must(err)
return cipher
}
}
if len(key) == s.keySaltLength {
s.key = key
} else if len(key) > 0 {
return nil, shadowsocks.ErrBadKey
} else if password != "" {
s.key = shadowsocks.Key([]byte(password), s.keySaltLength)
} else {
return nil, shadowsocks.ErrMissingPassword
}
return s, nil
}
func (s *Service) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
err := s.newConnection(ctx, conn, metadata)
if err != nil {
err = &shadowsocks.ServerConnError{Conn: conn, Source: metadata.Source, Cause: err}
}
return err
}
func (s *Service) newConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
_header := buf.Make(s.keySaltLength + PacketLengthBufferSize + Overhead)
defer runtime.KeepAlive(_header)
header := common.Dup(_header)
n, err := conn.Read(header)
if err != nil {
return E.Cause(err, "read header")
} else if n < len(header) {
return ErrBadHeader
}
key := Kdf(s.key, header[:s.keySaltLength], s.keySaltLength)
reader := NewReader(conn, s.constructor(common.Dup(key)), MaxPacketSize)
err = reader.ReadWithLengthChunk(header[s.keySaltLength:])
if err != nil {
return err
}
destination, err := M.SocksaddrSerializer.ReadAddrPort(reader)
if err != nil {
return err
}
metadata.Protocol = "shadowsocks"
metadata.Destination = destination
return s.handler.NewConnection(ctx, &serverConn{
Service: s,
Conn: conn,
reader: reader,
}, metadata)
}
type serverConn struct {
*Service
net.Conn
access sync.Mutex
reader *Reader
writer *Writer
}
func (c *serverConn) writeResponse(payload []byte) (n int, err error) {
_salt := buf.Make(c.keySaltLength)
salt := common.Dup(_salt)
common.Must1(io.ReadFull(c.secureRNG, salt))
key := Kdf(c.key, salt, c.keySaltLength)
runtime.KeepAlive(_salt)
writer := NewWriter(
c.Conn,
c.constructor(common.Dup(key)),
MaxPacketSize,
)
runtime.KeepAlive(key)
header := writer.Buffer()
header.Write(salt)
bufferedWriter := writer.BufferedWriter(header.Len())
if len(payload) > 0 {
_, err = bufferedWriter.Write(payload)
if err != nil {
return
}
}
err = bufferedWriter.Flush()
if err != nil {
return
}
c.writer = writer
return
}
func (c *serverConn) Write(p []byte) (n int, err error) {
if c.writer != nil {
return c.writer.Write(p)
}
c.access.Lock()
if c.writer != nil {
c.access.Unlock()
return c.writer.Write(p)
}
defer c.access.Unlock()
return c.writeResponse(p)
}
func (c *serverConn) ReadFrom(r io.Reader) (n int64, err error) {
if c.writer == nil {
return rw.ReadFrom0(c, r)
}
return c.writer.ReadFrom(r)
}
func (c *serverConn) WriteTo(w io.Writer) (n int64, err error) {
return c.reader.WriteTo(w)
}
func (c *serverConn) Upstream() any {
return c.Conn
}
func (s *Service) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
err := s.newPacket(ctx, conn, buffer, metadata)
if err != nil {
err = &shadowsocks.ServerPacketError{Source: metadata.Source, Cause: err}
}
return err
}
func (s *Service) newPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
if buffer.Len() < s.keySaltLength {
return E.New("bad packet")
}
key := Kdf(s.key, buffer.To(s.keySaltLength), s.keySaltLength)
c := s.constructor(common.Dup(key))
runtime.KeepAlive(key)
packet, err := c.Open(buffer.Index(s.keySaltLength), rw.ZeroBytes[:c.NonceSize()], buffer.From(s.keySaltLength), nil)
if err != nil {
return err
}
buffer.Advance(s.keySaltLength)
buffer.Truncate(len(packet))
destination, err := M.SocksaddrSerializer.ReadAddrPort(buffer)
if err != nil {
return err
}
metadata.Protocol = "shadowsocks"
metadata.Destination = destination
s.udpNat.NewPacket(ctx, metadata.Source.AddrPort(), func() N.PacketWriter {
return &serverPacketWriter{s, conn, metadata.Source}
}, buffer, metadata)
return nil
}
type serverPacketWriter struct {
*Service
N.PacketConn
source M.Socksaddr
}
func (w *serverPacketWriter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
header := buffer.ExtendHeader(w.keySaltLength + M.SocksaddrSerializer.AddrPortLen(destination))
common.Must1(io.ReadFull(w.secureRNG, header[:w.keySaltLength]))
err := M.SocksaddrSerializer.WriteAddrPort(buf.With(header[w.keySaltLength:]), destination)
if err != nil {
return err
}
key := Kdf(w.key, buffer.To(w.keySaltLength), w.keySaltLength)
c := w.constructor(common.Dup(key))
runtime.KeepAlive(key)
c.Seal(buffer.From(w.keySaltLength)[:0], rw.ZeroBytes[:c.NonceSize()], buffer.From(w.keySaltLength), nil)
buffer.Extend(Overhead)
return w.PacketConn.WritePacket(buffer, w.source)
}

View file

@ -1,717 +0,0 @@
package shadowaead_2022
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"encoding/binary"
"io"
"math"
"math/rand"
"net"
"os"
"runtime"
"sync/atomic"
"time"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
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/replay"
"github.com/sagernet/sing/common/rw"
"github.com/sagernet/sing/protocol/shadowsocks"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead"
"golang.org/x/crypto/chacha20poly1305"
wgReplay "golang.zx2c4.com/wireguard/replay"
"lukechampine.com/blake3"
)
const (
HeaderTypeClient = 0
HeaderTypeServer = 1
MaxPaddingLength = 900
PacketNonceSize = 24
MaxPacketSize = 65535
RequestHeaderFixedChunkLength = 1 + 8 + 2
)
var (
ErrMissingPasswordPSK = E.New("missing password or psk")
ErrBadHeaderType = E.New("bad header type")
ErrBadTimestamp = E.New("bad timestamp")
ErrBadRequestSalt = E.New("bad request salt")
ErrBadClientSessionId = E.New("bad client session id")
ErrPacketIdNotUnique = E.New("packet id not unique")
ErrTooManyServerSessions = E.New("server session changed more than once during the last minute")
)
var List = []string{
"2022-blake3-aes-128-gcm",
"2022-blake3-aes-256-gcm",
"2022-blake3-chacha20-poly1305",
}
func New(method string, pskList [][]byte, password string, secureRNG io.Reader) (shadowsocks.Method, error) {
m := &Method{
name: method,
secureRNG: secureRNG,
replayFilter: replay.NewCuckoo(60),
}
switch method {
case "2022-blake3-aes-128-gcm":
m.keySaltLength = 16
m.constructor = newAESGCM
m.blockConstructor = newAES
case "2022-blake3-aes-256-gcm":
m.keySaltLength = 32
m.constructor = newAESGCM
m.blockConstructor = newAES
case "2022-blake3-chacha20-poly1305":
if len(pskList) > 1 {
return nil, os.ErrInvalid
}
m.keySaltLength = 32
m.constructor = newChacha20Poly1305
}
if len(pskList) == 0 {
if password == "" {
return nil, ErrMissingPasswordPSK
}
pskList = [][]byte{Key([]byte(password), m.keySaltLength)}
}
for i, psk := range pskList {
if len(psk) < m.keySaltLength {
return nil, shadowsocks.ErrBadKey
} else if len(psk) > m.keySaltLength {
pskList[i] = Key(psk, m.keySaltLength)
}
}
if len(pskList) > 1 {
pskHash := make([]byte, (len(pskList)-1)*aes.BlockSize)
for i, psk := range pskList {
if i == 0 {
continue
}
hash := blake3.Sum512(psk)
copy(pskHash[aes.BlockSize*(i-1):aes.BlockSize*i], hash[:aes.BlockSize])
}
m.pskHash = pskHash
}
switch method {
case "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm":
m.udpBlockCipher = newAES(pskList[0])
case "2022-blake3-chacha20-poly1305":
m.udpCipher = newXChacha20Poly1305(pskList[0])
}
m.pskList = pskList
return m, nil
}
func Key(key []byte, keyLength int) []byte {
psk := sha256.Sum256(key)
return psk[:keyLength]
}
func SessionKey(psk []byte, salt []byte, keyLength int) []byte {
sessionKey := buf.Make(len(psk) + len(salt))
copy(sessionKey, psk)
copy(sessionKey[len(psk):], salt)
outKey := buf.Make(keyLength)
blake3.DeriveKey(outKey, "shadowsocks 2022 session subkey", sessionKey)
return outKey
}
func newAES(key []byte) cipher.Block {
block, err := aes.NewCipher(key)
common.Must(err)
return block
}
func newAESGCM(key []byte) cipher.AEAD {
block, err := aes.NewCipher(key)
common.Must(err)
aead, err := cipher.NewGCM(block)
common.Must(err)
return aead
}
func newChacha20Poly1305(key []byte) cipher.AEAD {
cipher, err := chacha20poly1305.New(key)
common.Must(err)
return cipher
}
func newXChacha20Poly1305(key []byte) cipher.AEAD {
cipher, err := chacha20poly1305.NewX(key)
common.Must(err)
return cipher
}
type Method struct {
name string
keySaltLength int
constructor func(key []byte) cipher.AEAD
blockConstructor func(key []byte) cipher.Block
udpCipher cipher.AEAD
udpBlockCipher cipher.Block
pskList [][]byte
pskHash []byte
secureRNG io.Reader
replayFilter replay.Filter
}
func (m *Method) Name() string {
return m.name
}
func (m *Method) KeyLength() int {
return m.keySaltLength
}
func (m *Method) DialConn(conn net.Conn, destination M.Socksaddr) (net.Conn, error) {
shadowsocksConn := &clientConn{
Method: m,
Conn: conn,
destination: destination,
}
return shadowsocksConn, shadowsocksConn.writeRequest(nil)
}
func (m *Method) DialEarlyConn(conn net.Conn, destination M.Socksaddr) net.Conn {
return &clientConn{
Method: m,
Conn: conn,
destination: destination,
}
}
func (m *Method) DialPacketConn(conn net.Conn) N.NetPacketConn {
return &clientPacketConn{m, conn, m.newUDPSession()}
}
type clientConn struct {
*Method
net.Conn
destination M.Socksaddr
requestSalt []byte
reader *shadowaead.Reader
writer *shadowaead.Writer
}
func (m *Method) writeExtendedIdentityHeaders(request *buf.Buffer, salt []byte) {
pskLen := len(m.pskList)
if pskLen < 2 {
return
}
for i, psk := range m.pskList {
keyMaterial := buf.Make(m.keySaltLength * 2)
copy(keyMaterial, psk)
copy(keyMaterial[m.keySaltLength:], salt)
_identitySubkey := buf.Make(m.keySaltLength)
identitySubkey := common.Dup(_identitySubkey)
blake3.DeriveKey(identitySubkey, "shadowsocks 2022 identity subkey", keyMaterial)
pskHash := m.pskHash[aes.BlockSize*i : aes.BlockSize*(i+1)]
header := request.Extend(16)
m.blockConstructor(identitySubkey).Encrypt(header, pskHash)
runtime.KeepAlive(_identitySubkey)
if i == pskLen-2 {
break
}
}
}
func (c *clientConn) writeRequest(payload []byte) error {
salt := buf.Make(c.keySaltLength)
common.Must1(io.ReadFull(c.secureRNG, salt))
key := SessionKey(c.pskList[len(c.pskList)-1], salt, c.keySaltLength)
writer := shadowaead.NewWriter(
c.Conn,
c.constructor(common.Dup(key)),
MaxPacketSize,
)
runtime.KeepAlive(key)
header := writer.Buffer()
header.Write(salt)
c.writeExtendedIdentityHeaders(header, salt)
var _fixedLengthBuffer [RequestHeaderFixedChunkLength]byte
fixedLengthBuffer := buf.With(common.Dup(_fixedLengthBuffer[:]))
common.Must(fixedLengthBuffer.WriteByte(HeaderTypeClient))
common.Must(binary.Write(fixedLengthBuffer, binary.BigEndian, uint64(time.Now().Unix())))
var paddingLen int
if len(payload) == 0 {
paddingLen = rand.Intn(MaxPaddingLength + 1)
}
variableLengthHeaderLen := M.SocksaddrSerializer.AddrPortLen(c.destination) + 2 + paddingLen + len(payload)
common.Must(binary.Write(fixedLengthBuffer, binary.BigEndian, uint16(variableLengthHeaderLen)))
writer.WriteChunk(header, fixedLengthBuffer.Slice())
runtime.KeepAlive(_fixedLengthBuffer)
_variableLengthBuffer := buf.Make(variableLengthHeaderLen)
variableLengthBuffer := buf.With(common.Dup(_variableLengthBuffer))
common.Must(M.SocksaddrSerializer.WriteAddrPort(variableLengthBuffer, c.destination))
common.Must(binary.Write(variableLengthBuffer, binary.BigEndian, uint16(paddingLen)))
if paddingLen > 0 {
common.Must1(io.CopyN(variableLengthBuffer, c.secureRNG, int64(paddingLen)))
} else {
common.Must1(variableLengthBuffer.Write(payload))
}
writer.WriteChunk(header, variableLengthBuffer.Slice())
runtime.KeepAlive(_variableLengthBuffer)
err := writer.BufferedWriter(header.Len()).Flush()
if err != nil {
return E.Cause(err, "client handshake")
}
c.requestSalt = salt
c.writer = writer
return nil
}
func (c *clientConn) readResponse() error {
if c.reader != nil {
return nil
}
_salt := buf.Make(c.keySaltLength)
salt := common.Dup(_salt)
_, err := io.ReadFull(c.Conn, salt)
if err != nil {
return err
}
if !c.replayFilter.Check(salt) {
return ErrSaltNotUnique
}
key := SessionKey(c.pskList[len(c.pskList)-1], salt, c.keySaltLength)
runtime.KeepAlive(_salt)
reader := shadowaead.NewReader(
c.Conn,
c.constructor(common.Dup(key)),
MaxPacketSize,
)
runtime.KeepAlive(key)
err = reader.ReadWithLength(uint16(1 + 8 + c.keySaltLength + 2))
if err != nil {
return E.Cause(err, "read response fixed length chunk")
}
headerType, err := rw.ReadByte(reader)
if err != nil {
return err
}
if headerType != HeaderTypeServer {
return E.Extend(ErrBadHeaderType, "expected ", HeaderTypeServer, ", got ", headerType)
}
var epoch uint64
err = binary.Read(reader, binary.BigEndian, &epoch)
if err != nil {
return err
}
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
if diff > 30 {
return E.Extend(ErrBadTimestamp, "received ", epoch, ", diff ", diff, "s")
}
_requestSalt := buf.Make(c.keySaltLength)
requestSalt := common.Dup(_requestSalt)
_, err = io.ReadFull(reader, requestSalt)
if err != nil {
return err
}
if bytes.Compare(requestSalt, c.requestSalt) > 0 {
return ErrBadRequestSalt
}
runtime.KeepAlive(_requestSalt)
var length uint16
err = binary.Read(reader, binary.BigEndian, &length)
if err != nil {
return err
}
err = reader.ReadWithLength(length)
if err != nil {
return err
}
c.requestSalt = nil
c.reader = reader
return nil
}
func (c *clientConn) Read(p []byte) (n int, err error) {
if err = c.readResponse(); err != nil {
return
}
return c.reader.Read(p)
}
func (c *clientConn) WriteTo(w io.Writer) (n int64, err error) {
if err = c.readResponse(); err != nil {
return
}
return c.reader.WriteTo(w)
}
func (c *clientConn) Write(p []byte) (n int, err error) {
if c.writer == nil {
err = c.writeRequest(p)
if err == nil {
n = len(p)
}
return
}
return c.writer.Write(p)
}
func (c *clientConn) ReadFrom(r io.Reader) (n int64, err error) {
if c.writer == nil {
return rw.ReadFrom0(c, r)
}
return c.writer.ReadFrom(r)
}
func (c *clientConn) Upstream() any {
return c.Conn
}
type clientPacketConn struct {
*Method
net.Conn
session *udpSession
}
func (c *clientPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
var hdrLen int
if c.udpCipher != nil {
hdrLen = PacketNonceSize
}
hdrLen += 16 // packet header
pskLen := len(c.pskList)
if c.udpCipher == nil && pskLen > 1 {
hdrLen += (pskLen - 1) * aes.BlockSize
}
hdrLen += 1 // header type
hdrLen += 8 // timestamp
hdrLen += 2 // padding length
hdrLen += M.SocksaddrSerializer.AddrPortLen(destination)
header := buf.With(buffer.ExtendHeader(hdrLen))
var dataIndex int
if c.udpCipher != nil {
common.Must1(header.ReadFullFrom(c.secureRNG, PacketNonceSize))
if pskLen > 1 {
panic("unsupported chacha extended header")
}
dataIndex = PacketNonceSize
} else {
dataIndex = aes.BlockSize
}
common.Must(
binary.Write(header, binary.BigEndian, c.session.sessionId),
binary.Write(header, binary.BigEndian, c.session.nextPacketId()),
)
if c.udpCipher == nil && pskLen > 1 {
for i, psk := range c.pskList {
dataIndex += aes.BlockSize
pskHash := c.pskHash[aes.BlockSize*i : aes.BlockSize*(i+1)]
identityHeader := header.Extend(aes.BlockSize)
for textI := 0; textI < aes.BlockSize; textI++ {
identityHeader[textI] = pskHash[textI] ^ header.Byte(textI)
}
c.blockConstructor(psk).Encrypt(identityHeader, identityHeader)
if i == pskLen-2 {
break
}
}
}
common.Must(
header.WriteByte(HeaderTypeClient),
binary.Write(header, binary.BigEndian, uint64(time.Now().Unix())),
binary.Write(header, binary.BigEndian, uint16(0)), // padding length
)
err := M.SocksaddrSerializer.WriteAddrPort(header, destination)
if err != nil {
return err
}
if c.udpCipher != nil {
c.udpCipher.Seal(buffer.Index(dataIndex), buffer.To(dataIndex), buffer.From(dataIndex), nil)
buffer.Extend(shadowaead.Overhead)
} else {
packetHeader := buffer.To(aes.BlockSize)
c.session.cipher.Seal(buffer.Index(dataIndex), packetHeader[4:16], buffer.From(dataIndex), nil)
buffer.Extend(shadowaead.Overhead)
c.udpBlockCipher.Encrypt(packetHeader, packetHeader)
}
return common.Error(c.Write(buffer.Bytes()))
}
func (c *clientPacketConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
n, err := c.Read(buffer.FreeBytes())
if err != nil {
return M.Socksaddr{}, err
}
buffer.Truncate(n)
var packetHeader []byte
if c.udpCipher != nil {
_, err = c.udpCipher.Open(buffer.Index(PacketNonceSize), buffer.To(PacketNonceSize), buffer.From(PacketNonceSize), nil)
if err != nil {
return M.Socksaddr{}, E.Cause(err, "decrypt packet")
}
buffer.Advance(PacketNonceSize)
buffer.Truncate(buffer.Len() - shadowaead.Overhead)
} else {
packetHeader = buffer.To(aes.BlockSize)
c.udpBlockCipher.Decrypt(packetHeader, packetHeader)
}
var sessionId, packetId uint64
err = binary.Read(buffer, binary.BigEndian, &sessionId)
if err != nil {
return M.Socksaddr{}, err
}
err = binary.Read(buffer, binary.BigEndian, &packetId)
if err != nil {
return M.Socksaddr{}, err
}
var remoteCipher cipher.AEAD
if packetHeader != nil {
if sessionId == c.session.remoteSessionId {
remoteCipher = c.session.remoteCipher
} else if sessionId == c.session.lastRemoteSessionId {
remoteCipher = c.session.lastRemoteCipher
} else {
key := SessionKey(c.pskList[len(c.pskList)-1], packetHeader[:8], c.keySaltLength)
remoteCipher = c.constructor(common.Dup(key))
runtime.KeepAlive(key)
}
_, err = remoteCipher.Open(buffer.Index(0), packetHeader[4:16], buffer.Bytes(), nil)
if err != nil {
return M.Socksaddr{}, E.Cause(err, "decrypt packet")
}
buffer.Truncate(buffer.Len() - shadowaead.Overhead)
}
var headerType byte
headerType, err = buffer.ReadByte()
if err != nil {
return M.Socksaddr{}, err
}
if headerType != HeaderTypeServer {
return M.Socksaddr{}, E.Extend(ErrBadHeaderType, "expected ", HeaderTypeServer, ", got ", headerType)
}
var epoch uint64
err = binary.Read(buffer, binary.BigEndian, &epoch)
if err != nil {
return M.Socksaddr{}, err
}
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
if diff > 30 {
return M.Socksaddr{}, E.Extend(ErrBadTimestamp, "received ", epoch, ", diff ", diff, "s")
}
if sessionId == c.session.remoteSessionId {
if !c.session.filter.ValidateCounter(packetId, math.MaxUint64) {
return M.Socksaddr{}, ErrPacketIdNotUnique
}
} else if sessionId == c.session.lastRemoteSessionId {
if !c.session.lastFilter.ValidateCounter(packetId, math.MaxUint64) {
return M.Socksaddr{}, ErrPacketIdNotUnique
}
remoteCipher = c.session.lastRemoteCipher
c.session.lastRemoteSeen = time.Now().Unix()
} else {
if c.session.remoteSessionId != 0 {
if time.Now().Unix()-c.session.lastRemoteSeen < 60 {
return M.Socksaddr{}, ErrTooManyServerSessions
} else {
c.session.lastRemoteSessionId = c.session.remoteSessionId
c.session.lastFilter = c.session.filter
c.session.lastRemoteSeen = time.Now().Unix()
c.session.lastRemoteCipher = c.session.remoteCipher
c.session.filter = wgReplay.Filter{}
}
}
c.session.remoteSessionId = sessionId
c.session.remoteCipher = remoteCipher
c.session.filter.ValidateCounter(packetId, math.MaxUint64)
}
var clientSessionId uint64
err = binary.Read(buffer, binary.BigEndian, &clientSessionId)
if err != nil {
return M.Socksaddr{}, err
}
if clientSessionId != c.session.sessionId {
return M.Socksaddr{}, ErrBadClientSessionId
}
var paddingLength uint16
err = binary.Read(buffer, binary.BigEndian, &paddingLength)
if err != nil {
return M.Socksaddr{}, E.Cause(err, "read padding length")
}
buffer.Advance(int(paddingLength))
destination, err := M.SocksaddrSerializer.ReadAddrPort(buffer)
if err != nil {
return M.Socksaddr{}, err
}
return destination, nil
}
func (c *clientPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
buffer := buf.With(p)
destination, err := c.ReadPacket(buffer)
if err != nil {
return
}
addr = destination.UDPAddr()
n = copy(p, buffer.Bytes())
return
}
func (c *clientPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
destination := M.SocksaddrFromNet(addr)
var overHead int
if c.udpCipher != nil {
overHead = PacketNonceSize + shadowaead.Overhead
} else {
overHead = shadowaead.Overhead
}
overHead += 16 // packet header
pskLen := len(c.pskList)
if c.udpCipher == nil && pskLen > 1 {
overHead += (pskLen - 1) * aes.BlockSize
}
overHead += 1 // header type
overHead += 8 // timestamp
overHead += 2 // padding length
overHead += M.SocksaddrSerializer.AddrPortLen(destination)
_buffer := buf.Make(overHead + len(p))
defer runtime.KeepAlive(_buffer)
buffer := buf.With(common.Dup(_buffer))
var dataIndex int
if c.udpCipher != nil {
common.Must1(buffer.ReadFullFrom(c.secureRNG, PacketNonceSize))
if pskLen > 1 {
panic("unsupported chacha extended header")
}
dataIndex = PacketNonceSize
} else {
dataIndex = aes.BlockSize
}
common.Must(
binary.Write(buffer, binary.BigEndian, c.session.sessionId),
binary.Write(buffer, binary.BigEndian, c.session.nextPacketId()),
)
if c.udpCipher == nil && pskLen > 1 {
for i, psk := range c.pskList {
dataIndex += aes.BlockSize
pskHash := c.pskHash[aes.BlockSize*i : aes.BlockSize*(i+1)]
identityHeader := buffer.Extend(aes.BlockSize)
for textI := 0; textI < aes.BlockSize; textI++ {
identityHeader[textI] = pskHash[textI] ^ buffer.Byte(textI)
}
c.blockConstructor(psk).Encrypt(identityHeader, identityHeader)
if i == pskLen-2 {
break
}
}
}
common.Must(
buffer.WriteByte(HeaderTypeClient),
binary.Write(buffer, binary.BigEndian, uint64(time.Now().Unix())),
binary.Write(buffer, binary.BigEndian, uint16(0)), // padding length
)
err = M.SocksaddrSerializer.WriteAddrPort(buffer, destination)
if err != nil {
return
}
if c.udpCipher != nil {
c.udpCipher.Seal(buffer.Index(dataIndex), buffer.To(dataIndex), buffer.From(dataIndex), nil)
buffer.Extend(shadowaead.Overhead)
} else {
packetHeader := buffer.To(aes.BlockSize)
c.session.cipher.Seal(buffer.Index(dataIndex), packetHeader[4:16], buffer.From(dataIndex), nil)
buffer.Extend(shadowaead.Overhead)
c.udpBlockCipher.Encrypt(packetHeader, packetHeader)
}
err = common.Error(c.Write(buffer.Bytes()))
if err != nil {
return
}
return len(p), nil
}
type udpSession struct {
headerType byte
sessionId uint64
packetId uint64
remoteSessionId uint64
lastRemoteSessionId uint64
lastRemoteSeen int64
cipher cipher.AEAD
remoteCipher cipher.AEAD
lastRemoteCipher cipher.AEAD
filter wgReplay.Filter
lastFilter wgReplay.Filter
}
func (s *udpSession) nextPacketId() uint64 {
return atomic.AddUint64(&s.packetId, 1)
}
func (m *Method) newUDPSession() *udpSession {
session := &udpSession{}
common.Must(binary.Read(m.secureRNG, binary.BigEndian, &session.sessionId))
session.packetId--
if m.udpCipher == nil {
sessionId := make([]byte, 8)
binary.BigEndian.PutUint64(sessionId, session.sessionId)
key := SessionKey(m.pskList[len(m.pskList)-1], sessionId, m.keySaltLength)
session.cipher = m.constructor(common.Dup(key))
runtime.KeepAlive(key)
}
return session
}
func (c *clientPacketConn) Upstream() any {
return c.Conn
}

View file

@ -1,233 +0,0 @@
package shadowaead_2022
import (
"context"
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"io"
"net"
"os"
"runtime"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
"github.com/sagernet/sing/common/cache"
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/udpnat"
"github.com/sagernet/sing/protocol/shadowsocks"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead"
"lukechampine.com/blake3"
)
type Relay[U comparable] struct {
name string
secureRNG io.Reader
keySaltLength int
handler shadowsocks.Handler
constructor func(key []byte) cipher.AEAD
blockConstructor func(key []byte) cipher.Block
udpBlockCipher cipher.Block
iPSK []byte
uPSKHash map[U][aes.BlockSize]byte
uPSKHashR map[[aes.BlockSize]byte]U
uDestination map[U]M.Socksaddr
uCipher map[U]cipher.Block
udpNat *udpnat.Service[uint64]
udpSessions *cache.LruCache[uint64, *relayUDPSession]
}
func (s *Relay[U]) AddUser(user U, key []byte, destination M.Socksaddr) error {
if len(key) < s.keySaltLength {
return shadowsocks.ErrBadKey
} else if len(key) > s.keySaltLength {
key = Key(key, s.keySaltLength)
}
var uPSKHash [aes.BlockSize]byte
hash512 := blake3.Sum512(key)
copy(uPSKHash[:], hash512[:])
if oldHash, loaded := s.uPSKHash[user]; loaded {
delete(s.uPSKHashR, oldHash)
}
s.uPSKHash[user] = uPSKHash
s.uPSKHashR[uPSKHash] = user
s.uDestination[user] = destination
s.uCipher[user] = s.blockConstructor(key)
return nil
}
func (s *Relay[U]) RemoveUser(user U) {
if hash, loaded := s.uPSKHash[user]; loaded {
delete(s.uPSKHashR, hash)
}
delete(s.uPSKHash, user)
delete(s.uCipher, user)
}
func NewRelay[U comparable](method string, psk []byte, secureRNG io.Reader, udpTimeout int64, handler shadowsocks.Handler) (*Relay[U], error) {
s := &Relay[U]{
name: method,
secureRNG: secureRNG,
handler: handler,
uPSKHash: make(map[U][aes.BlockSize]byte),
uPSKHashR: make(map[[aes.BlockSize]byte]U),
uDestination: make(map[U]M.Socksaddr),
uCipher: make(map[U]cipher.Block),
udpNat: udpnat.New[uint64](udpTimeout, handler),
udpSessions: cache.New(
cache.WithAge[uint64, *relayUDPSession](udpTimeout),
cache.WithUpdateAgeOnGet[uint64, *relayUDPSession](),
),
}
switch method {
case "2022-blake3-aes-128-gcm":
s.keySaltLength = 16
s.constructor = newAESGCM
s.blockConstructor = newAES
case "2022-blake3-aes-256-gcm":
s.keySaltLength = 32
s.constructor = newAESGCM
s.blockConstructor = newAES
default:
return nil, os.ErrInvalid
}
if len(psk) != s.keySaltLength {
if len(psk) < s.keySaltLength {
return nil, shadowsocks.ErrBadKey
} else {
psk = Key(psk, s.keySaltLength)
}
}
s.udpBlockCipher = s.blockConstructor(psk)
return s, nil
}
func (s *Relay[U]) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
err := s.newConnection(ctx, conn, metadata)
if err != nil {
err = &shadowsocks.ServerConnError{Conn: conn, Source: metadata.Source, Cause: err}
}
return err
}
func (s *Relay[U]) newConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
_requestHeader := buf.StackNew()
defer runtime.KeepAlive(_requestHeader)
requestHeader := common.Dup(_requestHeader)
n, err := requestHeader.ReadFrom(conn)
if err != nil {
return err
} else if int(n) < s.keySaltLength+aes.BlockSize {
return shadowaead.ErrBadHeader
}
requestSalt := requestHeader.To(s.keySaltLength)
var _eiHeader [aes.BlockSize]byte
eiHeader := common.Dup(_eiHeader[:])
copy(eiHeader, requestHeader.Range(s.keySaltLength, s.keySaltLength+aes.BlockSize))
keyMaterial := buf.Make(s.keySaltLength * 2)
copy(keyMaterial, s.iPSK)
copy(keyMaterial[s.keySaltLength:], requestSalt)
_identitySubkey := buf.Make(s.keySaltLength)
identitySubkey := common.Dup(_identitySubkey)
blake3.DeriveKey(identitySubkey, "shadowsocks 2022 identity subkey", keyMaterial)
s.blockConstructor(identitySubkey).Decrypt(eiHeader, eiHeader)
runtime.KeepAlive(_identitySubkey)
var user U
if u, loaded := s.uPSKHashR[_eiHeader]; loaded {
user = u
} else {
return E.New("invalid request")
}
runtime.KeepAlive(_eiHeader)
copy(requestHeader.Range(aes.BlockSize, aes.BlockSize+s.keySaltLength), requestHeader.To(s.keySaltLength))
requestHeader.Advance(aes.BlockSize)
ctx = shadowsocks.UserContext[U]{
ctx,
user,
}
metadata.Protocol = "shadowsocks-relay"
metadata.Destination = s.uDestination[user]
conn = &bufio.BufferedConn{
Conn: conn,
Buffer: requestHeader,
}
return s.handler.NewConnection(ctx, conn, metadata)
}
func (s *Relay[U]) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
err := s.newPacket(ctx, conn, buffer, metadata)
if err != nil {
err = &shadowsocks.ServerPacketError{Source: metadata.Source, Cause: err}
}
return err
}
func (s *Relay[U]) newPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
packetHeader := buffer.To(aes.BlockSize)
s.udpBlockCipher.Decrypt(packetHeader, packetHeader)
sessionId := binary.BigEndian.Uint64(packetHeader)
var _eiHeader [aes.BlockSize]byte
eiHeader := common.Dup(_eiHeader[:])
s.udpBlockCipher.Decrypt(eiHeader, buffer.Range(aes.BlockSize, 2*aes.BlockSize))
for i := range eiHeader {
eiHeader[i] = eiHeader[i] ^ packetHeader[i]
}
var user U
if u, loaded := s.uPSKHashR[_eiHeader]; loaded {
user = u
} else {
return E.New("invalid request")
}
session, _ := s.udpSessions.LoadOrStore(sessionId, func() *relayUDPSession {
return new(relayUDPSession)
})
session.sourceAddr = metadata.Source
s.uCipher[user].Encrypt(packetHeader, packetHeader)
copy(buffer.Range(aes.BlockSize, 2*aes.BlockSize), packetHeader)
buffer.Advance(aes.BlockSize)
metadata.Protocol = "shadowsocks-relay"
metadata.Destination = s.uDestination[user]
s.udpNat.NewContextPacket(ctx, sessionId, func() (context.Context, N.PacketWriter) {
return &shadowsocks.UserContext[U]{
ctx,
user,
}, &relayPacketWriter[U]{conn, session}
}, buffer, metadata)
return nil
}
type relayUDPSession struct {
sourceAddr M.Socksaddr
}
type relayPacketWriter[U comparable] struct {
N.PacketConn
session *relayUDPSession
}
func (w *relayPacketWriter[U]) WritePacket(buffer *buf.Buffer, _ M.Socksaddr) error {
return w.PacketConn.WritePacket(buffer, w.session.sourceAddr)
}

View file

@ -1,474 +0,0 @@
package shadowaead_2022
import (
"context"
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"io"
"math"
"net"
"os"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/cache"
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/replay"
"github.com/sagernet/sing/common/rw"
"github.com/sagernet/sing/common/udpnat"
"github.com/sagernet/sing/protocol/shadowsocks"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead"
wgReplay "golang.zx2c4.com/wireguard/replay"
)
var (
ErrSaltNotUnique = E.New("bad request: salt not unique")
ErrNoPadding = E.New("bad request: missing payload or padding")
ErrBadPadding = E.New("bad request: damaged padding")
)
type Service struct {
name string
secureRNG io.Reader
keySaltLength int
handler shadowsocks.Handler
constructor func(key []byte) cipher.AEAD
blockConstructor func(key []byte) cipher.Block
udpCipher cipher.AEAD
udpBlockCipher cipher.Block
psk []byte
replayFilter replay.Filter
udpNat *udpnat.Service[uint64]
udpSessions *cache.LruCache[uint64, *serverUDPSession]
}
func NewService(method string, psk []byte, password string, secureRNG io.Reader, udpTimeout int64, handler shadowsocks.Handler) (shadowsocks.Service, error) {
s := &Service{
name: method,
secureRNG: secureRNG,
handler: handler,
replayFilter: replay.NewCuckoo(60),
udpNat: udpnat.New[uint64](udpTimeout, handler),
udpSessions: cache.New[uint64, *serverUDPSession](
cache.WithAge[uint64, *serverUDPSession](udpTimeout),
cache.WithUpdateAgeOnGet[uint64, *serverUDPSession](),
),
}
switch method {
case "2022-blake3-aes-128-gcm":
s.keySaltLength = 16
s.constructor = newAESGCM
s.blockConstructor = newAES
case "2022-blake3-aes-256-gcm":
s.keySaltLength = 32
s.constructor = newAESGCM
s.blockConstructor = newAES
case "2022-blake3-chacha20-poly1305":
s.keySaltLength = 32
s.constructor = newChacha20Poly1305
default:
return nil, os.ErrInvalid
}
if len(psk) != s.keySaltLength {
if len(psk) < s.keySaltLength {
return nil, shadowsocks.ErrBadKey
} else if len(psk) > s.keySaltLength {
psk = Key(psk, s.keySaltLength)
} else if password == "" {
return nil, ErrMissingPasswordPSK
} else {
psk = Key([]byte(password), s.keySaltLength)
}
}
switch method {
case "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm":
s.udpBlockCipher = newAES(psk)
case "2022-blake3-chacha20-poly1305":
s.udpCipher = newXChacha20Poly1305(psk)
}
s.psk = psk
return s, nil
}
func (s *Service) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
err := s.newConnection(ctx, conn, metadata)
if err != nil {
err = &shadowsocks.ServerConnError{Conn: conn, Source: metadata.Source, Cause: err}
}
return err
}
func (s *Service) newConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
header := buf.Make(s.keySaltLength + shadowaead.Overhead + RequestHeaderFixedChunkLength)
n, err := conn.Read(header)
if err != nil {
return E.Cause(err, "read header")
} else if n < len(header) {
return shadowaead.ErrBadHeader
}
requestSalt := header[:s.keySaltLength]
if !s.replayFilter.Check(requestSalt) {
return ErrSaltNotUnique
}
requestKey := SessionKey(s.psk, requestSalt, s.keySaltLength)
reader := shadowaead.NewReader(
conn,
s.constructor(common.Dup(requestKey)),
MaxPacketSize,
)
runtime.KeepAlive(requestKey)
err = reader.ReadChunk(header[s.keySaltLength:])
if err != nil {
return err
}
headerType, err := reader.ReadByte()
if err != nil {
return E.Cause(err, "read header")
}
if headerType != HeaderTypeClient {
return E.Extend(ErrBadHeaderType, "expected ", HeaderTypeClient, ", got ", headerType)
}
var epoch uint64
err = binary.Read(reader, binary.BigEndian, &epoch)
if err != nil {
return err
}
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
if diff > 30 {
return E.Extend(ErrBadTimestamp, "received ", epoch, ", diff ", diff, "s")
}
var length uint16
err = binary.Read(reader, binary.BigEndian, &length)
if err != nil {
return err
}
err = reader.ReadWithLength(length)
if err != nil {
return err
}
destination, err := M.SocksaddrSerializer.ReadAddrPort(reader)
if err != nil {
return err
}
var paddingLen uint16
err = binary.Read(reader, binary.BigEndian, &paddingLen)
if err != nil {
return err
}
if uint16(reader.Cached()) < paddingLen {
return ErrNoPadding
}
if paddingLen > 0 {
err = reader.Discard(int(paddingLen))
if err != nil {
return E.Cause(err, "discard padding")
}
} else if reader.Cached() == 0 {
return ErrNoPadding
}
metadata.Protocol = "shadowsocks"
metadata.Destination = destination
return s.handler.NewConnection(ctx, &serverConn{
Service: s,
Conn: conn,
uPSK: s.psk,
reader: reader,
requestSalt: requestSalt,
}, metadata)
}
type serverConn struct {
*Service
net.Conn
uPSK []byte
access sync.Mutex
reader *shadowaead.Reader
writer *shadowaead.Writer
requestSalt []byte
}
func (c *serverConn) writeResponse(payload []byte) (n int, err error) {
_salt := buf.Make(c.keySaltLength)
salt := common.Dup(_salt[:])
common.Must1(io.ReadFull(c.secureRNG, salt))
key := SessionKey(c.uPSK, salt, c.keySaltLength)
runtime.KeepAlive(_salt)
writer := shadowaead.NewWriter(
c.Conn,
c.constructor(common.Dup(key)),
MaxPacketSize,
)
runtime.KeepAlive(key)
header := writer.Buffer()
header.Write(salt)
_headerFixedChunk := buf.Make(1 + 8 + c.keySaltLength + 2)
headerFixedChunk := buf.With(common.Dup(_headerFixedChunk))
common.Must(headerFixedChunk.WriteByte(HeaderTypeServer))
common.Must(binary.Write(headerFixedChunk, binary.BigEndian, uint64(time.Now().Unix())))
common.Must1(headerFixedChunk.Write(c.requestSalt))
common.Must(binary.Write(headerFixedChunk, binary.BigEndian, uint16(len(payload))))
writer.WriteChunk(header, headerFixedChunk.Slice())
runtime.KeepAlive(_headerFixedChunk)
c.requestSalt = nil
if len(payload) > 0 {
writer.WriteChunk(header, payload)
}
err = writer.BufferedWriter(header.Len()).Flush()
if err != nil {
return
}
c.writer = writer
n = len(payload)
return
}
func (c *serverConn) Write(p []byte) (n int, err error) {
if c.writer != nil {
return c.writer.Write(p)
}
c.access.Lock()
if c.writer != nil {
c.access.Unlock()
return c.writer.Write(p)
}
defer c.access.Unlock()
return c.writeResponse(p)
}
func (c *serverConn) ReadFrom(r io.Reader) (n int64, err error) {
if c.writer == nil {
return rw.ReadFrom0(c, r)
}
return c.writer.ReadFrom(r)
}
func (c *serverConn) WriteTo(w io.Writer) (n int64, err error) {
return c.reader.WriteTo(w)
}
func (c *serverConn) Upstream() any {
return c.Conn
}
func (s *Service) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
err := s.newPacket(ctx, conn, buffer, metadata)
if err != nil {
err = &shadowsocks.ServerPacketError{Source: metadata.Source, Cause: err}
}
return err
}
func (s *Service) newPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
var packetHeader []byte
if s.udpCipher != nil {
_, err := s.udpCipher.Open(buffer.Index(PacketNonceSize), buffer.To(PacketNonceSize), buffer.From(PacketNonceSize), nil)
if err != nil {
return E.Cause(err, "decrypt packet header")
}
buffer.Advance(PacketNonceSize)
buffer.Truncate(buffer.Len() - shadowaead.Overhead)
} else {
packetHeader = buffer.To(aes.BlockSize)
s.udpBlockCipher.Decrypt(packetHeader, packetHeader)
}
var sessionId, packetId uint64
err := binary.Read(buffer, binary.BigEndian, &sessionId)
if err != nil {
return err
}
err = binary.Read(buffer, binary.BigEndian, &packetId)
if err != nil {
return err
}
session, loaded := s.udpSessions.LoadOrStore(sessionId, s.newUDPSession)
if !loaded {
session.remoteSessionId = sessionId
if packetHeader != nil {
key := SessionKey(s.psk, packetHeader[:8], s.keySaltLength)
session.remoteCipher = s.constructor(common.Dup(key))
runtime.KeepAlive(key)
}
}
goto process
returnErr:
if !loaded {
s.udpSessions.Delete(sessionId)
}
return err
process:
if !session.filter.ValidateCounter(packetId, math.MaxUint64) {
err = ErrPacketIdNotUnique
goto returnErr
}
if packetHeader != nil {
_, err = session.remoteCipher.Open(buffer.Index(0), packetHeader[4:16], buffer.Bytes(), nil)
if err != nil {
err = E.Cause(err, "decrypt packet")
goto returnErr
}
buffer.Truncate(buffer.Len() - shadowaead.Overhead)
}
var headerType byte
headerType, err = buffer.ReadByte()
if err != nil {
err = E.Cause(err, "decrypt packet")
goto returnErr
}
if headerType != HeaderTypeClient {
err = E.Extend(ErrBadHeaderType, "expected ", HeaderTypeClient, ", got ", headerType)
goto returnErr
}
var epoch uint64
err = binary.Read(buffer, binary.BigEndian, &epoch)
if err != nil {
goto returnErr
}
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
if diff > 30 {
err = E.Extend(ErrBadTimestamp, "received ", epoch, ", diff ", diff, "s")
goto returnErr
}
var paddingLength uint16
err = binary.Read(buffer, binary.BigEndian, &paddingLength)
if err != nil {
err = E.Cause(err, "read padding length")
goto returnErr
}
buffer.Advance(int(paddingLength))
destination, err := M.SocksaddrSerializer.ReadAddrPort(buffer)
if err != nil {
goto returnErr
}
metadata.Destination = destination
session.remoteAddr = metadata.Source
s.udpNat.NewPacket(ctx, sessionId, func() N.PacketWriter {
return &serverPacketWriter{s, conn, session}
}, buffer, metadata)
return nil
}
type serverPacketWriter struct {
*Service
N.PacketConn
session *serverUDPSession
}
func (w *serverPacketWriter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
var hdrLen int
if w.udpCipher != nil {
hdrLen = PacketNonceSize
}
hdrLen += 16 // packet header
hdrLen += 1 // header type
hdrLen += 8 // timestamp
hdrLen += 8 // remote session id
hdrLen += 2 // padding length
hdrLen += M.SocksaddrSerializer.AddrPortLen(destination)
header := buf.With(buffer.ExtendHeader(hdrLen))
var dataIndex int
if w.udpCipher != nil {
common.Must1(header.ReadFullFrom(w.secureRNG, PacketNonceSize))
dataIndex = PacketNonceSize
} else {
dataIndex = aes.BlockSize
}
common.Must(
binary.Write(header, binary.BigEndian, w.session.sessionId),
binary.Write(header, binary.BigEndian, w.session.nextPacketId()),
header.WriteByte(HeaderTypeServer),
binary.Write(header, binary.BigEndian, uint64(time.Now().Unix())),
binary.Write(header, binary.BigEndian, w.session.remoteSessionId),
binary.Write(header, binary.BigEndian, uint16(0)), // padding length
)
err := M.SocksaddrSerializer.WriteAddrPort(header, destination)
if err != nil {
return err
}
if w.udpCipher != nil {
w.udpCipher.Seal(buffer.Index(dataIndex), buffer.To(dataIndex), buffer.From(dataIndex), nil)
buffer.Extend(shadowaead.Overhead)
} else {
packetHeader := buffer.To(aes.BlockSize)
w.session.cipher.Seal(buffer.Index(dataIndex), packetHeader[4:16], buffer.From(dataIndex), nil)
buffer.Extend(shadowaead.Overhead)
w.udpBlockCipher.Encrypt(packetHeader, packetHeader)
}
return w.PacketConn.WritePacket(buffer, w.session.remoteAddr)
}
type serverUDPSession struct {
sessionId uint64
remoteSessionId uint64
remoteAddr M.Socksaddr
packetId uint64
cipher cipher.AEAD
remoteCipher cipher.AEAD
filter wgReplay.Filter
}
func (s *serverUDPSession) nextPacketId() uint64 {
return atomic.AddUint64(&s.packetId, 1)
}
func (m *Service) newUDPSession() *serverUDPSession {
session := &serverUDPSession{}
common.Must(binary.Read(m.secureRNG, binary.BigEndian, &session.sessionId))
session.packetId--
if m.udpCipher == nil {
sessionId := make([]byte, 8)
binary.BigEndian.PutUint64(sessionId, session.sessionId)
key := SessionKey(m.psk, sessionId, m.keySaltLength)
session.cipher = m.constructor(common.Dup(key))
runtime.KeepAlive(key)
}
return session
}

View file

@ -1,337 +0,0 @@
package shadowaead_2022
import (
"context"
"crypto/aes"
"encoding/binary"
"io"
"math"
"net"
"os"
"runtime"
"time"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
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/rw"
"github.com/sagernet/sing/protocol/shadowsocks"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead"
"lukechampine.com/blake3"
)
type MultiService[U comparable] struct {
*Service
uPSK map[U][]byte
uPSKHash map[U][aes.BlockSize]byte
uPSKHashR map[[aes.BlockSize]byte]U
}
func (s *MultiService[U]) AddUser(user U, key []byte) error {
if len(key) < s.keySaltLength {
return shadowsocks.ErrBadKey
} else if len(key) > s.keySaltLength {
key = Key(key, s.keySaltLength)
}
var uPSKHash [aes.BlockSize]byte
hash512 := blake3.Sum512(key)
copy(uPSKHash[:], hash512[:])
if oldHash, loaded := s.uPSKHash[user]; loaded {
delete(s.uPSKHashR, oldHash)
}
s.uPSKHash[user] = uPSKHash
s.uPSKHashR[uPSKHash] = user
s.uPSK[user] = key
return nil
}
func (s *MultiService[U]) RemoveUser(user U) {
if hash, loaded := s.uPSKHash[user]; loaded {
delete(s.uPSKHashR, hash)
}
delete(s.uPSK, user)
delete(s.uPSKHash, user)
}
func NewMultiService[U comparable](method string, iPSK []byte, secureRNG io.Reader, udpTimeout int64, handler shadowsocks.Handler) (*MultiService[U], error) {
switch method {
case "2022-blake3-aes-128-gcm":
case "2022-blake3-aes-256-gcm":
default:
return nil, os.ErrInvalid
}
ss, err := NewService(method, iPSK, "", secureRNG, udpTimeout, handler)
if err != nil {
return nil, err
}
s := &MultiService[U]{
Service: ss.(*Service),
uPSK: make(map[U][]byte),
uPSKHash: make(map[U][aes.BlockSize]byte),
uPSKHashR: make(map[[aes.BlockSize]byte]U),
}
return s, nil
}
func (s *MultiService[U]) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
err := s.newConnection(ctx, conn, metadata)
if err != nil {
err = &shadowsocks.ServerConnError{Conn: conn, Source: metadata.Source, Cause: err}
}
return err
}
func (s *MultiService[U]) newConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
requestHeader := make([]byte, s.keySaltLength+aes.BlockSize+shadowaead.Overhead+RequestHeaderFixedChunkLength)
n, err := conn.Read(requestHeader)
if err != nil {
return err
} else if n < len(requestHeader) {
return shadowaead.ErrBadHeader
}
requestSalt := requestHeader[:s.keySaltLength]
if !s.replayFilter.Check(requestSalt) {
return ErrSaltNotUnique
}
var _eiHeader [aes.BlockSize]byte
eiHeader := common.Dup(_eiHeader[:])
copy(eiHeader, requestHeader[s.keySaltLength:s.keySaltLength+aes.BlockSize])
keyMaterial := buf.Make(s.keySaltLength * 2)
copy(keyMaterial, s.psk)
copy(keyMaterial[s.keySaltLength:], requestSalt)
_identitySubkey := buf.Make(s.keySaltLength)
identitySubkey := common.Dup(_identitySubkey)
blake3.DeriveKey(identitySubkey, "shadowsocks 2022 identity subkey", keyMaterial)
s.blockConstructor(identitySubkey).Decrypt(eiHeader, eiHeader)
runtime.KeepAlive(_identitySubkey)
var user U
var uPSK []byte
if u, loaded := s.uPSKHashR[_eiHeader]; loaded {
user = u
uPSK = s.uPSK[u]
} else {
return E.New("invalid request")
}
runtime.KeepAlive(_eiHeader)
requestKey := SessionKey(uPSK, requestSalt, s.keySaltLength)
reader := shadowaead.NewReader(
conn,
s.constructor(common.Dup(requestKey)),
MaxPacketSize,
)
err = reader.ReadChunk(requestHeader[s.keySaltLength+aes.BlockSize:])
if err != nil {
return err
}
headerType, err := rw.ReadByte(reader)
if err != nil {
return E.Cause(err, "read header")
}
if headerType != HeaderTypeClient {
return E.Extend(ErrBadHeaderType, "expected ", HeaderTypeClient, ", got ", headerType)
}
var epoch uint64
err = binary.Read(reader, binary.BigEndian, &epoch)
if err != nil {
return E.Cause(err, "read timestamp")
}
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
if diff > 30 {
return E.Extend(ErrBadTimestamp, "received ", epoch, ", diff ", diff, "s")
}
var length uint16
err = binary.Read(reader, binary.BigEndian, &length)
if err != nil {
return E.Cause(err, "read length")
}
err = reader.ReadWithLength(length)
if err != nil {
return err
}
destination, err := M.SocksaddrSerializer.ReadAddrPort(reader)
if err != nil {
return E.Cause(err, "read destination")
}
var paddingLen uint16
err = binary.Read(reader, binary.BigEndian, &paddingLen)
if err != nil {
return E.Cause(err, "read padding length")
}
if reader.Cached() < int(paddingLen) {
return ErrBadPadding
} else if paddingLen > 0 {
err = reader.Discard(int(paddingLen))
if err != nil {
return E.Cause(err, "discard padding")
}
} else if reader.Cached() == 0 {
return ErrNoPadding
}
var userCtx shadowsocks.UserContext[U]
userCtx.Context = ctx
userCtx.User = user
metadata.Protocol = "shadowsocks"
metadata.Destination = destination
return s.handler.NewConnection(&userCtx, &serverConn{
Service: s.Service,
Conn: conn,
uPSK: uPSK,
reader: reader,
requestSalt: requestSalt,
}, metadata)
}
func (s *MultiService[U]) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
err := s.newPacket(ctx, conn, buffer, metadata)
if err != nil {
err = &shadowsocks.ServerPacketError{Source: metadata.Source, Cause: err}
}
return err
}
func (s *MultiService[U]) newPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata M.Metadata) error {
packetHeader := buffer.To(aes.BlockSize)
s.udpBlockCipher.Decrypt(packetHeader, packetHeader)
var _eiHeader [aes.BlockSize]byte
eiHeader := common.Dup(_eiHeader[:])
s.udpBlockCipher.Decrypt(eiHeader, buffer.Range(aes.BlockSize, 2*aes.BlockSize))
for i := range eiHeader {
eiHeader[i] = eiHeader[i] ^ packetHeader[i]
}
var user U
var uPSK []byte
if u, loaded := s.uPSKHashR[_eiHeader]; loaded {
user = u
uPSK = s.uPSK[u]
} else {
return E.New("invalid request")
}
var sessionId, packetId uint64
err := binary.Read(buffer, binary.BigEndian, &sessionId)
if err != nil {
return err
}
err = binary.Read(buffer, binary.BigEndian, &packetId)
if err != nil {
return err
}
session, loaded := s.udpSessions.LoadOrStore(sessionId, func() *serverUDPSession {
return s.newUDPSession(uPSK)
})
if !loaded {
session.remoteSessionId = sessionId
key := SessionKey(uPSK, packetHeader[:8], s.keySaltLength)
session.remoteCipher = s.constructor(common.Dup(key))
runtime.KeepAlive(key)
}
goto process
returnErr:
if !loaded {
s.udpSessions.Delete(sessionId)
}
return err
process:
if !session.filter.ValidateCounter(packetId, math.MaxUint64) {
err = ErrPacketIdNotUnique
goto returnErr
}
if packetHeader != nil {
_, err = session.remoteCipher.Open(buffer.Index(0), packetHeader[4:16], buffer.Bytes(), nil)
if err != nil {
err = E.Cause(err, "decrypt packet")
goto returnErr
}
buffer.Truncate(buffer.Len() - shadowaead.Overhead)
}
var headerType byte
headerType, err = buffer.ReadByte()
if err != nil {
err = E.Cause(err, "decrypt packet")
goto returnErr
}
if headerType != HeaderTypeClient {
err = E.Extend(ErrBadHeaderType, "expected ", HeaderTypeClient, ", got ", headerType)
goto returnErr
}
var epoch uint64
err = binary.Read(buffer, binary.BigEndian, &epoch)
if err != nil {
goto returnErr
}
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
if diff > 30 {
err = E.Extend(ErrBadTimestamp, "received ", epoch, ", diff ", diff, "s")
goto returnErr
}
var paddingLength uint16
err = binary.Read(buffer, binary.BigEndian, &paddingLength)
if err != nil {
err = E.Cause(err, "read padding length")
goto returnErr
}
buffer.Advance(int(paddingLength))
destination, err := M.SocksaddrSerializer.ReadAddrPort(buffer)
if err != nil {
goto returnErr
}
metadata.Destination = destination
session.remoteAddr = metadata.Source
s.udpNat.NewContextPacket(ctx, sessionId, func() (context.Context, N.PacketWriter) {
return &shadowsocks.UserContext[U]{
ctx,
user,
}, &serverPacketWriter{s.Service, conn, session}
}, buffer, metadata)
return nil
}
func (m *MultiService[U]) newUDPSession(uPSK []byte) *serverUDPSession {
session := &serverUDPSession{}
common.Must(binary.Read(m.secureRNG, binary.BigEndian, &session.sessionId))
session.packetId--
sessionId := make([]byte, 8)
binary.BigEndian.PutUint64(sessionId, session.sessionId)
key := SessionKey(uPSK, sessionId, m.keySaltLength)
session.cipher = m.constructor(common.Dup(key))
runtime.KeepAlive(key)
return session
}

View file

@ -1,75 +0,0 @@
package shadowaead_2022_test
import (
"context"
"net"
"sync"
"testing"
"github.com/sagernet/sing/common"
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/random"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead_2022"
)
func TestMultiService(t *testing.T) {
method := "2022-blake3-aes-128-gcm"
var iPSK [16]byte
random.Default.Read(iPSK[:])
var wg sync.WaitGroup
multiService, err := shadowaead_2022.NewMultiService[string](method, iPSK[:], random.Default, 500, &multiHandler{t, &wg})
if err != nil {
t.Fatal(err)
}
var uPSK [16]byte
random.Default.Read(uPSK[:])
multiService.AddUser("my user", uPSK[:])
client, err := shadowaead_2022.New(method, [][]byte{iPSK[:], uPSK[:]}, "", random.Default)
if err != nil {
t.Fatal(err)
}
wg.Add(1)
serverConn, clientConn := net.Pipe()
defer common.Close(serverConn, clientConn)
go func() {
err := multiService.NewConnection(context.Background(), serverConn, M.Metadata{})
if err != nil {
serverConn.Close()
t.Error(E.Cause(err, "server"))
return
}
}()
_, err = client.DialConn(clientConn, M.ParseSocksaddr("test.com:443"))
if err != nil {
t.Fatal(err)
}
wg.Wait()
}
type multiHandler struct {
t *testing.T
wg *sync.WaitGroup
}
func (h *multiHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
if metadata.Destination.String() != "test.com:443" {
h.t.Error("bad destination")
}
h.wg.Done()
return nil
}
func (h *multiHandler) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
return nil
}
func (h *multiHandler) HandleError(err error) {
h.t.Error(err)
}

View file

@ -1,49 +0,0 @@
package shadowaead_2022_test
import (
"context"
"net"
"sync"
"testing"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/common/random"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead_2022"
)
func TestService(t *testing.T) {
method := "2022-blake3-aes-128-gcm"
var psk [16]byte
random.Default.Read(psk[:])
var wg sync.WaitGroup
service, err := shadowaead_2022.NewService(method, psk[:], "", random.Default, 500, &multiHandler{t, &wg})
if err != nil {
t.Fatal(err)
}
client, err := shadowaead_2022.New(method, [][]byte{psk[:]}, "", random.Default)
if err != nil {
t.Fatal(err)
}
wg.Add(1)
serverConn, clientConn := net.Pipe()
defer common.Close(serverConn, clientConn)
go func() {
err := service.NewConnection(context.Background(), serverConn, M.Metadata{})
if err != nil {
serverConn.Close()
t.Error(E.Cause(err, "server"))
return
}
}()
_, err = client.DialConn(clientConn, M.ParseSocksaddr("test.com:443"))
if err != nil {
t.Fatal(err)
}
wg.Wait()
}

View file

@ -1,56 +0,0 @@
package shadowimpl
import (
"encoding/base64"
"io"
"strings"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/protocol/shadowsocks"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead_2022"
"github.com/sagernet/sing/protocol/shadowsocks/shadowstream"
)
func FetchMethod(method string, key string, password string, secureRNG io.Reader) (shadowsocks.Method, error) {
if method == "none" {
return shadowsocks.NewNone(), nil
} else if common.Contains(shadowstream.List, method) {
var keyBytes []byte
if key != "" {
kb, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return nil, E.Cause(err, "decode key")
}
keyBytes = kb
}
return shadowstream.New(method, keyBytes, password, secureRNG)
} else if common.Contains(shadowaead.List, method) {
var keyBytes []byte
if key != "" {
kb, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return nil, E.Cause(err, "decode key")
}
keyBytes = kb
}
return shadowaead.New(method, keyBytes, password, secureRNG)
} else if common.Contains(shadowaead_2022.List, method) {
var pskList [][]byte
if key != "" {
keyStrList := strings.Split(key, ":")
pskList = make([][]byte, len(keyStrList))
for i, keyStr := range keyStrList {
kb, err := base64.StdEncoding.DecodeString(keyStr)
if err != nil {
return nil, E.Cause(err, "decode key")
}
pskList[i] = kb
}
}
return shadowaead_2022.New(method, pskList, password, secureRNG)
} else {
return nil, E.New("shadowsocks: unsupported method ", method)
}
}

View file

@ -1,393 +0,0 @@
package shadowstream
import (
"crypto/aes"
"crypto/cipher"
"crypto/des"
"crypto/md5"
"crypto/rc4"
"io"
"net"
"os"
"runtime"
"github.com/dgryski/go-camellia"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/protocol/shadowsocks"
"github.com/sagernet/sing/protocol/shadowsocks/shadowaead"
"golang.org/x/crypto/blowfish"
"golang.org/x/crypto/cast5"
"golang.org/x/crypto/chacha20"
)
var List = []string{
"aes-128-ctr",
"aes-192-ctr",
"aes-256-ctr",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"camellia-128-cfb",
"camellia-192-cfb",
"camellia-256-cfb",
"bf-cfb",
"cast5-cfb",
"des-cfb",
"rc4",
"rc4-md5",
"chacha20",
"chacha20-ietf",
"xchacha20",
}
type Method struct {
name string
keyLength int
saltLength int
encryptConstructor func(key []byte, salt []byte) (cipher.Stream, error)
decryptConstructor func(key []byte, salt []byte) (cipher.Stream, error)
key []byte
secureRNG io.Reader
}
func New(method string, key []byte, password string, secureRNG io.Reader) (shadowsocks.Method, error) {
m := &Method{
name: method,
secureRNG: secureRNG,
}
switch method {
case "aes-128-ctr":
m.keyLength = 16
m.saltLength = aes.BlockSize
m.encryptConstructor = blockStream(aes.NewCipher, cipher.NewCTR)
m.decryptConstructor = blockStream(aes.NewCipher, cipher.NewCTR)
case "aes-192-ctr":
m.keyLength = 24
m.saltLength = aes.BlockSize
m.encryptConstructor = blockStream(aes.NewCipher, cipher.NewCTR)
m.decryptConstructor = blockStream(aes.NewCipher, cipher.NewCTR)
case "aes-256-ctr":
m.keyLength = 32
m.saltLength = aes.BlockSize
m.encryptConstructor = blockStream(aes.NewCipher, cipher.NewCTR)
m.decryptConstructor = blockStream(aes.NewCipher, cipher.NewCTR)
case "aes-128-cfb":
m.keyLength = 16
m.saltLength = aes.BlockSize
m.encryptConstructor = blockStream(aes.NewCipher, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(aes.NewCipher, cipher.NewCFBDecrypter)
case "aes-192-cfb":
m.keyLength = 24
m.saltLength = aes.BlockSize
m.encryptConstructor = blockStream(aes.NewCipher, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(aes.NewCipher, cipher.NewCFBDecrypter)
case "aes-256-cfb":
m.keyLength = 32
m.saltLength = aes.BlockSize
m.encryptConstructor = blockStream(aes.NewCipher, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(aes.NewCipher, cipher.NewCFBDecrypter)
case "camellia-128-cfb":
m.keyLength = 16
m.saltLength = camellia.BlockSize
m.encryptConstructor = blockStream(camellia.New, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(camellia.New, cipher.NewCFBDecrypter)
case "camellia-192-cfb":
m.keyLength = 24
m.saltLength = camellia.BlockSize
m.encryptConstructor = blockStream(camellia.New, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(camellia.New, cipher.NewCFBDecrypter)
case "camellia-256-cfb":
m.keyLength = 32
m.saltLength = camellia.BlockSize
m.encryptConstructor = blockStream(camellia.New, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(camellia.New, cipher.NewCFBDecrypter)
case "bf-cfb":
m.keyLength = 16
m.saltLength = blowfish.BlockSize
m.encryptConstructor = blockStream(func(key []byte) (cipher.Block, error) { return blowfish.NewCipher(key) }, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(func(key []byte) (cipher.Block, error) { return blowfish.NewCipher(key) }, cipher.NewCFBDecrypter)
case "cast5-cfb":
m.keyLength = 16
m.saltLength = cast5.BlockSize
m.encryptConstructor = blockStream(func(key []byte) (cipher.Block, error) { return cast5.NewCipher(key) }, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(func(key []byte) (cipher.Block, error) { return cast5.NewCipher(key) }, cipher.NewCFBDecrypter)
case "des-cfb":
m.keyLength = 8
m.saltLength = des.BlockSize
m.encryptConstructor = blockStream(des.NewCipher, cipher.NewCFBEncrypter)
m.decryptConstructor = blockStream(des.NewCipher, cipher.NewCFBDecrypter)
case "rc4":
m.keyLength = 16
m.saltLength = 0
m.encryptConstructor = func(key []byte, salt []byte) (cipher.Stream, error) {
return rc4.NewCipher(key)
}
m.decryptConstructor = func(key []byte, salt []byte) (cipher.Stream, error) {
return rc4.NewCipher(key)
}
case "rc4-md5":
m.keyLength = 16
m.saltLength = 0
m.encryptConstructor = func(key []byte, salt []byte) (cipher.Stream, error) {
h := md5.New()
h.Write(key)
h.Write(salt)
return rc4.NewCipher(h.Sum(nil))
}
m.decryptConstructor = func(key []byte, salt []byte) (cipher.Stream, error) {
h := md5.New()
h.Write(key)
h.Write(salt)
return rc4.NewCipher(h.Sum(nil))
}
case "chacha20", "chacha20-ietf":
m.keyLength = chacha20.KeySize
m.saltLength = chacha20.NonceSize
m.encryptConstructor = func(key []byte, salt []byte) (cipher.Stream, error) {
return chacha20.NewUnauthenticatedCipher(key, salt)
}
m.decryptConstructor = func(key []byte, salt []byte) (cipher.Stream, error) {
return chacha20.NewUnauthenticatedCipher(key, salt)
}
case "xchacha20":
m.keyLength = chacha20.KeySize
m.saltLength = chacha20.NonceSizeX
m.encryptConstructor = func(key []byte, salt []byte) (cipher.Stream, error) {
return chacha20.NewUnauthenticatedCipher(key, salt)
}
m.decryptConstructor = func(key []byte, salt []byte) (cipher.Stream, error) {
return chacha20.NewUnauthenticatedCipher(key, salt)
}
default:
return nil, os.ErrInvalid
}
if len(key) == m.keyLength {
m.key = key
} else if len(key) > 0 {
return nil, shadowsocks.ErrBadKey
} else if password != "" {
m.key = shadowsocks.Key([]byte(password), m.keyLength)
} else {
return nil, shadowsocks.ErrMissingPassword
}
return m, nil
}
func blockStream(blockCreator func(key []byte) (cipher.Block, error), streamCreator func(block cipher.Block, iv []byte) cipher.Stream) func([]byte, []byte) (cipher.Stream, error) {
return func(key []byte, iv []byte) (cipher.Stream, error) {
block, err := blockCreator(key)
if err != nil {
return nil, err
}
return streamCreator(block, iv), err
}
}
func (m *Method) Name() string {
return m.name
}
func (m *Method) KeyLength() int {
return m.keyLength
}
func (m *Method) DialConn(conn net.Conn, destination M.Socksaddr) (net.Conn, error) {
shadowsocksConn := &clientConn{
Conn: conn,
method: m,
destination: destination,
}
return shadowsocksConn, shadowsocksConn.writeRequest(nil)
}
func (m *Method) DialEarlyConn(conn net.Conn, destination M.Socksaddr) net.Conn {
return &clientConn{
Conn: conn,
method: m,
destination: destination,
}
}
func (m *Method) DialPacketConn(conn net.Conn) N.NetPacketConn {
return &clientPacketConn{m, conn}
}
type clientConn struct {
net.Conn
method *Method
destination M.Socksaddr
readStream cipher.Stream
writeStream cipher.Stream
}
func (c *clientConn) writeRequest(payload []byte) error {
_buffer := buf.Make(c.method.keyLength + M.SocksaddrSerializer.AddrPortLen(c.destination) + len(payload))
defer runtime.KeepAlive(_buffer)
buffer := buf.With(common.Dup(_buffer))
salt := buffer.Extend(c.method.keyLength)
common.Must1(io.ReadFull(c.method.secureRNG, salt))
key := shadowaead.Kdf(c.method.key, salt, c.method.keyLength)
writer, err := c.method.encryptConstructor(c.method.key, salt)
if err != nil {
return err
}
runtime.KeepAlive(key)
err = M.SocksaddrSerializer.WriteAddrPort(buffer, c.destination)
if err != nil {
return err
}
_, err = buffer.Write(payload)
if err != nil {
return err
}
_, err = c.Conn.Write(buffer.Bytes())
if err != nil {
return err
}
c.writeStream = writer
return nil
}
func (c *clientConn) readResponse() error {
if c.readStream != nil {
return nil
}
_salt := buf.Make(c.method.keyLength)
defer runtime.KeepAlive(_salt)
salt := common.Dup(_salt)
_, err := io.ReadFull(c.Conn, salt)
if err != nil {
return err
}
key := shadowaead.Kdf(c.method.key, salt, c.method.keyLength)
defer runtime.KeepAlive(key)
c.readStream, err = c.method.decryptConstructor(common.Dup(key), salt)
if err != nil {
return err
}
return nil
}
func (c *clientConn) Read(p []byte) (n int, err error) {
if err = c.readResponse(); err != nil {
return
}
n, err = c.Conn.Read(p)
if err != nil {
return 0, err
}
c.readStream.XORKeyStream(p[:n], p[:n])
return
}
func (c *clientConn) Write(p []byte) (n int, err error) {
if c.writeStream == nil {
err = c.writeRequest(p)
if err == nil {
n = len(p)
}
return
}
c.writeStream.XORKeyStream(p, p)
return c.Conn.Write(p)
}
func (c *clientConn) Upstream() any {
return c.Conn
}
type clientPacketConn struct {
*Method
net.Conn
}
func (c *clientPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
header := buf.With(buffer.ExtendHeader(c.keyLength + M.SocksaddrSerializer.AddrPortLen(destination)))
common.Must1(header.ReadFullFrom(c.secureRNG, c.keyLength))
err := M.SocksaddrSerializer.WriteAddrPort(header, destination)
if err != nil {
return err
}
stream, err := c.encryptConstructor(c.key, buffer.To(c.keyLength))
if err != nil {
return err
}
stream.XORKeyStream(buffer.From(c.keyLength), buffer.From(c.keyLength))
return common.Error(c.Write(buffer.Bytes()))
}
func (c *clientPacketConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
n, err := c.Read(buffer.FreeBytes())
if err != nil {
return M.Socksaddr{}, err
}
buffer.Truncate(n)
stream, err := c.decryptConstructor(c.key, buffer.To(c.keyLength))
if err != nil {
return M.Socksaddr{}, err
}
stream.XORKeyStream(buffer.From(c.keyLength), buffer.From(c.keyLength))
buffer.Advance(c.keyLength)
return M.SocksaddrSerializer.ReadAddrPort(buffer)
}
func (c *clientPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
n, err = c.Read(p)
if err != nil {
return
}
stream, err := c.decryptConstructor(c.key, p[:c.keyLength])
if err != nil {
return
}
buffer := buf.With(p[c.keyLength:n])
stream.XORKeyStream(buffer.Bytes(), buffer.Bytes())
destination, err := M.SocksaddrSerializer.ReadAddrPort(buffer)
if err != nil {
return
}
addr = destination.UDPAddr()
n = copy(p, buffer.Bytes())
return
}
func (c *clientPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
destination := M.SocksaddrFromNet(addr)
_buffer := buf.Make(c.keyLength + M.SocksaddrSerializer.AddrPortLen(destination) + len(p))
defer runtime.KeepAlive(_buffer)
buffer := buf.With(common.Dup(_buffer))
common.Must1(buffer.ReadFullFrom(c.secureRNG, c.keyLength))
err = M.SocksaddrSerializer.WriteAddrPort(buffer, M.SocksaddrFromNet(addr))
if err != nil {
return
}
_, err = buffer.Write(p)
if err != nil {
return
}
stream, err := c.encryptConstructor(c.key, buffer.To(c.keyLength))
if err != nil {
return
}
stream.XORKeyStream(buffer.From(c.keyLength), buffer.From(c.keyLength))
_, err = c.Write(buffer.Bytes())
if err != nil {
return
}
return len(p), nil
}
func (c *clientPacketConn) Upstream() any {
return c.Conn
}

View file

@ -11,11 +11,18 @@ import (
"github.com/sagernet/sing/common/auth"
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/rw"
"github.com/sagernet/sing/protocol/socks/socks4"
"github.com/sagernet/sing/protocol/socks/socks5"
)
type Handler interface {
N.TCPConnectionHandler
N.UDPConnectionHandler
E.Handler
}
func ClientHandshake4(conn io.ReadWriter, command byte, destination M.Socksaddr, username string) (socks4.Response, error) {
err := socks4.WriteRequest(conn, socks4.Request{
Command: command,
@ -37,7 +44,7 @@ func ClientHandshake4(conn io.ReadWriter, command byte, destination M.Socksaddr,
func ClientHandshake5(conn io.ReadWriter, command byte, destination M.Socksaddr, username string, password string) (socks5.Response, error) {
var method byte
if common.IsBlank(username) {
if username == "" {
method = socks5.AuthTypeNotRequired
} else {
method = socks5.AuthTypeUsernamePassword

View file

@ -1,50 +0,0 @@
package socks
import (
"context"
"net"
"net/netip"
"github.com/sagernet/sing/common/auth"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/transport/tcp"
)
type Handler interface {
tcp.Handler
N.UDPConnectionHandler
}
type Listener struct {
bindAddr netip.Addr
tcpListener *tcp.Listener
authenticator auth.Authenticator
handler Handler
}
func NewListener(bind netip.AddrPort, authenticator auth.Authenticator, handler Handler) *Listener {
listener := &Listener{
bindAddr: bind.Addr(),
handler: handler,
authenticator: authenticator,
}
listener.tcpListener = tcp.NewTCPListener(bind, listener)
return listener
}
func (l *Listener) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
return HandleConnection(ctx, conn, l.authenticator, l.handler, metadata)
}
func (l *Listener) Start() error {
return l.tcpListener.Start()
}
func (l *Listener) Close() error {
return l.tcpListener.Close()
}
func (l *Listener) HandleError(err error) {
l.handler.HandleError(err)
}

View file

@ -15,7 +15,7 @@ import (
)
type Handler interface {
M.TCPConnectionHandler
N.TCPConnectionHandler
N.UDPConnectionHandler
}

View file

@ -10,7 +10,6 @@ import (
"runtime"
"strings"
"github.com/sagernet/sing"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/auth"
"github.com/sagernet/sing/common/buf"
@ -87,7 +86,6 @@ func (l *Listener) NewConnection(ctx context.Context, conn net.Conn, metadata M.
ProtoMinor: request.ProtoMinor,
Header: netHttp.Header{
"Content-Type": {"application/x-ns-proxy-autoconfig"},
"Server": {sing.VersionStr},
},
ContentLength: int64(len(content)),
Body: io.NopCloser(strings.NewReader(content)),

View file

@ -4,14 +4,6 @@ import (
"net/netip"
)
/*func newPAC(proxyAddr M.Socksaddr) string {
return `
function FindProxyForURL(url, host) {
return "SOCKS5 ` + proxyAddr.String() + `;SOCKS ` + proxyAddr.String() + `; PROXY ` + proxyAddr.String() + `";
}`
}
*/
func newPAC(proxyAddr netip.AddrPort) string {
// TODO: socks4 not supported
return `

View file

@ -9,11 +9,12 @@ import (
"github.com/sagernet/sing/common/debug"
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/redir"
)
type Handler interface {
M.TCPConnectionHandler
N.TCPConnectionHandler
E.Handler
}

View file

@ -1,80 +0,0 @@
package tls
import (
crand "crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"math/rand"
"net"
"time"
"github.com/sagernet/sing/common/random"
)
func GenerateCertificate(hosts ...string) (*tls.Certificate, error) {
rng := random.System
r := rand.New(rng)
privateKey, err := rsa.GenerateKey(rng, 2048)
if err != nil {
return nil, err
}
createAt := time.Now().AddDate(0, -r.Intn(2)-1, -rand.Intn(15))
createAt = createAt.Add(-(time.Duration(r.Intn(12)) * time.Hour))
createAt = createAt.Add(-(time.Duration(r.Intn(60)) * time.Minute))
createAt = createAt.Add(-(time.Duration(r.Intn(60)) * time.Second))
createAt = createAt.Add(-(time.Duration(r.Intn(1000)) * time.Millisecond))
createAt = createAt.Add(-(time.Duration(r.Intn(1000)) * time.Microsecond))
endAt := createAt.AddDate(0, (r.Intn(1)+1)*6, 0)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := crand.Int(rng, serialNumberLimit)
if err != nil {
return nil, err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Cloudflare, Inc."},
},
NotBefore: createAt,
NotAfter: endAt,
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
template.Raw, err = x509.CreateCertificate(rng, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return nil, err
}
privBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return nil, err
}
cert, err := tls.X509KeyPair(
pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: template.Raw}),
pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}),
)
if err != nil {
return nil, err
}
return &cert, nil
}

View file

@ -1,14 +0,0 @@
package tls_test
import (
"testing"
"github.com/sagernet/sing/transport/tls"
)
func TestGenerateCertificate(t *testing.T) {
_, err := tls.GenerateCertificate("cn.bing.com")
if err != nil {
t.Fatal(err)
}
}