Skip to content

Commit

Permalink
replace zhangyunhao116/fastrand to metacubex/randv2
Browse files Browse the repository at this point in the history
  • Loading branch information
wwqgtxx committed May 31, 2024
1 parent d38e141 commit 7b1e83c
Show file tree
Hide file tree
Showing 26 changed files with 101 additions and 76 deletions.
4 changes: 2 additions & 2 deletions adapter/outbound/hysteria2.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ import (

"github.com/metacubex/sing-quic/hysteria2"

"github.com/metacubex/randv2"
M "github.com/sagernet/sing/common/metadata"
"github.com/zhangyunhao116/fastrand"
)

func init() {
Expand Down Expand Up @@ -165,7 +165,7 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
})
if len(serverAddress) > 0 {
clientOptions.ServerAddress = func(ctx context.Context) (*net.UDPAddr, error) {
return resolveUDPAddr(ctx, "udp", serverAddress[fastrand.Intn(len(serverAddress))])
return resolveUDPAddr(ctx, "udp", serverAddress[randv2.IntN(len(serverAddress))])
}

if option.HopInterval == 0 {
Expand Down
8 changes: 4 additions & 4 deletions adapter/outbound/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
"github.com/metacubex/mihomo/component/proxydialer"
C "github.com/metacubex/mihomo/constant"

"github.com/zhangyunhao116/fastrand"
"github.com/metacubex/randv2"
"golang.org/x/crypto/ssh"
)

Expand Down Expand Up @@ -180,10 +180,10 @@ func NewSsh(option SshOption) (*Ssh, error) {
}

version := "SSH-2.0-OpenSSH_"
if fastrand.Intn(2) == 0 {
version += "7." + strconv.Itoa(fastrand.Intn(10))
if randv2.IntN(2) == 0 {
version += "7." + strconv.Itoa(randv2.IntN(10))
} else {
version += "8." + strconv.Itoa(fastrand.Intn(9))
version += "8." + strconv.Itoa(randv2.IntN(9))
}
config.ClientVersion = version

Expand Down
4 changes: 2 additions & 2 deletions common/pool/alloc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package pool
import (
"testing"

"github.com/metacubex/randv2"
"github.com/stretchr/testify/assert"
"github.com/zhangyunhao116/fastrand"
)

func TestAllocGet(t *testing.T) {
Expand Down Expand Up @@ -43,6 +43,6 @@ func TestAllocPutThenGet(t *testing.T) {

func BenchmarkMSB(b *testing.B) {
for i := 0; i < b.N; i++ {
msb(fastrand.Int())
msb(randv2.Int())
}
}
38 changes: 29 additions & 9 deletions common/utils/uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,39 @@ package utils

import (
"github.com/gofrs/uuid/v5"
"github.com/zhangyunhao116/fastrand"
"github.com/metacubex/randv2"
)

type fastRandReader struct{}
type unsafeRandReader struct{}

func (r fastRandReader) Read(p []byte) (int, error) {
return fastrand.Read(p)
func (r unsafeRandReader) Read(p []byte) (n int, err error) {
// modify from https://github.com/golang/go/blob/587c3847da81aa7cfc3b3db2677c8586c94df13a/src/runtime/rand.go#L70-L89
// Inspired by wyrand.
n = len(p)
v := randv2.Uint64()
for len(p) > 0 {
v ^= 0xa0761d6478bd642f
v *= 0xe7037ed1a0b428db
size := 8
if len(p) < 8 {
size = len(p)
}
for i := 0; i < size; i++ {
p[i] ^= byte(v >> (8 * i))
}
p = p[size:]
v = v>>32 | v<<32
}

return
}

var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(fastRandReader{}))
var UnsafeRandReader = unsafeRandReader{}

var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(UnsafeRandReader))

func NewUUIDV1() uuid.UUID {
u, _ := UnsafeUUIDGenerator.NewV1() // fastrand.Read wouldn't cause error, so ignore err is safe
u, _ := UnsafeUUIDGenerator.NewV1() // unsafeRandReader wouldn't cause error, so ignore err is safe
return u
}

Expand All @@ -23,7 +43,7 @@ func NewUUIDV3(ns uuid.UUID, name string) uuid.UUID {
}

func NewUUIDV4() uuid.UUID {
u, _ := UnsafeUUIDGenerator.NewV4() // fastrand.Read wouldn't cause error, so ignore err is safe
u, _ := UnsafeUUIDGenerator.NewV4() // unsafeRandReader wouldn't cause error, so ignore err is safe
return u
}

Expand All @@ -32,12 +52,12 @@ func NewUUIDV5(ns uuid.UUID, name string) uuid.UUID {
}

func NewUUIDV6() uuid.UUID {
u, _ := UnsafeUUIDGenerator.NewV6() // fastrand.Read wouldn't cause error, so ignore err is safe
u, _ := UnsafeUUIDGenerator.NewV6() // unsafeRandReader wouldn't cause error, so ignore err is safe
return u
}

func NewUUIDV7() uuid.UUID {
u, _ := UnsafeUUIDGenerator.NewV7() // fastrand.Read wouldn't cause error, so ignore err is safe
u, _ := UnsafeUUIDGenerator.NewV7() // unsafeRandReader wouldn't cause error, so ignore err is safe
return u
}

Expand Down
10 changes: 5 additions & 5 deletions component/resolver/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (

"github.com/metacubex/mihomo/component/trie"

"github.com/metacubex/randv2"
"github.com/miekg/dns"
"github.com/zhangyunhao116/fastrand"
)

var (
Expand Down Expand Up @@ -89,7 +89,7 @@ func ResolveIPv4WithResolver(ctx context.Context, host string, r Resolver) (neti
} else if len(ips) == 0 {
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
}
return ips[fastrand.Intn(len(ips))], nil
return ips[randv2.IntN(len(ips))], nil
}

// ResolveIPv4 with a host, return ipv4
Expand Down Expand Up @@ -143,7 +143,7 @@ func ResolveIPv6WithResolver(ctx context.Context, host string, r Resolver) (neti
} else if len(ips) == 0 {
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
}
return ips[fastrand.Intn(len(ips))], nil
return ips[randv2.IntN(len(ips))], nil
}

func ResolveIPv6(ctx context.Context, host string) (netip.Addr, error) {
Expand Down Expand Up @@ -194,9 +194,9 @@ func ResolveIPWithResolver(ctx context.Context, host string, r Resolver) (netip.
}
ipv4s, ipv6s := SortationAddr(ips)
if len(ipv4s) > 0 {
return ipv4s[fastrand.Intn(len(ipv4s))], nil
return ipv4s[randv2.IntN(len(ipv4s))], nil
}
return ipv6s[fastrand.Intn(len(ipv6s))], nil
return ipv6s[randv2.IntN(len(ipv6s))], nil
}

// ResolveIP with a host, return ip and priority return TypeA
Expand Down
4 changes: 2 additions & 2 deletions dns/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import (
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"

"github.com/metacubex/randv2"
D "github.com/miekg/dns"
"github.com/zhangyunhao116/fastrand"
)

type client struct {
Expand Down Expand Up @@ -67,7 +67,7 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
} else if len(ips) == 0 {
return nil, fmt.Errorf("%w: %s", resolver.ErrIPNotFound, c.host)
}
ip = ips[fastrand.Intn(len(ips))]
ip = ips[randv2.IntN(len(ips))]
}

network := "udp"
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/insomniacslk/dhcp v0.0.0-20240419123447-f1cffa2c0c49
github.com/mdlayher/netlink v1.7.2
github.com/metacubex/quic-go v0.44.1-0.20240521004242-fcd70d587e22
github.com/metacubex/randv2 v0.2.0
github.com/metacubex/sing-quic v0.0.0-20240518034124-7696d3f7da72
github.com/metacubex/sing-shadowsocks v0.2.6
github.com/metacubex/sing-shadowsocks2 v0.2.0
Expand Down Expand Up @@ -98,4 +99,4 @@ require (
golang.org/x/tools v0.21.0 // indirect
)

replace github.com/sagernet/sing => github.com/metacubex/sing v0.0.0-20240518125217-e63d65a914d1
replace github.com/sagernet/sing => github.com/metacubex/sing v0.0.0-20240518125217-e63d65a914d1
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ github.com/metacubex/gvisor v0.0.0-20240320004321-933faba989ec h1:HxreOiFTUrJXJa
github.com/metacubex/gvisor v0.0.0-20240320004321-933faba989ec/go.mod h1:8BVmQ+3cxjqzWElafm24rb2Ae4jRI6vAXNXWqWjfrXw=
github.com/metacubex/quic-go v0.44.1-0.20240521004242-fcd70d587e22 h1:hsQ0b2A509b6ubnLtLOcUgZ8vOb+d/667zVEJ1T2fao=
github.com/metacubex/quic-go v0.44.1-0.20240521004242-fcd70d587e22/go.mod h1:88wAATpevav4xdy5N8oejQ2cbbI6EcLYEklFeo+qywA=
github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs=
github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY=
github.com/metacubex/sing v0.0.0-20240518125217-e63d65a914d1 h1:7hDHLTmjgtRoAp59STwPQpe5Pinwi4cWex+FB3Ohvco=
github.com/metacubex/sing v0.0.0-20240518125217-e63d65a914d1/go.mod h1:+60H3Cm91RnL9dpVGWDPHt0zTQImO9Vfqt9a4rSambI=
github.com/metacubex/sing-quic v0.0.0-20240518034124-7696d3f7da72 h1:Wr4g1HCb5Z/QIFwFiVNjO2qL+dRu25+Mdn9xtAZZ+ew=
Expand Down
7 changes: 4 additions & 3 deletions transport/simple-obfs/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package obfs

import (
"bytes"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
Expand All @@ -10,7 +11,7 @@ import (

"github.com/metacubex/mihomo/common/pool"

"github.com/zhangyunhao116/fastrand"
"github.com/metacubex/randv2"
)

// HTTPObfs is shadowsocks http simple-obfs implementation
Expand Down Expand Up @@ -64,12 +65,12 @@ func (ho *HTTPObfs) Read(b []byte) (int, error) {
func (ho *HTTPObfs) Write(b []byte) (int, error) {
if ho.firstRequest {
randBytes := make([]byte, 16)
fastrand.Read(randBytes)
rand.Read(randBytes)
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s/", ho.host), bytes.NewBuffer(b[:]))
if err != nil {
return 0, err
}
req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", fastrand.Int()%54, fastrand.Int()%2))
req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", randv2.Int()%54, randv2.Int()%2))
req.Header.Set("Upgrade", "websocket")
req.Header.Set("Connection", "Upgrade")
req.Host = ho.host
Expand Down
10 changes: 5 additions & 5 deletions transport/ssr/obfs/http_simple.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

"github.com/metacubex/mihomo/common/pool"

"github.com/zhangyunhao116/fastrand"
"github.com/metacubex/randv2"
)

func init() {
Expand Down Expand Up @@ -82,7 +82,7 @@ func (c *httpConn) Write(b []byte) (int, error) {
bLength := len(b)
headDataLength := bLength
if bLength-headLength > 64 {
headDataLength = headLength + fastrand.Intn(65)
headDataLength = headLength + randv2.IntN(65)
}
headData := b[:headDataLength]
b = b[headDataLength:]
Expand All @@ -100,7 +100,7 @@ func (c *httpConn) Write(b []byte) (int, error) {
}
}
hosts := strings.Split(host, ",")
host = hosts[fastrand.Intn(len(hosts))]
host = hosts[randv2.IntN(len(hosts))]

buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
Expand All @@ -119,7 +119,7 @@ func (c *httpConn) Write(b []byte) (int, error) {
buf.WriteString(body + "\r\n\r\n")
} else {
buf.WriteString("User-Agent: ")
buf.WriteString(userAgent[fastrand.Intn(len(userAgent))])
buf.WriteString(userAgent[randv2.IntN(len(userAgent))])
buf.WriteString("\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Encoding: gzip, deflate\r\n")
if c.post {
packBoundary(buf)
Expand Down Expand Up @@ -147,7 +147,7 @@ func packBoundary(buf *bytes.Buffer) {
buf.WriteString("Content-Type: multipart/form-data; boundary=")
set := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for i := 0; i < 32; i++ {
buf.WriteByte(set[fastrand.Intn(62)])
buf.WriteByte(set[randv2.IntN(62)])
}
buf.WriteString("\r\n")
}
Expand Down
4 changes: 2 additions & 2 deletions transport/ssr/obfs/random_head.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

"github.com/metacubex/mihomo/common/pool"

"github.com/zhangyunhao116/fastrand"
"github.com/metacubex/randv2"
)

func init() {
Expand Down Expand Up @@ -55,7 +55,7 @@ func (c *randomHeadConn) Write(b []byte) (int, error) {
c.buf = append(c.buf, b...)
if !c.hasSentHeader {
c.hasSentHeader = true
dataLength := fastrand.Intn(96) + 4
dataLength := randv2.IntN(96) + 4
buf := pool.Get(dataLength + 4)
defer pool.Put(buf)
rand.Read(buf[:dataLength])
Expand Down
8 changes: 4 additions & 4 deletions transport/ssr/obfs/tls1.2_ticket_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"github.com/metacubex/mihomo/common/pool"
"github.com/metacubex/mihomo/transport/ssr/tools"

"github.com/zhangyunhao116/fastrand"
"github.com/metacubex/randv2"
)

func init() {
Expand Down Expand Up @@ -92,7 +92,7 @@ func (c *tls12TicketConn) Write(b []byte) (int, error) {
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
for len(b) > 2048 {
size := fastrand.Intn(4096) + 100
size := randv2.IntN(4096) + 100
if len(b) < size {
size = len(b)
}
Expand Down Expand Up @@ -198,7 +198,7 @@ func packSNIData(buf *bytes.Buffer, u string) {
}

func (c *tls12TicketConn) packTicketBuf(buf *bytes.Buffer, u string) {
length := 16 * (fastrand.Intn(17) + 8)
length := 16 * (randv2.IntN(17) + 8)
buf.Write([]byte{0, 0x23})
binary.Write(buf, binary.BigEndian, uint16(length))
tools.AppendRandBytes(buf, length)
Expand All @@ -223,6 +223,6 @@ func (t *tls12Ticket) getHost() string {
host = ""
}
hosts := strings.Split(host, ",")
host = hosts[fastrand.Intn(len(hosts))]
host = hosts[randv2.IntN(len(hosts))]
return host
}
14 changes: 7 additions & 7 deletions transport/ssr/protocol/auth_aes128_sha1.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/transport/ssr/tools"

"github.com/zhangyunhao116/fastrand"
"github.com/metacubex/randv2"
)

type (
Expand Down Expand Up @@ -201,7 +201,7 @@ func (a *authAES128) packData(poolBuf *bytes.Buffer, data []byte, fullDataLength
}

func trapezoidRandom(max int, d float64) int {
base := fastrand.Float64()
base := randv2.Float64()
if d-0 > 1e-6 {
a := 1 - d
base = (math.Sqrt(a*a+4*d*base) - a) / (2 * d)
Expand All @@ -222,10 +222,10 @@ func (a *authAES128) getRandDataLengthForPackData(dataLength, fullDataLength int
if revLength > -1460 {
return trapezoidRandom(revLength+1460, -0.3)
}
return fastrand.Intn(32)
return randv2.IntN(32)
}
if dataLength > 900 {
return fastrand.Intn(revLength)
return randv2.IntN(revLength)
}
return trapezoidRandom(revLength, -0.3)
}
Expand All @@ -250,7 +250,7 @@ func (a *authAES128) packAuthData(poolBuf *bytes.Buffer, data []byte) {
copy(macKey, a.iv)
copy(macKey[len(a.iv):], a.Key)

poolBuf.WriteByte(byte(fastrand.Intn(256)))
poolBuf.WriteByte(byte(randv2.IntN(256)))
poolBuf.Write(a.hmac(macKey, poolBuf.Bytes())[:6])
poolBuf.Write(a.userID[:])
err := a.authData.putEncryptedData(poolBuf, a.userKey, [2]int{packedAuthDataLength, randDataLength}, a.salt)
Expand All @@ -266,9 +266,9 @@ func (a *authAES128) packAuthData(poolBuf *bytes.Buffer, data []byte) {

func (a *authAES128) getRandDataLengthForPackAuthData(size int) int {
if size > 400 {
return fastrand.Intn(512)
return randv2.IntN(512)
}
return fastrand.Intn(1024)
return randv2.IntN(1024)
}

func (a *authAES128) packRandData(poolBuf *bytes.Buffer, size int) {
Expand Down
Loading

0 comments on commit 7b1e83c

Please sign in to comment.