1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-21 09:36:34 -05:00

Style: format code by gofumpt (#1022)

This commit is contained in:
Loyalsoldier 2021-05-20 05:28:52 +08:00 committed by GitHub
parent cf009a4ba2
commit 6f8979d017
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
87 changed files with 249 additions and 270 deletions

View File

@ -26,9 +26,7 @@ import (
"github.com/v2fly/v2ray-core/v4/transport/pipe" "github.com/v2fly/v2ray-core/v4/transport/pipe"
) )
var ( var errSniffingTimeout = newError("timeout on sniffing")
errSniffingTimeout = newError("timeout on sniffing")
)
type cachedReader struct { type cachedReader struct {
sync.Mutex sync.Mutex

View File

@ -22,8 +22,7 @@ import (
"github.com/v2fly/v2ray-core/v4/testing/servers/udp" "github.com/v2fly/v2ray-core/v4/testing/servers/udp"
) )
type staticHandler struct { type staticHandler struct{}
}
func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
ans := new(dns.Msg) ans := new(dns.Msg)

View File

@ -56,9 +56,7 @@ func isNewer(baseRec *IPRecord, newRec *IPRecord) bool {
return baseRec.Expire.Before(newRec.Expire) return baseRec.Expire.Before(newRec.Expire)
} }
var ( var errRecordNotFound = errors.New("record not found")
errRecordNotFound = errors.New("record not found")
)
type dnsRequest struct { type dnsRequest struct {
reqType dnsmessage.Type reqType dnsmessage.Type

View File

@ -52,20 +52,28 @@ func Test_parseResponse(t *testing.T) {
want *IPRecord want *IPRecord
wantErr bool wantErr bool
}{ }{
{"empty", {
"empty",
&IPRecord{0, []net.Address(nil), time.Time{}, dnsmessage.RCodeSuccess}, &IPRecord{0, []net.Address(nil), time.Time{}, dnsmessage.RCodeSuccess},
false, false,
}, },
{"error", {
"error",
nil, nil,
true, true,
}, },
{"a record", {
&IPRecord{1, []net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")}, "a record",
time.Time{}, dnsmessage.RCodeSuccess}, &IPRecord{
1,
[]net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")},
time.Time{},
dnsmessage.RCodeSuccess,
},
false, false,
}, },
{"aaaa record", {
"aaaa record",
&IPRecord{2, []net.Address{net.ParseAddress("2001::123:8888"), net.ParseAddress("2001::123:8844")}, time.Time{}, dnsmessage.RCodeSuccess}, &IPRecord{2, []net.Address{net.ParseAddress("2001::123:8888"), net.ParseAddress("2001::123:8844")}, time.Time{}, dnsmessage.RCodeSuccess},
false, false,
}, },

View File

@ -13,9 +13,7 @@ type HandlerCreatorOptions struct {
type HandlerCreator func(LogType, HandlerCreatorOptions) (log.Handler, error) type HandlerCreator func(LogType, HandlerCreatorOptions) (log.Handler, error)
var ( var handlerCreatorMap = make(map[LogType]HandlerCreator)
handlerCreatorMap = make(map[LogType]HandlerCreator)
)
func RegisterHandlerCreator(logType LogType, f HandlerCreator) error { func RegisterHandlerCreator(logType LogType, f HandlerCreator) error {
if f == nil { if f == nil {

View File

@ -465,6 +465,7 @@ func (w *dsWorker) Proxy() proxy.Inbound {
func (w *dsWorker) Port() net.Port { func (w *dsWorker) Port() net.Port {
return net.Port(0) return net.Port(0)
} }
func (w *dsWorker) Start() error { func (w *dsWorker) Start() error {
ctx := context.Background() ctx := context.Background()
hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn internet.Connection) { hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn internet.Connection) {

View File

@ -14,8 +14,7 @@ type BalancingStrategy interface {
PickOutbound([]string) string PickOutbound([]string) string
} }
type RandomStrategy struct { type RandomStrategy struct{}
}
func (s *RandomStrategy) PickOutbound(tags []string) string { func (s *RandomStrategy) PickOutbound(tags []string) string {
n := len(tags) n := len(tags)
@ -47,6 +46,7 @@ func (b *Balancer) PickOutbound() (string, error) {
} }
return tag, nil return tag, nil
} }
func (b *Balancer) InjectContext(ctx context.Context) { func (b *Balancer) InjectContext(ctx context.Context) {
if contextReceiver, ok := b.strategy.(extension.ContextReceiver); ok { if contextReceiver, ok := b.strategy.(extension.ContextReceiver); ok {
contextReceiver.InjectContext(ctx) contextReceiver.InjectContext(ctx)

View File

@ -203,6 +203,4 @@ func (c *GeoIPMatcherContainer) Add(geoip *GeoIP) (*GeoIPMatcher, error) {
return m, nil return m, nil
} }
var ( var globalGeoIPContainer GeoIPMatcherContainer
globalGeoIPContainer GeoIPMatcherContainer
)

View File

@ -28,7 +28,7 @@ func init() {
os.Setenv("v2ray.location.asset", tempPath) os.Setenv("v2ray.location.asset", tempPath)
if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geoipBytes, err := common.FetchHTTPContent(geoipURL) geoipBytes, err := common.FetchHTTPContent(geoipURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) common.Must(filesystem.WriteFile(geoipPath, geoipBytes))
@ -98,7 +98,8 @@ func TestGeoIPMatcher(t *testing.T) {
{ {
Input: "192.0.1.0", Input: "192.0.1.0",
Output: false, Output: false,
}, { },
{
Input: "0.1.0.0", Input: "0.1.0.0",
Output: true, Output: true,
}, },

View File

@ -38,13 +38,13 @@ func init() {
os.Setenv("v2ray.location.asset", tempPath) os.Setenv("v2ray.location.asset", tempPath)
if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geoipBytes, err := common.FetchHTTPContent(geoipURL) geoipBytes, err := common.FetchHTTPContent(geoipURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) common.Must(filesystem.WriteFile(geoipPath, geoipBytes))
} }
if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geositeBytes, err := common.FetchHTTPContent(geositeURL) geositeBytes, err := common.FetchHTTPContent(geositeURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geositePath, geositeBytes)) common.Must(filesystem.WriteFile(geositePath, geositeBytes))
@ -369,6 +369,7 @@ func loadGeoSite(country string) ([]*router.Domain, error) {
return nil, errors.New("country not found: " + country) return nil, errors.New("country not found: " + country)
} }
func TestChinaSites(t *testing.T) { func TestChinaSites(t *testing.T) {
domains, err := loadGeoSite("CN") domains, err := loadGeoSite("CN")
common.Must(err) common.Must(err)

View File

@ -78,6 +78,7 @@ func TestBufferByte(t *testing.T) {
buffer.Release() buffer.Release()
} }
} }
func TestBufferResize(t *testing.T) { func TestBufferResize(t *testing.T) {
buffer := New() buffer := New()
defer buffer.Release() defer buffer.Release()

View File

@ -18,10 +18,8 @@ import (
//go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
var ( // ErrNoClue is for the situation that existing information is not enough to make a decision. For example, Router may return this error when there is no suitable route.
// ErrNoClue is for the situation that existing information is not enough to make a decision. For example, Router may return this error when there is no suitable route. var ErrNoClue = errors.New("not enough information for making a decision")
ErrNoClue = errors.New("not enough information for making a decision")
)
// Must panics if err is not nil. // Must panics if err is not nil.
func Must(err error) { func Must(err error) {

View File

@ -295,7 +295,6 @@ func (w *AuthenticationWriter) writeStream(mb buf.MultiBuffer) error {
mb = nb mb = nb
eb, err := w.seal(rawBytes[:nBytes]) eb, err := w.seal(rawBytes[:nBytes])
if err != nil { if err != nil {
buf.ReleaseMulti(mb2Write) buf.ReleaseMulti(mb2Write)
return err return err

View File

@ -18,7 +18,7 @@ func mustDecodeHex(s string) []byte {
} }
func TestChaCha20Stream(t *testing.T) { func TestChaCha20Stream(t *testing.T) {
var cases = []struct { cases := []struct {
key []byte key []byte
iv []byte iv []byte
output []byte output []byte

View File

@ -3,7 +3,7 @@ package internal
import "encoding/binary" import "encoding/binary"
func ChaCha20Block(s *[16]uint32, out []byte, rounds int) { func ChaCha20Block(s *[16]uint32, out []byte, rounds int) {
var x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 = s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15] x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 := s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15]
for i := 0; i < rounds; i += 2 { for i := 0; i < rounds; i += 2 {
var x uint32 var x uint32

View File

@ -55,7 +55,7 @@ func ChaCha20Block(s *[16]uint32, out []byte, rounds int) {
} }
func main() { func main() {
file, err := os.OpenFile("chacha_core.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) file, err := os.OpenFile("chacha_core.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644)
if err != nil { if err != nil {
log.Fatalf("Failed to generate chacha_core.go: %v", err) log.Fatalf("Failed to generate chacha_core.go: %v", err)
} }

View File

@ -27,9 +27,7 @@ func (r *CryptionReader) Read(data []byte) (int, error) {
return nBytes, err return nBytes, err
} }
var ( var _ buf.Writer = (*CryptionWriter)(nil)
_ buf.Writer = (*CryptionWriter)(nil)
)
type CryptionWriter struct { type CryptionWriter struct {
stream cipher.Stream stream cipher.Stream

View File

@ -17,7 +17,7 @@ func main() {
pkg = "core" pkg = "core"
} }
file, err := os.OpenFile("errors.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) file, err := os.OpenFile("errors.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644)
if err != nil { if err != nil {
fmt.Printf("Failed to generate errors.generated.go: %v", err) fmt.Printf("Failed to generate errors.generated.go: %v", err)
os.Exit(1) os.Exit(1)

View File

@ -32,9 +32,7 @@ func Record(msg Message) {
logHandler.Handle(msg) logHandler.Handle(msg)
} }
var ( var logHandler syncHandler
logHandler syncHandler
)
// RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded. // RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded.
func RegisterHandler(handler Handler) { func RegisterHandler(handler Handler) {

View File

@ -130,13 +130,13 @@ func CreateStderrLogWriter() WriterCreator {
// CreateFileLogWriter returns a LogWriterCreator that creates LogWriter for the given file. // CreateFileLogWriter returns a LogWriterCreator that creates LogWriter for the given file.
func CreateFileLogWriter(path string) (WriterCreator, error) { func CreateFileLogWriter(path string) (WriterCreator, error) {
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil { if err != nil {
return nil, err return nil, err
} }
file.Close() file.Close()
return func() Writer { return func() Writer {
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil { if err != nil {
return nil return nil
} }

View File

@ -143,6 +143,7 @@ func NewDialingWorkerFactory(ctx context.Context, proxy proxy.Outbound, dialer i
ctx: ctx, ctx: ctx,
} }
} }
func (f *DialingWorkerFactory) Create() (*ClientWorker, error) { func (f *DialingWorkerFactory) Create() (*ClientWorker, error) {
opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)} opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)}
uplinkReader, upLinkWriter := pipe.New(opts...) uplinkReader, upLinkWriter := pipe.New(opts...)
@ -152,7 +153,6 @@ func (f *DialingWorkerFactory) Create() (*ClientWorker, error) {
Reader: downlinkReader, Reader: downlinkReader,
Writer: upLinkWriter, Writer: upLinkWriter,
}, f.Strategy) }, f.Strategy)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -185,8 +185,10 @@ type ClientWorker struct {
strategy ClientStrategy strategy ClientStrategy
} }
var muxCoolAddress = net.DomainAddress("v1.mux.cool") var (
var muxCoolPort = net.Port(9527) muxCoolAddress = net.DomainAddress("v1.mux.cool")
muxCoolPort = net.Port(9527)
)
// NewClientWorker creates a new mux.Client. // NewClientWorker creates a new mux.Client.
func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) { func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) {

View File

@ -2,60 +2,48 @@ package net
import "net" import "net"
// DialTCP is an alias of net.DialTCP. const (
var DialTCP = net.DialTCP IPv4len = net.IPv4len
var DialUDP = net.DialUDP IPv6len = net.IPv6len
var DialUnix = net.DialUnix )
var Dial = net.Dial
type ListenConfig = net.ListenConfig var (
CIDRMask = net.CIDRMask
Dial = net.Dial
DialTCP = net.DialTCP
DialUDP = net.DialUDP
DialUnix = net.DialUnix
FileConn = net.FileConn
Listen = net.Listen
ListenTCP = net.ListenTCP
ListenUDP = net.ListenUDP
ListenUnix = net.ListenUnix
LookupIP = net.LookupIP
ParseIP = net.ParseIP
ResolveUDPAddr = net.ResolveUDPAddr
ResolveUnixAddr = net.ResolveUnixAddr
SplitHostPort = net.SplitHostPort
)
var Listen = net.Listen type (
var ListenTCP = net.ListenTCP Addr = net.Addr
var ListenUDP = net.ListenUDP AddrError = net.AddrError
var ListenUnix = net.ListenUnix Conn = net.Conn
Dialer = net.Dialer
var LookupIP = net.LookupIP Error = net.Error
IP = net.IP
var FileConn = net.FileConn IPMask = net.IPMask
IPNet = net.IPNet
// ParseIP is an alias of net.ParseIP ListenConfig = net.ListenConfig
var ParseIP = net.ParseIP Listener = net.Listener
PacketConn = net.PacketConn
var SplitHostPort = net.SplitHostPort Resolver = net.Resolver
TCPAddr = net.TCPAddr
var CIDRMask = net.CIDRMask TCPConn = net.TCPConn
TCPListener = net.TCPListener
type Addr = net.Addr UDPAddr = net.UDPAddr
type Conn = net.Conn UDPConn = net.UDPConn
type PacketConn = net.PacketConn UnixAddr = net.UnixAddr
UnixConn = net.UnixConn
type TCPAddr = net.TCPAddr UnixListener = net.UnixListener
type TCPConn = net.TCPConn )
type UDPAddr = net.UDPAddr
type UDPConn = net.UDPConn
type UnixAddr = net.UnixAddr
type UnixConn = net.UnixConn
// IP is an alias for net.IP.
type IP = net.IP
type IPMask = net.IPMask
type IPNet = net.IPNet
const IPv4len = net.IPv4len
const IPv6len = net.IPv6len
type Error = net.Error
type AddrError = net.AddrError
type Dialer = net.Dialer
type Listener = net.Listener
type TCPListener = net.TCPListener
type UnixListener = net.UnixListener
var ResolveUnixAddr = net.ResolveUnixAddr
var ResolveUDPAddr = net.ResolveUDPAddr
type Resolver = net.Resolver

View File

@ -55,7 +55,7 @@ func CopyFile(dst string, src string) error {
if err != nil { if err != nil {
return err return err
} }
f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil { if err != nil {
return err return err
} }

View File

@ -6,8 +6,7 @@ import (
"github.com/v2fly/v2ray-core/v4/common" "github.com/v2fly/v2ray-core/v4/common"
) )
type SniffHeader struct { type SniffHeader struct{}
}
func (h *SniffHeader) Protocol() string { func (h *SniffHeader) Protocol() string {
return "bittorrent" return "bittorrent"

View File

@ -73,6 +73,7 @@ func printJSON(certificate *Certificate) {
os.Stdout.Write(content) os.Stdout.Write(content)
os.Stdout.WriteString("\n") os.Stdout.WriteString("\n")
} }
func printFile(certificate *Certificate, name string) error { func printFile(certificate *Certificate, name string) error {
certPEM, keyPEM := certificate.ToPEM() certPEM, keyPEM := certificate.ToPEM()
return task.Run(context.Background(), func() error { return task.Run(context.Background(), func() error {
@ -81,6 +82,7 @@ func printFile(certificate *Certificate, name string) error {
return writeFile(keyPEM, name+"_key.pem") return writeFile(keyPEM, name+"_key.pem")
}) })
} }
func writeFile(content []byte, name string) error { func writeFile(content []byte, name string) error {
f, err := os.Create(name) f, err := os.Create(name)
if err != nil { if err != nil {

View File

@ -20,8 +20,10 @@ func (h *SniffHeader) Domain() string {
return h.domain return h.domain
} }
var errNotTLS = errors.New("not TLS header") var (
var errNotClientHello = errors.New("not client hello") errNotTLS = errors.New("not TLS header")
errNotClientHello = errors.New("not client hello")
)
func IsValidTLSVersion(major, minor byte) bool { func IsValidTLSVersion(major, minor byte) bool {
return major == 3 return major == 3

View File

@ -6,9 +6,7 @@ import (
"time" "time"
) )
var ( var ErrRetryFailed = newError("all retry attempts failed")
ErrRetryFailed = newError("all retry attempts failed")
)
// Strategy is a way to retry on a specific function. // Strategy is a way to retry on a specific function.
type Strategy interface { type Strategy interface {

View File

@ -9,9 +9,7 @@ import (
. "github.com/v2fly/v2ray-core/v4/common/retry" . "github.com/v2fly/v2ray-core/v4/common/retry"
) )
var ( var errorTestOnly = errors.New("this is a fake error")
errorTestOnly = errors.New("this is a fake error")
)
func TestNoRetry(t *testing.T) { func TestNoRetry(t *testing.T) {
startTime := time.Now().Unix() startTime := time.Now().Unix()

View File

@ -122,7 +122,7 @@ var char2Index = []int{
} }
func NewACAutomaton() *ACAutomaton { func NewACAutomaton() *ACAutomaton {
var ac = new(ACAutomaton) ac := new(ACAutomaton)
ac.trie = append(ac.trie, newNode()) ac.trie = append(ac.trie, newNode())
ac.fail = append(ac.fail, 0) ac.fail = append(ac.fail, 0)
ac.exists = append(ac.exists, MatchType{ ac.exists = append(ac.exists, MatchType{
@ -133,9 +133,9 @@ func NewACAutomaton() *ACAutomaton {
} }
func (ac *ACAutomaton) Add(domain string, t Type) { func (ac *ACAutomaton) Add(domain string, t Type) {
var node = 0 node := 0
for i := len(domain) - 1; i >= 0; i-- { for i := len(domain) - 1; i >= 0; i-- {
var idx = char2Index[domain[i]] idx := char2Index[domain[i]]
if ac.trie[node][idx].nextNode == 0 { if ac.trie[node][idx].nextNode == 0 {
ac.count++ ac.count++
if len(ac.trie) < ac.count+1 { if len(ac.trie) < ac.count+1 {
@ -163,7 +163,7 @@ func (ac *ACAutomaton) Add(domain string, t Type) {
matchType: Full, matchType: Full,
exist: true, exist: true,
} }
var idx = char2Index['.'] idx := char2Index['.']
if ac.trie[node][idx].nextNode == 0 { if ac.trie[node][idx].nextNode == 0 {
ac.count++ ac.count++
if len(ac.trie) < ac.count+1 { if len(ac.trie) < ac.count+1 {
@ -190,18 +190,18 @@ func (ac *ACAutomaton) Add(domain string, t Type) {
} }
func (ac *ACAutomaton) Build() { func (ac *ACAutomaton) Build() {
var queue = list.New() queue := list.New()
for i := 0; i < validCharCount; i++ { for i := 0; i < validCharCount; i++ {
if ac.trie[0][i].nextNode != 0 { if ac.trie[0][i].nextNode != 0 {
queue.PushBack(ac.trie[0][i]) queue.PushBack(ac.trie[0][i])
} }
} }
for { for {
var front = queue.Front() front := queue.Front()
if front == nil { if front == nil {
break break
} else { } else {
var node = front.Value.(Edge).nextNode node := front.Value.(Edge).nextNode
queue.Remove(front) queue.Remove(front)
for i := 0; i < validCharCount; i++ { for i := 0; i < validCharCount; i++ {
if ac.trie[node][i].nextNode != 0 { if ac.trie[node][i].nextNode != 0 {
@ -219,13 +219,13 @@ func (ac *ACAutomaton) Build() {
} }
func (ac *ACAutomaton) Match(s string) bool { func (ac *ACAutomaton) Match(s string) bool {
var node = 0 node := 0
var fullMatch = true fullMatch := true
// 1. the match string is all through trie edge. FULL MATCH or DOMAIN // 1. the match string is all through trie edge. FULL MATCH or DOMAIN
// 2. the match string is through a fail edge. NOT FULL MATCH // 2. the match string is through a fail edge. NOT FULL MATCH
// 2.1 Through a fail edge, but there exists a valid node. SUBSTR // 2.1 Through a fail edge, but there exists a valid node. SUBSTR
for i := len(s) - 1; i >= 0; i-- { for i := len(s) - 1; i >= 0; i-- {
var idx = char2Index[s[i]] idx := char2Index[s[i]]
fullMatch = fullMatch && ac.trie[node][idx].edgeType fullMatch = fullMatch && ac.trie[node][idx].edgeType
node = ac.trie[node][idx].nextNode node = ac.trie[node][idx].nextNode
switch ac.exists[node].matchType { switch ac.exists[node].matchType {

View File

@ -71,6 +71,7 @@ func TestMatcher(t *testing.T) {
} }
} }
} }
func TestACAutomaton(t *testing.T) { func TestACAutomaton(t *testing.T) {
cases1 := []struct { cases1 := []struct {
pattern string pattern string
@ -122,7 +123,7 @@ func TestACAutomaton(t *testing.T) {
}, },
} }
for _, test := range cases1 { for _, test := range cases1 {
var ac = NewACAutomaton() ac := NewACAutomaton()
ac.Add(test.pattern, test.mType) ac.Add(test.pattern, test.mType)
ac.Build() ac.Build()
if m := ac.Match(test.input); m != test.output { if m := ac.Match(test.input); m != test.output {
@ -155,7 +156,7 @@ func TestACAutomaton(t *testing.T) {
mType: Substr, mType: Substr,
}, },
} }
var ac = NewACAutomaton() ac := NewACAutomaton()
for _, test := range cases2Input { for _, test := range cases2Input {
ac.Add(test.pattern, test.mType) ac.Add(test.pattern, test.mType)
} }
@ -218,7 +219,7 @@ func TestACAutomaton(t *testing.T) {
mType: Domain, mType: Domain,
}, },
} }
var ac = NewACAutomaton() ac := NewACAutomaton()
for _, test := range cases3Input { for _, test := range cases3Input {
ac.Add(test.pattern, test.mType) ac.Add(test.pattern, test.mType)
} }

View File

@ -102,7 +102,7 @@ func (g *MphMatcherGroup) Build() {
g.level0Mask = len(g.level0) - 1 g.level0Mask = len(g.level0) - 1
g.level1 = make([]uint32, nextPow2(keyLen)) g.level1 = make([]uint32, nextPow2(keyLen))
g.level1Mask = len(g.level1) - 1 g.level1Mask = len(g.level1) - 1
var sparseBuckets = make([][]int, len(g.level0)) sparseBuckets := make([][]int, len(g.level0))
var ruleIdx int var ruleIdx int
for rule, hash := range *g.ruleMap { for rule, hash := range *g.ruleMap {
n := int(hash) & g.level0Mask n := int(hash) & g.level0Mask
@ -122,7 +122,7 @@ func (g *MphMatcherGroup) Build() {
occ := make([]bool, len(g.level1)) occ := make([]bool, len(g.level1))
var tmpOcc []int var tmpOcc []int
for _, bucket := range buckets { for _, bucket := range buckets {
var seed = uint32(0) seed := uint32(0)
for { for {
findSeed := true findSeed := true
tmpOcc = tmpOcc[:0] tmpOcc = tmpOcc[:0]
@ -284,9 +284,11 @@ tail:
h ^= h >> 32 h ^= h >> 32
return uintptr(h) return uintptr(h)
} }
func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { func add(p unsafe.Pointer, x uintptr) unsafe.Pointer {
return unsafe.Pointer(uintptr(p) + x) return unsafe.Pointer(uintptr(p) + x)
} }
func readUnaligned32(p unsafe.Pointer) uint32 { func readUnaligned32(p unsafe.Pointer) uint32 {
q := (*[4]byte)(p) q := (*[4]byte)(p)
return uint32(q[0]) | uint32(q[1])<<8 | uint32(q[2])<<16 | uint32(q[3])<<24 return uint32(q[0]) | uint32(q[1])<<8 | uint32(q[2])<<16 | uint32(q[3])<<24
@ -295,6 +297,7 @@ func readUnaligned32(p unsafe.Pointer) uint32 {
func rotl31(x uint64) uint64 { func rotl31(x uint64) uint64 {
return (x << 31) | (x >> (64 - 31)) return (x << 31) | (x >> (64 - 31))
} }
func readUnaligned64(p unsafe.Pointer) uint64 { func readUnaligned64(p unsafe.Pointer) uint64 {
q := (*[8]byte)(p) q := (*[8]byte)(p)
return uint64(q[0]) | uint64(q[1])<<8 | uint64(q[2])<<16 | uint64(q[3])<<24 | uint64(q[4])<<32 | uint64(q[5])<<40 | uint64(q[6])<<48 | uint64(q[7])<<56 return uint64(q[0]) | uint64(q[1])<<8 | uint64(q[2])<<16 | uint64(q[3])<<24 | uint64(q[4])<<32 | uint64(q[5])<<40 | uint64(q[6])<<48 | uint64(q[7])<<56

View File

@ -8,9 +8,7 @@ import (
// ConfigCreator is a function to create an object by a config. // ConfigCreator is a function to create an object by a config.
type ConfigCreator func(ctx context.Context, config interface{}) (interface{}, error) type ConfigCreator func(ctx context.Context, config interface{}) (interface{}, error)
var ( var typeCreatorRegistry = make(map[reflect.Type]ConfigCreator)
typeCreatorRegistry = make(map[reflect.Type]ConfigCreator)
)
// RegisterConfig registers a global config creator. The config can be nil but must have a type. // RegisterConfig registers a global config creator. The config can be nil but must have a type.
func RegisterConfig(config interface{}, configCreator ConfigCreator) error { func RegisterConfig(config interface{}, configCreator ConfigCreator) error {

View File

@ -16,7 +16,7 @@ type YConfig struct {
} }
func TestObjectCreation(t *testing.T) { func TestObjectCreation(t *testing.T) {
var f = func(ctx context.Context, t interface{}) (interface{}, error) { f := func(ctx context.Context, t interface{}) (interface{}, error) {
return func() int { return func() int {
return t.(*TConfig).value return t.(*TConfig).value
}, nil }, nil

View File

@ -9,9 +9,7 @@ import (
"github.com/v2fly/v2ray-core/v4/common/errors" "github.com/v2fly/v2ray-core/v4/common/errors"
) )
var ( var byteGroups = []int{8, 4, 4, 4, 12}
byteGroups = []int{8, 4, 4, 4, 12}
)
type UUID [16]byte type UUID [16]byte

View File

@ -42,12 +42,10 @@ func (v *BlackholeConfig) Build() (proto.Message, error) {
return config, nil return config, nil
} }
var ( var configLoader = NewJSONConfigLoader(
configLoader = NewJSONConfigLoader( ConfigCreatorCache{
ConfigCreatorCache{ "none": func() interface{} { return new(NoneResponse) },
"none": func() interface{} { return new(NoneResponse) }, "http": func() interface{} { return new(HTTPResponse) },
"http": func() interface{} { return new(HTTPResponse) }, },
}, "type",
"type", "")
"")
)

View File

@ -34,13 +34,13 @@ func init() {
os.Setenv("v2ray.location.asset", tempPath) os.Setenv("v2ray.location.asset", tempPath)
if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geoipBytes, err := common.FetchHTTPContent(geoipURL) geoipBytes, err := common.FetchHTTPContent(geoipURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) common.Must(filesystem.WriteFile(geoipPath, geoipBytes))
} }
if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geositeBytes, err := common.FetchHTTPContent(geositeURL) geositeBytes, err := common.FetchHTTPContent(geositeURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geositePath, geositeBytes)) common.Must(filesystem.WriteFile(geositePath, geositeBytes))

View File

@ -31,13 +31,13 @@ func init() {
os.Setenv("v2ray.location.asset", tempPath) os.Setenv("v2ray.location.asset", tempPath)
if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geoipBytes, err := common.FetchHTTPContent(geoipURL) geoipBytes, err := common.FetchHTTPContent(geoipURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) common.Must(filesystem.WriteFile(geoipPath, geoipBytes))
} }
if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geositeBytes, err := common.FetchHTTPContent(geositeURL) geositeBytes, err := common.FetchHTTPContent(geositeURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geositePath, geositeBytes)) common.Must(filesystem.WriteFile(geositePath, geositeBytes))

View File

@ -29,13 +29,13 @@ func init() {
os.Setenv("v2ray.location.asset", tempPath) os.Setenv("v2ray.location.asset", tempPath)
if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geoipBytes, err := common.FetchHTTPContent(geoipURL) geoipBytes, err := common.FetchHTTPContent(geoipURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) common.Must(filesystem.WriteFile(geoipPath, geoipBytes))
} }
if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geositeBytes, err := common.FetchHTTPContent(geositeURL) geositeBytes, err := common.FetchHTTPContent(geositeURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geositePath, geositeBytes)) common.Must(filesystem.WriteFile(geositePath, geositeBytes))

View File

@ -50,8 +50,7 @@ func loadSite(filename, list string) ([]*router.Domain, error) {
return nil, newError("list not found in ", filename, ": ", list) return nil, newError("list not found in ", filename, ": ", list)
} }
type standardLoader struct { type standardLoader struct{}
}
func (d standardLoader) LoadSite(filename, list string) ([]*router.Domain, error) { func (d standardLoader) LoadSite(filename, list string) ([]*router.Domain, error) {
return loadSite(filename, list) return loadSite(filename, list)

View File

@ -52,6 +52,7 @@ type HTTPRemoteConfig struct {
Port uint16 `json:"port"` Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"` Users []json.RawMessage `json:"users"`
} }
type HTTPClientConfig struct { type HTTPClientConfig struct {
Servers []*HTTPRemoteConfig `json:"servers"` Servers []*HTTPRemoteConfig `json:"servers"`
} }

View File

@ -24,7 +24,8 @@ content 2`,
` `
content content
content 2`}, content 2`,
},
{`content`, `content`}, {`content`, `content`},
{" ", " "}, {" ", " "},
{`con/*abcd*/tent`, "content"}, {`con/*abcd*/tent`, "content"},

View File

@ -60,8 +60,7 @@ func (c *MTProtoServerConfig) Build() (proto.Message, error) {
return config, nil return config, nil
} }
type MTProtoClientConfig struct { type MTProtoClientConfig struct{}
}
func (c *MTProtoClientConfig) Build() (proto.Message, error) { func (c *MTProtoClientConfig) Build() (proto.Message, error) {
config := new(mtproto.ClientConfig) config := new(mtproto.ClientConfig)

View File

@ -30,7 +30,7 @@ func parseDomainRule(ctx context.Context, domain string) ([]*router.Domain, erro
return domains, nil return domains, nil
} }
var isExtDatFile = 0 isExtDatFile := 0
{ {
const prefix = "ext:" const prefix = "ext:"
if strings.HasPrefix(domain, prefix) { if strings.HasPrefix(domain, prefix) {
@ -141,7 +141,7 @@ func toCidrList(ctx context.Context, ips cfgcommon.StringList) ([]*router.GeoIP,
continue continue
} }
var isExtDatFile = 0 isExtDatFile := 0
{ {
const prefix = "ext:" const prefix = "ext:"
if strings.HasPrefix(ip, prefix) { if strings.HasPrefix(ip, prefix) {

View File

@ -29,7 +29,7 @@ func init() {
os.Setenv("v2ray.location.asset", tempPath) os.Setenv("v2ray.location.asset", tempPath)
if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) {
common.Must(os.MkdirAll(tempPath, 0755)) common.Must(os.MkdirAll(tempPath, 0o755))
geoipBytes, err := common.FetchHTTPContent(geoipURL) geoipBytes, err := common.FetchHTTPContent(geoipURL)
common.Must(err) common.Must(err)
common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) common.Must(filesystem.WriteFile(geoipPath, geoipBytes))

View File

@ -71,6 +71,7 @@ type SocksRemoteConfig struct {
Port uint16 `json:"port"` Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"` Users []json.RawMessage `json:"users"`
} }
type SocksClientConfig struct { type SocksClientConfig struct {
Servers []*SocksRemoteConfig `json:"servers"` Servers []*SocksRemoteConfig `json:"servers"`
} }

View File

@ -380,7 +380,8 @@ func TestConfig_Override(t *testing.T) {
fn string fn string
want *Config want *Config
}{ }{
{"combine/empty", {
"combine/empty",
&Config{}, &Config{},
&Config{ &Config{
LogConfig: &LogConfig{}, LogConfig: &LogConfig{},
@ -404,40 +405,54 @@ func TestConfig_Override(t *testing.T) {
Reverse: &ReverseConfig{}, Reverse: &ReverseConfig{},
}, },
}, },
{"combine/newattr", {
"combine/newattr",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "old"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "old"}}},
&Config{LogConfig: &LogConfig{}}, "", &Config{LogConfig: &LogConfig{}}, "",
&Config{LogConfig: &LogConfig{}, InboundConfigs: []InboundDetourConfig{{Tag: "old"}}}}, &Config{LogConfig: &LogConfig{}, InboundConfigs: []InboundDetourConfig{{Tag: "old"}}},
{"replace/inbounds", },
{
"replace/inbounds",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"", "",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}},
{"replace/inbounds-replaceall", },
{
"replace/inbounds-replaceall",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
"", "",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
{"replace/notag-append", },
{
"replace/notag-append",
&Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}}}, &Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"", "",
&Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}, {Tag: "pos1", Protocol: "kcp"}}}}, &Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}, {Tag: "pos1", Protocol: "kcp"}}},
{"replace/outbounds", },
{
"replace/outbounds",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"", "",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}},
{"replace/outbounds-prepend", },
{
"replace/outbounds-prepend",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
"config.json", "config.json",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
{"replace/outbounds-append", },
{
"replace/outbounds-append",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos2", Protocol: "kcp"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos2", Protocol: "kcp"}}},
"config_tail.json", "config_tail.json",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}, {Tag: "pos2", Protocol: "kcp"}}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}, {Tag: "pos2", Protocol: "kcp"}}},
},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {

View File

@ -120,6 +120,7 @@ type VMessOutboundTarget struct {
Port uint16 `json:"port"` Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"` Users []json.RawMessage `json:"users"`
} }
type VMessOutboundConfig struct { type VMessOutboundConfig struct {
Receivers []*VMessOutboundTarget `json:"vnext"` Receivers []*VMessOutboundTarget `json:"vnext"`
} }

View File

@ -33,8 +33,7 @@ type jsonCert struct {
Key []string `json:"key"` Key []string `json:"key"`
} }
type CertificateCommand struct { type CertificateCommand struct{}
}
func (c *CertificateCommand) Name() string { func (c *CertificateCommand) Name() string {
return "cert" return "cert"

View File

@ -8,8 +8,7 @@ import (
v2tls "github.com/v2fly/v2ray-core/v4/transport/internet/tls" v2tls "github.com/v2fly/v2ray-core/v4/transport/internet/tls"
) )
type CertificateChainHashCommand struct { type CertificateChainHashCommand struct{}
}
func (c CertificateChainHashCommand) Name() string { func (c CertificateChainHashCommand) Name() string {
return "certChainHash" return "certChainHash"

View File

@ -5,8 +5,10 @@ import (
"os" "os"
) )
type configFileLoader func(string) (io.Reader, error) type (
type extconfigLoader func([]string, io.Reader) (io.Reader, error) configFileLoader func(string) (io.Reader, error)
extconfigLoader func([]string, io.Reader) (io.Reader, error)
)
var ( var (
EffectiveConfigFileLoader configFileLoader EffectiveConfigFileLoader configFileLoader

View File

@ -20,7 +20,7 @@ func TestBlackHoleHTTPResponse(t *testing.T) {
reader, writer := pipe.New(pipe.WithoutSizeLimit()) reader, writer := pipe.New(pipe.WithoutSizeLimit())
var readerError = make(chan error) readerError := make(chan error)
var mb buf.MultiBuffer var mb buf.MultiBuffer
go func() { go func() {
b, e := reader.ReadMultiBuffer() b, e := reader.ReadMultiBuffer()

View File

@ -24,8 +24,7 @@ import (
"github.com/v2fly/v2ray-core/v4/testing/servers/udp" "github.com/v2fly/v2ray-core/v4/testing/servers/udp"
) )
type staticHandler struct { type staticHandler struct{}
}
func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
ans := new(dns.Msg) ans := new(dns.Msg)

View File

@ -133,7 +133,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)) return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
} }
var responseDonePost = task.OnSuccess(responseFunc, task.Close(link.Writer)) responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

View File

@ -203,7 +203,7 @@ func (s *Server) handleConnect(ctx context.Context, _ *http.Request, reader *buf
return nil return nil
} }
var closeWriter = task.OnSuccess(requestDone, task.Close(link.Writer)) closeWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, closeWriter, responseDone); err != nil { if err := task.Run(ctx, closeWriter, responseDone); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)

View File

@ -133,13 +133,11 @@ func Inverse(b []byte) []byte {
return b2 return b2
} }
var ( var authPool = sync.Pool{
authPool = sync.Pool{ New: func() interface{} {
New: func() interface{} { return new(Authentication)
return new(Authentication) },
}, }
}
)
func getAuthenticationObject() *Authentication { func getAuthenticationObject() *Authentication {
return authPool.Get().(*Authentication) return authPool.Get().(*Authentication)

View File

@ -13,8 +13,7 @@ import (
"github.com/v2fly/v2ray-core/v4/transport/internet" "github.com/v2fly/v2ray-core/v4/transport/internet"
) )
type Client struct { type Client struct{}
}
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
return &Client{}, nil return &Client{}, nil
@ -62,7 +61,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return buf.Copy(connReader, link.Writer) return buf.Copy(connReader, link.Writer)
} }
var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(response, task.Close(link.Writer))
if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

View File

@ -21,15 +21,13 @@ import (
"github.com/v2fly/v2ray-core/v4/transport/internet" "github.com/v2fly/v2ray-core/v4/transport/internet"
) )
var ( var dcList = []net.Address{
dcList = []net.Address{ net.ParseAddress("149.154.175.50"),
net.ParseAddress("149.154.175.50"), net.ParseAddress("149.154.167.51"),
net.ParseAddress("149.154.167.51"), net.ParseAddress("149.154.175.100"),
net.ParseAddress("149.154.175.100"), net.ParseAddress("149.154.167.91"),
net.ParseAddress("149.154.167.91"), net.ParseAddress("149.154.171.5"),
net.ParseAddress("149.154.171.5"), }
}
)
type Server struct { type Server struct {
user *protocol.User user *protocol.User
@ -65,8 +63,10 @@ func (s *Server) Network() []net.Network {
return []net.Network{net.Network_TCP} return []net.Network{net.Network_TCP}
} }
var ctype1 = []byte{0xef, 0xef, 0xef, 0xef} var (
var ctype2 = []byte{0xee, 0xee, 0xee, 0xee} ctype1 = []byte{0xef, 0xef, 0xef, 0xef}
ctype2 = []byte{0xee, 0xee, 0xee, 0xee}
)
func isValidConnectionType(c [4]byte) bool { func isValidConnectionType(c [4]byte) bool {
if bytes.Equal(c[:], ctype1) { if bytes.Equal(c[:], ctype1) {
@ -145,7 +145,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn internet
return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)) return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
} }
var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(response, task.Close(link.Writer))
if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)

View File

@ -127,7 +127,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer)) return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
} }
var responseDoneAndCloseWriter = task.OnSuccess(responseDone, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }
@ -164,7 +164,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return nil return nil
} }
var responseDoneAndCloseWriter = task.OnSuccess(responseDone, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

View File

@ -222,7 +222,7 @@ func (s *Server) handleConnection(ctx context.Context, conn internet.Connection,
return nil return nil
} }
var requestDoneAndCloseWriter = task.OnSuccess(requestDone, task.Close(link.Writer)) requestDoneAndCloseWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil { if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)

View File

@ -149,7 +149,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
} }
} }
var responseDonePost = task.OnSuccess(responseFunc, task.Close(link.Writer)) responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

View File

@ -177,7 +177,7 @@ func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writ
return nil return nil
} }
var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer)) requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil { if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)
@ -220,7 +220,6 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn internet.Connection,
for _, payload := range mpayload { for _, payload := range mpayload {
request, err := DecodeUDPPacket(payload) request, err := DecodeUDPPacket(payload)
if err != nil { if err != nil {
newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx)) newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx))
payload.Release() payload.Release()

View File

@ -131,7 +131,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)) return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
} }
var responseDoneAndCloseWriter = task.OnSuccess(getResponse, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

View File

@ -275,7 +275,7 @@ func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Sess
return nil return nil
} }
var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer)) requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil { if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Must(common.Interrupt(link.Reader)) common.Must(common.Interrupt(link.Reader))
common.Must(common.Interrupt(link.Writer)) common.Must(common.Interrupt(link.Writer))

View File

@ -40,7 +40,6 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte {
} }
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderLengthAEADAESBlock) payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderLengthAEADAESBlock)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }
@ -61,7 +60,6 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte {
} }
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }
@ -69,7 +67,7 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte {
payloadHeaderAEADEncrypted = payloadHeaderAEAD.Seal(nil, payloadHeaderAEADNonce, data, generatedAuthID[:]) payloadHeaderAEADEncrypted = payloadHeaderAEAD.Seal(nil, payloadHeaderAEADNonce, data, generatedAuthID[:])
} }
var outputBuffer = bytes.NewBuffer(nil) outputBuffer := bytes.NewBuffer(nil)
common.Must2(outputBuffer.Write(generatedAuthID[:])) // 16 common.Must2(outputBuffer.Write(generatedAuthID[:])) // 16
common.Must2(outputBuffer.Write(payloadHeaderLengthAEADEncrypted)) // 2+16 common.Must2(outputBuffer.Write(payloadHeaderLengthAEADEncrypted)) // 2+16
@ -112,7 +110,6 @@ func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte,
} }
payloadHeaderLengthAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) payloadHeaderLengthAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }
@ -154,7 +151,6 @@ func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte,
} }
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }

View File

@ -16,7 +16,7 @@ func TestOpenVMessAEADHeader(t *testing.T) {
copy(keyw[:], key) copy(keyw[:], key)
sealed := SealVMessAEADHeader(keyw, TestHeader) sealed := SealVMessAEADHeader(keyw, TestHeader)
var AEADR = bytes.NewReader(sealed) AEADR := bytes.NewReader(sealed)
var authid [16]byte var authid [16]byte
@ -35,7 +35,7 @@ func TestOpenVMessAEADHeader2(t *testing.T) {
copy(keyw[:], key) copy(keyw[:], key)
sealed := SealVMessAEADHeader(keyw, TestHeader) sealed := SealVMessAEADHeader(keyw, TestHeader)
var AEADR = bytes.NewReader(sealed) AEADR := bytes.NewReader(sealed)
var authid [16]byte var authid [16]byte
@ -57,7 +57,7 @@ func TestOpenVMessAEADHeader4(t *testing.T) {
var sealedm [16]byte var sealedm [16]byte
copy(sealedm[:], sealed) copy(sealedm[:], sealed)
sealed[i] ^= 0xff sealed[i] ^= 0xff
var AEADR = bytes.NewReader(sealed) AEADR := bytes.NewReader(sealed)
var authid [16]byte var authid [16]byte
@ -85,7 +85,7 @@ func TestOpenVMessAEADHeader4Massive(t *testing.T) {
var sealedm [16]byte var sealedm [16]byte
copy(sealedm[:], sealed) copy(sealedm[:], sealed)
sealed[i] ^= 0xff sealed[i] ^= 0xff
var AEADR = bytes.NewReader(sealed) AEADR := bytes.NewReader(sealed)
var authid [16]byte var authid [16]byte

View File

@ -38,8 +38,7 @@ func (NoOpAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]
} }
// FnvAuthenticator is an AEAD based on Fnv hash. // FnvAuthenticator is an AEAD based on Fnv hash.
type FnvAuthenticator struct { type FnvAuthenticator struct{}
}
// NonceSize implements AEAD.NonceSize(). // NonceSize implements AEAD.NonceSize().
func (*FnvAuthenticator) NonceSize() int { func (*FnvAuthenticator) NonceSize() int {

View File

@ -77,8 +77,7 @@ type CommandFactory interface {
Unmarshal(data []byte) (interface{}, error) Unmarshal(data []byte) (interface{}, error)
} }
type CommandSwitchAccountFactory struct { type CommandSwitchAccountFactory struct{}
}
func (f *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error { func (f *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error {
cmd, ok := command.(*protocol.CommandSwitchAccount) cmd, ok := command.(*protocol.CommandSwitchAccount)

View File

@ -306,7 +306,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection i
return transferResponse(timer, svrSession, request, response, link.Reader, writer) return transferResponse(timer, svrSession, request, response, link.Reader, writer)
} }
var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer)) requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil { if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)
@ -352,15 +352,17 @@ func (h *Handler) generateCommand(ctx context.Context, request *protocol.Request
return nil return nil
} }
var aeadForced = false var (
var aeadForced2022 = false aeadForced = false
aeadForced2022 = false
)
func init() { func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config)) return New(ctx, config.(*Config))
})) }))
var defaultFlagValue = "NOT_DEFINED_AT_ALL" defaultFlagValue := "NOT_DEFINED_AT_ALL"
if time.Now().Year() >= 2022 { if time.Now().Year() >= 2022 {
defaultFlagValue = "true_by_default_2022" defaultFlagValue = "true_by_default_2022"

View File

@ -175,7 +175,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
return buf.Copy(bodyReader, output, buf.UpdateActivity(timer)) return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
} }
var responseDonePost = task.OnSuccess(responseDone, task.Close(output)) responseDonePost := task.OnSuccess(responseDone, task.Close(output))
if err := task.Run(ctx, requestDone, responseDonePost); err != nil { if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

View File

@ -97,7 +97,6 @@ func (server *Server) handleConnection(conn net.Conn) {
} }
} }
}) })
if err != nil { if err != nil {
fmt.Println("failed to transfer data: ", err.Error()) fmt.Println("failed to transfer data: ", err.Error())
} }

View File

@ -20,9 +20,7 @@ type Dialer interface {
// dialFunc is an interface to dial network connection to a specific destination. // dialFunc is an interface to dial network connection to a specific destination.
type dialFunc func(ctx context.Context, dest net.Destination, streamSettings *MemoryStreamConfig) (Connection, error) type dialFunc func(ctx context.Context, dest net.Destination, streamSettings *MemoryStreamConfig) (Connection, error)
var ( var transportDialerCache = make(map[string]dialFunc)
transportDialerCache = make(map[string]dialFunc)
)
// RegisterTransportDialer registers a Dialer with given name. // RegisterTransportDialer registers a Dialer with given name.
func RegisterTransportDialer(protocol string, dialer dialFunc) error { func RegisterTransportDialer(protocol string, dialer dialFunc) error {

View File

@ -8,8 +8,10 @@ import (
"github.com/v2fly/v2ray-core/v4/transport/internet" "github.com/v2fly/v2ray-core/v4/transport/internet"
) )
const protocolName = "domainsocket" const (
const sizeofSunPath = 108 protocolName = "domainsocket"
sizeofSunPath = 108
)
func (c *Config) GetUnixAddr() (*net.UnixAddr, error) { func (c *Config) GetUnixAddr() (*net.UnixAddr, error) {
path := c.Path path := c.Path

View File

@ -44,14 +44,13 @@ func dialgRPC(ctx context.Context, dest net.Destination, streamSettings *interne
grpcSettings := streamSettings.ProtocolSettings.(*Config) grpcSettings := streamSettings.ProtocolSettings.(*Config)
config := tls.ConfigFromStreamSettings(streamSettings) config := tls.ConfigFromStreamSettings(streamSettings)
var dialOption = grpc.WithInsecure() dialOption := grpc.WithInsecure()
if config != nil { if config != nil {
dialOption = grpc.WithTransportCredentials(credentials.NewTLS(config.GetTLSConfig())) dialOption = grpc.WithTransportCredentials(credentials.NewTLS(config.GetTLSConfig()))
} }
conn, err := getGrpcClient(ctx, dest, dialOption) conn, err := getGrpcClient(ctx, dest, dialOption)
if err != nil { if err != nil {
return nil, newError("Cannot dial grpc").Base(err) return nil, newError("Cannot dial grpc").Base(err)
} }

View File

@ -15,9 +15,7 @@ import (
"github.com/v2fly/v2ray-core/v4/transport/internet/tls" "github.com/v2fly/v2ray-core/v4/transport/internet/tls"
) )
var ( var globalConv = uint32(dice.RollUint16())
globalConv = uint32(dice.RollUint16())
)
func fetchInput(_ context.Context, input io.Reader, reader PacketReader, conn *Connection) { func fetchInput(_ context.Context, input io.Reader, reader PacketReader, conn *Connection) {
cache := make(chan *buf.Buffer, 1024) cache := make(chan *buf.Buffer, 1024)

View File

@ -99,7 +99,6 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti
IP: address.IP(), IP: address.IP(),
Port: int(port), Port: int(port),
}, streamSettings.SocketSettings) }, streamSettings.SocketSettings)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -15,8 +15,10 @@ import (
// //
// //
const protocolName = "quic" const (
const internalDomain = "quic.internal.v2fly.org" protocolName = "quic"
internalDomain = "quic.internal.v2fly.org"
)
func init() { func init() {
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} { common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {

View File

@ -45,6 +45,7 @@ func ioctl(s uintptr, ioc int, b []byte) error {
} }
return nil return nil
} }
func (nl *pfiocNatlook) rdPort() int { func (nl *pfiocNatlook) rdPort() int {
return int(binary.BigEndian.Uint16((*[2]byte)(unsafe.Pointer(&nl.Rdport))[:])) return int(binary.BigEndian.Uint16((*[2]byte)(unsafe.Pointer(&nl.Rdport))[:]))
} }

View File

@ -25,7 +25,6 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
if err := setTFO(syscall.Handle(fd), config.Tfo); err != nil { if err := setTFO(syscall.Handle(fd), config.Tfo); err != nil {
return err return err
} }
} }
return nil return nil

View File

@ -9,9 +9,7 @@ import (
"github.com/v2fly/v2ray-core/v4/common/session" "github.com/v2fly/v2ray-core/v4/common/session"
) )
var ( var effectiveSystemDialer SystemDialer = &DefaultSystemDialer{}
effectiveSystemDialer SystemDialer = &DefaultSystemDialer{}
)
type SystemDialer interface { type SystemDialer interface {
Dial(ctx context.Context, source net.Address, destination net.Destination, sockopt *SocketConfig) (net.Conn, error) Dial(ctx context.Context, source net.Address, destination net.Destination, sockopt *SocketConfig) (net.Conn, error)

View File

@ -11,9 +11,7 @@ import (
"github.com/v2fly/v2ray-core/v4/common/session" "github.com/v2fly/v2ray-core/v4/common/session"
) )
var ( var effectiveListener = DefaultListener{}
effectiveListener = DefaultListener{}
)
type controller func(network, address string, fd uintptr) error type controller func(network, address string, fd uintptr) error

View File

@ -6,9 +6,7 @@ import (
"github.com/v2fly/v2ray-core/v4/common/net" "github.com/v2fly/v2ray-core/v4/common/net"
) )
var ( var transportListenerCache = make(map[string]ListenFunc)
transportListenerCache = make(map[string]ListenFunc)
)
func RegisterTransportListener(protocol string, listener ListenFunc) error { func RegisterTransportListener(protocol string, listener ListenFunc) error {
if _, found := transportListenerCache[protocol]; found { if _, found := transportListenerCache[protocol]; found {
@ -48,6 +46,7 @@ func ListenUnix(ctx context.Context, address net.Address, settings *MemoryStream
} }
return listener, nil return listener, nil
} }
func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error) { func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error) {
if settings == nil { if settings == nil {
s, err := ToMemoryStreamConfig(nil) s, err := ToMemoryStreamConfig(nil)

View File

@ -16,9 +16,7 @@ import (
"github.com/v2fly/v2ray-core/v4/transport/internet" "github.com/v2fly/v2ray-core/v4/transport/internet"
) )
var ( var globalSessionCache = tls.NewLRUClientSessionCache(128)
globalSessionCache = tls.NewLRUClientSessionCache(128)
)
const exp8357 = "experiment:8357" const exp8357 = "experiment:8357"

View File

@ -11,9 +11,7 @@ import (
//go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
var ( var _ buf.Writer = (*Conn)(nil)
_ buf.Writer = (*Conn)(nil)
)
type Conn struct { type Conn struct {
*tls.Conn *tls.Conn

View File

@ -15,9 +15,7 @@ import (
"github.com/v2fly/v2ray-core/v4/common/serial" "github.com/v2fly/v2ray-core/v4/common/serial"
) )
var ( var _ buf.Writer = (*connection)(nil)
_ buf.Writer = (*connection)(nil)
)
// connection is a wrapper for net.Conn over WebSocket connection. // connection is a wrapper for net.Conn over WebSocket connection.
type connection struct { type connection struct {

View File

@ -142,8 +142,8 @@ func ListenWS(ctx context.Context, address net.Address, port net.Port, streamSet
} }
l.listener = listener l.listener = listener
var useEarlyData = false useEarlyData := false
var earlyDataHeaderName = "" earlyDataHeaderName := ""
if wsSettings.MaxEarlyData != 0 { if wsSettings.MaxEarlyData != 0 {
useEarlyData = true useEarlyData = true
earlyDataHeaderName = wsSettings.EarlyDataHeaderName earlyDataHeaderName = wsSettings.EarlyDataHeaderName

View File

@ -40,8 +40,10 @@ type pipe struct {
state state state state
} }
var errBufferFull = errors.New("buffer full") var (
var errSlowDown = errors.New("slow down") errBufferFull = errors.New("buffer full")
errSlowDown = errors.New("slow down")
)
func (p *pipe) getState(forRead bool) error { func (p *pipe) getState(forRead bool) error {
switch p.state { switch p.state {

View File

@ -159,7 +159,7 @@ func RequireFeatures(ctx context.Context, callback interface{}) error {
// The instance is not started at this point. // The instance is not started at this point.
// To ensure V2Ray instance works properly, the config must contain one Dispatcher, one InboundHandlerManager and one OutboundHandlerManager. Other features are optional. // To ensure V2Ray instance works properly, the config must contain one Dispatcher, one InboundHandlerManager and one OutboundHandlerManager. Other features are optional.
func New(config *Config) (*Instance, error) { func New(config *Config) (*Instance, error) {
var server = &Instance{ctx: context.Background()} server := &Instance{ctx: context.Background()}
done, err := initInstanceWithConfig(config, server) done, err := initInstanceWithConfig(config, server)
if done { if done {
@ -170,7 +170,7 @@ func New(config *Config) (*Instance, error) {
} }
func NewWithContext(ctx context.Context, config *Config) (*Instance, error) { func NewWithContext(ctx context.Context, config *Config) (*Instance, error) {
var server = &Instance{ctx: ctx} server := &Instance{ctx: ctx}
done, err := initInstanceWithConfig(config, server) done, err := initInstanceWithConfig(config, server)
if done { if done {