repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/client.go | proxy/shadowsocks2022/client.go | package shadowsocks2022
import (
"context"
gonet "net"
"sync"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/environment"
"github.com/v2fly/v2ray-core/v5/common/environment/envctx"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
type Client struct {
config *ClientConfig
ctx context.Context
}
const UDPConnectionState = "UDPConnectionState"
type ClientUDPConnState struct {
session *ClientUDPSession
initOnce *sync.Once
}
func (c *ClientUDPConnState) GetOrCreateSession(create func() (*ClientUDPSession, error)) (*ClientUDPSession, error) {
var errOuter error
c.initOnce.Do(func() {
sessionState, err := create()
if err != nil {
errOuter = newError("failed to create UDP session").Base(err)
return
}
c.session = sessionState
})
if errOuter != nil {
return nil, newError("failed to initialize UDP State").Base(errOuter)
}
return c.session, nil
}
func NewClientUDPConnState() (*ClientUDPConnState, error) {
return &ClientUDPConnState{initOnce: &sync.Once{}}, nil
}
func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified")
}
destination := outbound.Target
network := destination.Network
keyDerivation := newBLAKE3KeyDerivation()
var method Method
switch c.config.Method {
case "2022-blake3-aes-128-gcm":
method = newAES128GCMMethod()
case "2022-blake3-aes-256-gcm":
method = newAES256GCMMethod()
default:
return newError("unknown method: ", c.config.Method)
}
effectivePsk := c.config.Psk
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, time.Minute)
if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil {
udpSession, err := c.getUDPSession(c.ctx, network, dialer, method, keyDerivation)
if err != nil {
return newError("failed to get UDP udpSession").Base(err)
}
requestDone := func() error {
return udp.CopyPacketConn(udpSession, packetConn, udp.UpdateActivity(timer))
}
responseDone := func() error {
return udp.CopyPacketConn(packetConn, udpSession, udp.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
if network == net.Network_TCP {
var conn internet.Connection
err := retry.ExponentialBackoff(5, 100).On(func() error {
dest := net.TCPDestination(c.config.Address.AsAddress(), net.Port(c.config.Port))
dest.Network = network
rawConn, err := dialer.Dial(ctx, dest)
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
return newError("failed to find an available destination").AtWarning().Base(err)
}
newError("tunneling request to ", destination, " via ", network, ":", net.TCPDestination(c.config.Address.AsAddress(), net.Port(c.config.Port)).NetAddr()).WriteToLog(session.ExportIDToError(ctx))
defer conn.Close()
request := &TCPRequest{
keyDerivation: keyDerivation,
method: method,
}
TCPRequestBuffer := buf.New()
defer TCPRequestBuffer.Release()
err = request.EncodeTCPRequestHeader(effectivePsk, c.config.Ipsk, destination.Address,
int(destination.Port), nil, TCPRequestBuffer)
if err != nil {
return newError("failed to encode TCP request header").Base(err)
}
_, err = conn.Write(TCPRequestBuffer.Bytes())
if err != nil {
return newError("failed to write TCP request header").Base(err)
}
requestDone := func() error {
encodedWriter := request.CreateClientC2SWriter(conn)
return buf.Copy(link.Reader, encodedWriter, buf.UpdateActivity(timer))
}
responseDone := func() error {
err = request.DecodeTCPResponseHeader(effectivePsk, conn)
if err != nil {
return newError("failed to decode TCP response header").Base(err)
}
if err = request.CheckC2SConnectionConstraint(); err != nil {
return newError("C2S connection constraint violation").Base(err)
}
initialPayload := buf.NewWithSize(65535)
encodedReader, err := request.CreateClientS2CReader(conn, initialPayload)
if err != nil {
return newError("failed to create client S2C reader").Base(err)
}
err = link.Writer.WriteMultiBuffer(buf.MultiBuffer{initialPayload})
if err != nil {
return newError("failed to write initial payload").Base(err)
}
return buf.Copy(encodedReader, link.Writer, buf.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
} else {
udpSession, err := c.getUDPSession(c.ctx, network, dialer, method, keyDerivation)
if err != nil {
return newError("failed to get UDP udpSession").Base(err)
}
monoDestUDPConn := udp.NewMonoDestUDPConn(udpSession, &gonet.UDPAddr{IP: destination.Address.IP(), Port: int(destination.Port)})
requestDone := func() error {
return buf.Copy(link.Reader, monoDestUDPConn, buf.UpdateActivity(timer))
}
responseDone := func() error {
return buf.Copy(monoDestUDPConn, link.Writer, buf.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
}
func (c *Client) getUDPSession(ctx context.Context, network net.Network, dialer internet.Dialer, method Method, keyDerivation *BLAKE3KeyDerivation) (internet.AbstractPacketConn, error) {
storage := envctx.EnvironmentFromContext(ctx).(environment.ProxyEnvironment).TransientStorage()
clientUDPStateIfce, err := storage.Get(ctx, UDPConnectionState)
if err != nil {
return nil, newError("failed to get UDP connection state").Base(err)
}
clientUDPState, ok := clientUDPStateIfce.(*ClientUDPConnState)
if !ok {
return nil, newError("failed to cast UDP connection state")
}
sessionState, err := clientUDPState.GetOrCreateSession(func() (*ClientUDPSession, error) {
var conn internet.Connection
err := retry.ExponentialBackoff(5, 100).On(func() error {
dest := net.TCPDestination(c.config.Address.AsAddress(), net.Port(c.config.Port))
dest.Network = network
rawConn, err := dialer.Dial(ctx, dest)
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
return nil, newError("failed to find an available destination").AtWarning().Base(err)
}
newError("creating udp session to ", network, ":", c.config.Address).WriteToLog(session.ExportIDToError(ctx))
packetProcessor, err := method.GetUDPClientProcessor(c.config.Ipsk, c.config.Psk, keyDerivation)
if err != nil {
return nil, newError("failed to create UDP client packet processor").Base(err)
}
return NewClientUDPSession(ctx, conn, packetProcessor), nil
})
if err != nil {
return nil, newError("failed to create UDP session").Base(err)
}
sessionConn, err := sessionState.NewSessionConn()
if err != nil {
return nil, newError("failed to create UDP session connection").Base(err)
}
return sessionConn, nil
}
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
storage := envctx.EnvironmentFromContext(ctx).(environment.ProxyEnvironment).TransientStorage()
udpState, err := NewClientUDPConnState()
if err != nil {
return nil, newError("failed to create UDP connection state").Base(err)
}
storage.Put(ctx, UDPConnectionState, udpState)
return &Client{
config: config,
ctx: ctx,
}, nil
}
func init() {
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
clientConfig, ok := config.(*ClientConfig)
if !ok {
return nil, newError("not a ClientConfig")
}
return NewClient(ctx, clientConfig)
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/ss2022.go | proxy/shadowsocks2022/ss2022.go | package shadowsocks2022
import (
"crypto/cipher"
"io"
"github.com/v2fly/struc"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type KeyDerivation interface {
GetSessionSubKey(effectivePsk, Salt []byte, OutKey []byte) error
GetIdentitySubKey(effectivePsk, Salt []byte, OutKey []byte) error
}
type Method interface {
GetSessionSubKeyAndSaltLength() int
GetStreamAEAD(SessionSubKey []byte) (cipher.AEAD, error)
GenerateEIH(CurrentIdentitySubKey []byte, nextPskHash []byte, out []byte) error
GetUDPClientProcessor(ipsk [][]byte, psk []byte, derivation KeyDerivation) (UDPClientPacketProcessor, error)
}
type ExtensibleIdentityHeaders interface {
struc.Custom
}
type DestinationAddress interface {
net.Address
}
type RequestSalt interface {
struc.Custom
isRequestSalt()
Bytes() []byte
FillAllFrom(reader io.Reader) error
}
type TCPRequestHeader1PreSessionKey struct {
Salt RequestSalt
EIH ExtensibleIdentityHeaders
}
type TCPRequestHeader2FixedLength struct {
Type byte
Timestamp uint64
HeaderLength uint16
}
type TCPRequestHeader3VariableLength struct {
DestinationAddress DestinationAddress
Contents struct {
PaddingLength uint16 `struc:"sizeof=Padding"`
Padding []byte
}
}
type TCPRequestHeader struct {
PreSessionKeyHeader TCPRequestHeader1PreSessionKey
FixedLengthHeader TCPRequestHeader2FixedLength
Header TCPRequestHeader3VariableLength
}
type TCPResponseHeader1PreSessionKey struct {
Salt RequestSalt
}
type TCPResponseHeader2FixedLength struct {
Type byte
Timestamp uint64
RequestSalt RequestSalt
InitialPayloadLength uint16
}
type TCPResponseHeader struct {
PreSessionKeyHeader TCPResponseHeader1PreSessionKey
Header TCPResponseHeader2FixedLength
}
const (
TCPHeaderTypeClientToServerStream = byte(0x00)
TCPHeaderTypeServerToClientStream = byte(0x01)
TCPMinPaddingLength = 0
TCPMaxPaddingLength = 900
)
var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6),
protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain),
)
type UDPRequest struct {
SessionID [8]byte
PacketID uint64
TimeStamp uint64
Address DestinationAddress
Port int
Payload *buf.Buffer
}
type UDPResponse struct {
UDPRequest
ClientSessionID [8]byte
}
const (
UDPHeaderTypeClientToServerStream = byte(0x00)
UDPHeaderTypeServerToClientStream = byte(0x01)
)
type UDPClientPacketProcessorCachedStateContainer interface {
GetCachedState(sessionID string) UDPClientPacketProcessorCachedState
PutCachedState(sessionID string, cache UDPClientPacketProcessorCachedState)
GetCachedServerState(serverSessionID string) UDPClientPacketProcessorCachedState
PutCachedServerState(serverSessionID string, cache UDPClientPacketProcessorCachedState)
}
type UDPClientPacketProcessorCachedState interface{}
// UDPClientPacketProcessor
// Caller retain and receive all ownership of the buffer
type UDPClientPacketProcessor interface {
EncodeUDPRequest(request *UDPRequest, out *buf.Buffer, cache UDPClientPacketProcessorCachedStateContainer) error
DecodeUDPResp(input []byte, resp *UDPResponse, cache UDPClientPacketProcessorCachedStateContainer) error
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/method_aes128gcm.go | proxy/shadowsocks2022/method_aes128gcm.go | package shadowsocks2022
import (
"crypto/aes"
"crypto/cipher"
)
func newAES128GCMMethod() *AES128GCMMethod {
return &AES128GCMMethod{}
}
type AES128GCMMethod struct{}
func (a AES128GCMMethod) GetSessionSubKeyAndSaltLength() int {
return 16
}
func (a AES128GCMMethod) GetStreamAEAD(sessionSubKey []byte) (cipher.AEAD, error) {
aesCipher, err := aes.NewCipher(sessionSubKey)
if err != nil {
return nil, newError("failed to create AES cipher").Base(err)
}
aead, err := cipher.NewGCM(aesCipher)
if err != nil {
return nil, newError("failed to create AES-GCM AEAD").Base(err)
}
return aead, nil
}
func (a AES128GCMMethod) GenerateEIH(currentIdentitySubKey []byte, nextPskHash []byte, out []byte) error {
aesCipher, err := aes.NewCipher(currentIdentitySubKey)
if err != nil {
return newError("failed to create AES cipher").Base(err)
}
aesCipher.Encrypt(out, nextPskHash)
return nil
}
func (a AES128GCMMethod) GetUDPClientProcessor(ipsk [][]byte, psk []byte, derivation KeyDerivation) (UDPClientPacketProcessor, error) {
reqSeparateHeaderPsk := psk
if ipsk != nil {
reqSeparateHeaderPsk = ipsk[0]
}
reqSeparateHeaderCipher, err := aes.NewCipher(reqSeparateHeaderPsk)
if err != nil {
return nil, newError("failed to create AES cipher").Base(err)
}
respSeparateHeaderCipher, err := aes.NewCipher(psk)
if err != nil {
return nil, newError("failed to create AES cipher").Base(err)
}
getPacketAEAD := func(sessionID []byte) cipher.AEAD {
sessionKey := make([]byte, a.GetSessionSubKeyAndSaltLength())
derivation.GetSessionSubKey(psk, sessionID, sessionKey)
block, err := aes.NewCipher(sessionKey)
if err != nil {
panic(err)
}
aead, err := cipher.NewGCM(block)
if err != nil {
panic(err)
}
return aead
}
if len(ipsk) == 0 {
return NewAESUDPClientPacketProcessor(reqSeparateHeaderCipher, respSeparateHeaderCipher, getPacketAEAD, nil), nil
}
eihGenerator := newAESEIHGeneratorContainer(len(ipsk), psk, ipsk)
getEIH := func(mask []byte) ExtensibleIdentityHeaders {
eih, err := eihGenerator.GenerateEIHUDP(derivation, a, mask)
if err != nil {
newError("failed to generate EIH").Base(err).WriteToLog()
}
return eih
}
return NewAESUDPClientPacketProcessor(reqSeparateHeaderCipher, respSeparateHeaderCipher, getPacketAEAD, getEIH), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/requestsalt.go | proxy/shadowsocks2022/requestsalt.go | package shadowsocks2022
import (
"encoding/hex"
"io"
"github.com/v2fly/struc"
)
func newRequestSaltWithLength(length int) RequestSalt {
return &requestSaltWithLength{length: length}
}
type requestSaltWithLength struct {
length int
content []byte
}
func (r *requestSaltWithLength) isRequestSalt() {}
func (r *requestSaltWithLength) Pack(p []byte, opt *struc.Options) (int, error) {
n := copy(p, r.content)
if n != r.length {
return 0, newError("failed to pack request salt with length")
}
return n, nil
}
func (r *requestSaltWithLength) Unpack(reader io.Reader, length int, opt *struc.Options) error {
r.content = make([]byte, r.length)
n, err := io.ReadFull(reader, r.content)
if err != nil {
return newError("failed to unpack request salt with length").Base(err)
}
if n != r.length {
return newError("failed to unpack request salt with length")
}
return nil
}
func (r *requestSaltWithLength) Size(opt *struc.Options) int {
return r.length
}
func (r *requestSaltWithLength) String() string {
return hex.Dump(r.content)
}
func (r *requestSaltWithLength) Bytes() []byte {
return r.content
}
func (r *requestSaltWithLength) FillAllFrom(reader io.Reader) error {
r.content = make([]byte, r.length)
_, err := io.ReadFull(reader, r.content)
if err != nil {
return newError("failed to fill salt from reader").Base(err)
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/udp_aes.go | proxy/shadowsocks2022/udp_aes.go | package shadowsocks2022
import (
"bytes"
"crypto/cipher"
"io"
"github.com/v2fly/struc"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
)
type AESUDPClientPacketProcessor struct {
requestSeparateHeaderBlockCipher cipher.Block
responseSeparateHeaderBlockCipher cipher.Block
mainPacketAEAD func([]byte) cipher.AEAD
EIHGenerator func([]byte) ExtensibleIdentityHeaders
}
func NewAESUDPClientPacketProcessor(requestSeparateHeaderBlockCipher, responseSeparateHeaderBlockCipher cipher.Block, mainPacketAEAD func([]byte) cipher.AEAD, eih func([]byte) ExtensibleIdentityHeaders) *AESUDPClientPacketProcessor {
return &AESUDPClientPacketProcessor{
requestSeparateHeaderBlockCipher: requestSeparateHeaderBlockCipher,
responseSeparateHeaderBlockCipher: responseSeparateHeaderBlockCipher,
mainPacketAEAD: mainPacketAEAD,
EIHGenerator: eih,
}
}
type separateHeader struct {
SessionID [8]byte
PacketID uint64
}
type header struct {
Type byte
TimeStamp uint64
PaddingLength uint16 `struc:"sizeof=Padding"`
Padding []byte
}
type respHeader struct {
Type byte
TimeStamp uint64
ClientSessionID [8]byte
PaddingLength uint16 `struc:"sizeof=Padding"`
Padding []byte
}
type cachedUDPState struct {
sessionAEAD cipher.AEAD
sessionRecvAEAD cipher.AEAD
}
func (p *AESUDPClientPacketProcessor) EncodeUDPRequest(request *UDPRequest, out *buf.Buffer,
cache UDPClientPacketProcessorCachedStateContainer,
) error {
separateHeaderStruct := separateHeader{PacketID: request.PacketID, SessionID: request.SessionID}
separateHeaderBuffer := buf.New()
defer separateHeaderBuffer.Release()
{
err := struc.Pack(separateHeaderBuffer, &separateHeaderStruct)
if err != nil {
return newError("failed to pack separateHeader").Base(err)
}
}
separateHeaderBufferBytes := separateHeaderBuffer.Bytes()
{
encryptedDest := out.Extend(16)
p.requestSeparateHeaderBlockCipher.Encrypt(encryptedDest, separateHeaderBufferBytes)
}
if p.EIHGenerator != nil {
eih := p.EIHGenerator(separateHeaderBufferBytes[0:16])
eihHeader := struct {
EIH ExtensibleIdentityHeaders
}{
EIH: eih,
}
err := struc.Pack(out, &eihHeader)
if err != nil {
return newError("failed to pack eih").Base(err)
}
}
headerStruct := header{
Type: UDPHeaderTypeClientToServerStream,
TimeStamp: request.TimeStamp,
PaddingLength: 0,
Padding: nil,
}
requestBodyBuffer := buf.New()
{
err := struc.Pack(requestBodyBuffer, &headerStruct)
if err != nil {
return newError("failed to header").Base(err)
}
}
{
err := addrParser.WriteAddressPort(requestBodyBuffer, request.Address, net.Port(request.Port))
if err != nil {
return newError("failed to write address port").Base(err)
}
}
{
_, err := io.Copy(requestBodyBuffer, bytes.NewReader(request.Payload.Bytes()))
if err != nil {
return newError("failed to copy payload").Base(err)
}
}
{
cacheKey := string(separateHeaderBufferBytes[0:8])
receivedCacheInterface := cache.GetCachedState(cacheKey)
cachedState := &cachedUDPState{}
if receivedCacheInterface != nil {
cachedState = receivedCacheInterface.(*cachedUDPState)
}
if cachedState.sessionAEAD == nil {
cachedState.sessionAEAD = p.mainPacketAEAD(separateHeaderBufferBytes[0:8])
cache.PutCachedState(cacheKey, cachedState)
}
mainPacketAEADMaterialized := cachedState.sessionAEAD
encryptedDest := out.Extend(int32(mainPacketAEADMaterialized.Overhead()) + requestBodyBuffer.Len())
mainPacketAEADMaterialized.Seal(encryptedDest[:0], separateHeaderBuffer.Bytes()[4:16], requestBodyBuffer.Bytes(), nil)
}
return nil
}
func (p *AESUDPClientPacketProcessor) DecodeUDPResp(input []byte, resp *UDPResponse,
cache UDPClientPacketProcessorCachedStateContainer,
) error {
separateHeaderBuffer := buf.New()
defer separateHeaderBuffer.Release()
{
encryptedDest := separateHeaderBuffer.Extend(16)
p.responseSeparateHeaderBlockCipher.Decrypt(encryptedDest, input)
}
separateHeaderStruct := separateHeader{}
{
err := struc.Unpack(separateHeaderBuffer, &separateHeaderStruct)
if err != nil {
return newError("failed to unpack separateHeader").Base(err)
}
}
resp.PacketID = separateHeaderStruct.PacketID
resp.SessionID = separateHeaderStruct.SessionID
{
cacheKey := string(separateHeaderBuffer.Bytes()[0:8])
receivedCacheInterface := cache.GetCachedServerState(cacheKey)
cachedState := &cachedUDPState{}
if receivedCacheInterface != nil {
cachedState = receivedCacheInterface.(*cachedUDPState)
}
if cachedState.sessionRecvAEAD == nil {
cachedState.sessionRecvAEAD = p.mainPacketAEAD(separateHeaderBuffer.Bytes()[0:8])
cache.PutCachedServerState(cacheKey, cachedState)
}
mainPacketAEADMaterialized := cachedState.sessionRecvAEAD
decryptedDestBuffer := buf.New()
decryptedDest := decryptedDestBuffer.Extend(int32(len(input)) - 16 - int32(mainPacketAEADMaterialized.Overhead()))
_, err := mainPacketAEADMaterialized.Open(decryptedDest[:0], separateHeaderBuffer.Bytes()[4:16], input[16:], nil)
if err != nil {
return newError("failed to open main packet").Base(err)
}
decryptedDestReader := bytes.NewReader(decryptedDest)
headerStruct := respHeader{}
{
err := struc.Unpack(decryptedDestReader, &headerStruct)
if err != nil {
return newError("failed to unpack header").Base(err)
}
}
resp.TimeStamp = headerStruct.TimeStamp
addressReaderBuf := buf.New()
defer addressReaderBuf.Release()
var port net.Port
resp.Address, port, err = addrParser.ReadAddressPort(addressReaderBuf, decryptedDestReader)
if err != nil {
return newError("failed to read address port").Base(err)
}
resp.Port = int(port)
readedLength := decryptedDestReader.Size() - int64(decryptedDestReader.Len())
decryptedDestBuffer.Advance(int32(readedLength))
resp.Payload = decryptedDestBuffer
resp.ClientSessionID = headerStruct.ClientSessionID
return nil
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/config.pb.go | proxy/shadowsocks2022/config.pb.go | package shadowsocks2022
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ClientConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
Psk []byte `protobuf:"bytes,2,opt,name=psk,proto3" json:"psk,omitempty"`
Ipsk [][]byte `protobuf:"bytes,4,rep,name=ipsk,proto3" json:"ipsk,omitempty"`
Address *net.IPOrDomain `protobuf:"bytes,5,opt,name=address,proto3" json:"address,omitempty"`
Port uint32 `protobuf:"varint,6,opt,name=port,proto3" json:"port,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClientConfig) Reset() {
*x = ClientConfig{}
mi := &file_proxy_shadowsocks2022_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ClientConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ClientConfig) ProtoMessage() {}
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_shadowsocks2022_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
func (*ClientConfig) Descriptor() ([]byte, []int) {
return file_proxy_shadowsocks2022_config_proto_rawDescGZIP(), []int{0}
}
func (x *ClientConfig) GetMethod() string {
if x != nil {
return x.Method
}
return ""
}
func (x *ClientConfig) GetPsk() []byte {
if x != nil {
return x.Psk
}
return nil
}
func (x *ClientConfig) GetIpsk() [][]byte {
if x != nil {
return x.Ipsk
}
return nil
}
func (x *ClientConfig) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *ClientConfig) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
var File_proxy_shadowsocks2022_config_proto protoreflect.FileDescriptor
const file_proxy_shadowsocks2022_config_proto_rawDesc = "" +
"\n" +
"\"proxy/shadowsocks2022/config.proto\x12 v2ray.core.proxy.shadowsocks2022\x1a\x18common/net/address.proto\x1a common/protoext/extensions.proto\"\xc2\x01\n" +
"\fClientConfig\x12\x16\n" +
"\x06method\x18\x01 \x01(\tR\x06method\x12\x10\n" +
"\x03psk\x18\x02 \x01(\fR\x03psk\x12\x12\n" +
"\x04ipsk\x18\x04 \x03(\fR\x04ipsk\x12;\n" +
"\aaddress\x18\x05 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" +
"\x04port\x18\x06 \x01(\rR\x04port:#\x82\xb5\x18\x1f\n" +
"\boutbound\x12\x0fshadowsocks2022\x90\xff)\x01B\x81\x01\n" +
"$com.v2ray.core.proxy.shadowsocks2022P\x01Z4github.com/v2fly/v2ray-core/v5/proxy/shadowsocks2022\xaa\x02 V2Ray.Core.Proxy.Shadowsocks2022b\x06proto3"
var (
file_proxy_shadowsocks2022_config_proto_rawDescOnce sync.Once
file_proxy_shadowsocks2022_config_proto_rawDescData []byte
)
func file_proxy_shadowsocks2022_config_proto_rawDescGZIP() []byte {
file_proxy_shadowsocks2022_config_proto_rawDescOnce.Do(func() {
file_proxy_shadowsocks2022_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_shadowsocks2022_config_proto_rawDesc), len(file_proxy_shadowsocks2022_config_proto_rawDesc)))
})
return file_proxy_shadowsocks2022_config_proto_rawDescData
}
var file_proxy_shadowsocks2022_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_proxy_shadowsocks2022_config_proto_goTypes = []any{
(*ClientConfig)(nil), // 0: v2ray.core.proxy.shadowsocks2022.ClientConfig
(*net.IPOrDomain)(nil), // 1: v2ray.core.common.net.IPOrDomain
}
var file_proxy_shadowsocks2022_config_proto_depIdxs = []int32{
1, // 0: v2ray.core.proxy.shadowsocks2022.ClientConfig.address:type_name -> v2ray.core.common.net.IPOrDomain
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_proxy_shadowsocks2022_config_proto_init() }
func file_proxy_shadowsocks2022_config_proto_init() {
if File_proxy_shadowsocks2022_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_shadowsocks2022_config_proto_rawDesc), len(file_proxy_shadowsocks2022_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_shadowsocks2022_config_proto_goTypes,
DependencyIndexes: file_proxy_shadowsocks2022_config_proto_depIdxs,
MessageInfos: file_proxy_shadowsocks2022_config_proto_msgTypes,
}.Build()
File_proxy_shadowsocks2022_config_proto = out.File
file_proxy_shadowsocks2022_config_proto_goTypes = nil
file_proxy_shadowsocks2022_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/encoding.go | proxy/shadowsocks2022/encoding.go | package shadowsocks2022
import (
"bytes"
"crypto/cipher"
cryptoRand "crypto/rand"
"encoding/binary"
"io"
"time"
"github.com/v2fly/struc"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/crypto"
"github.com/v2fly/v2ray-core/v5/common/dice"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
type TCPRequest struct {
keyDerivation KeyDerivation
method Method
c2sSalt RequestSalt
c2sNonce crypto.BytesGenerator
c2sAEAD cipher.AEAD
s2cSalt RequestSalt
s2cNonce crypto.BytesGenerator
s2cAEAD cipher.AEAD
s2cSaltAssert RequestSalt
s2cInitialPayloadSize int
}
func (t *TCPRequest) EncodeTCPRequestHeader(effectivePsk []byte,
eih [][]byte, address DestinationAddress, destPort int, initialPayload []byte, out *buf.Buffer,
) error {
requestSalt := newRequestSaltWithLength(t.method.GetSessionSubKeyAndSaltLength())
{
err := requestSalt.FillAllFrom(cryptoRand.Reader)
if err != nil {
return newError("failed to fill salt").Base(err)
}
}
t.c2sSalt = requestSalt
sessionKey := make([]byte, t.method.GetSessionSubKeyAndSaltLength())
{
err := t.keyDerivation.GetSessionSubKey(effectivePsk, requestSalt.Bytes(), sessionKey)
if err != nil {
return newError("failed to get session sub key").Base(err)
}
}
aead, err := t.method.GetStreamAEAD(sessionKey)
if err != nil {
return newError("failed to get stream AEAD").Base(err)
}
t.c2sAEAD = aead
paddingLength := TCPMinPaddingLength
if initialPayload == nil {
initialPayload = []byte{}
paddingLength += 1 + dice.RollWith(TCPMaxPaddingLength, cryptoRand.Reader)
}
variableLengthHeader := &TCPRequestHeader3VariableLength{
DestinationAddress: address,
Contents: struct {
PaddingLength uint16 `struc:"sizeof=Padding"`
Padding []byte
}(struct {
PaddingLength uint16
Padding []byte
}{
PaddingLength: uint16(paddingLength),
Padding: make([]byte, paddingLength),
}),
}
variableLengthHeaderBuffer := buf.New()
defer variableLengthHeaderBuffer.Release()
{
err := addrParser.WriteAddressPort(variableLengthHeaderBuffer, address, net.Port(destPort))
if err != nil {
return newError("failed to write address port").Base(err)
}
}
{
err := struc.Pack(variableLengthHeaderBuffer, &variableLengthHeader.Contents)
if err != nil {
return newError("failed to pack variable length header").Base(err)
}
}
{
_, err := variableLengthHeaderBuffer.Write(initialPayload)
if err != nil {
return newError("failed to write initial payload").Base(err)
}
}
fixedLengthHeader := &TCPRequestHeader2FixedLength{
Type: TCPHeaderTypeClientToServerStream,
Timestamp: uint64(time.Now().Unix()),
HeaderLength: uint16(variableLengthHeaderBuffer.Len()),
}
fixedLengthHeaderBuffer := buf.New()
defer fixedLengthHeaderBuffer.Release()
{
err := struc.Pack(fixedLengthHeaderBuffer, fixedLengthHeader)
if err != nil {
return newError("failed to pack fixed length header").Base(err)
}
}
eihHeader := ExtensibleIdentityHeaders(newAESEIH(0))
if len(eih) != 0 {
eihGenerator := newAESEIHGeneratorContainer(len(eih), effectivePsk, eih)
eihHeaderGenerated, err := eihGenerator.GenerateEIH(t.keyDerivation, t.method, requestSalt.Bytes())
if err != nil {
return newError("failed to construct EIH").Base(err)
}
eihHeader = eihHeaderGenerated
}
preSessionKeyHeader := &TCPRequestHeader1PreSessionKey{
Salt: requestSalt,
EIH: eihHeader,
}
preSessionKeyHeaderBuffer := buf.New()
defer preSessionKeyHeaderBuffer.Release()
{
err := struc.Pack(preSessionKeyHeaderBuffer, preSessionKeyHeader)
if err != nil {
return newError("failed to pack pre session key header").Base(err)
}
}
requestNonce := crypto.GenerateInitialAEADNonce()
t.c2sNonce = requestNonce
{
n, err := out.Write(preSessionKeyHeaderBuffer.BytesFrom(0))
if err != nil {
return newError("failed to write pre session key header").Base(err)
}
if int32(n) != preSessionKeyHeaderBuffer.Len() {
return newError("failed to write pre session key header")
}
}
{
fixedLengthEncrypted := out.Extend(fixedLengthHeaderBuffer.Len() + int32(aead.Overhead()))
aead.Seal(fixedLengthEncrypted[:0], requestNonce(), fixedLengthHeaderBuffer.Bytes(), nil)
}
{
variableLengthEncrypted := out.Extend(variableLengthHeaderBuffer.Len() + int32(aead.Overhead()))
aead.Seal(variableLengthEncrypted[:0], requestNonce(), variableLengthHeaderBuffer.Bytes(), nil)
}
return nil
}
func (t *TCPRequest) DecodeTCPResponseHeader(effectivePsk []byte, in io.Reader) error {
var preSessionKeyHeader TCPResponseHeader1PreSessionKey
preSessionKeyHeader.Salt = newRequestSaltWithLength(t.method.GetSessionSubKeyAndSaltLength())
{
err := struc.Unpack(in, &preSessionKeyHeader)
if err != nil {
return newError("failed to unpack pre session key header").Base(err)
}
}
s2cSalt := preSessionKeyHeader.Salt.Bytes()
t.s2cSalt = preSessionKeyHeader.Salt
sessionKey := make([]byte, t.method.GetSessionSubKeyAndSaltLength())
{
err := t.keyDerivation.GetSessionSubKey(effectivePsk, s2cSalt, sessionKey)
if err != nil {
return newError("failed to get session sub key").Base(err)
}
}
aead, err := t.method.GetStreamAEAD(sessionKey)
if err != nil {
return newError("failed to get stream AEAD").Base(err)
}
t.s2cAEAD = aead
fixedLengthHeaderEncryptedBuffer := buf.New()
defer fixedLengthHeaderEncryptedBuffer.Release()
{
_, err := fixedLengthHeaderEncryptedBuffer.ReadFullFrom(in, 11+int32(t.method.GetSessionSubKeyAndSaltLength())+int32(aead.Overhead()))
if err != nil {
return newError("failed to read fixed length header encrypted").Base(err)
}
}
s2cNonce := crypto.GenerateInitialAEADNonce()
t.s2cNonce = s2cNonce
fixedLengthHeaderDecryptedBuffer := buf.New()
defer fixedLengthHeaderDecryptedBuffer.Release()
{
decryptionBuffer := fixedLengthHeaderDecryptedBuffer.Extend(11 + int32(t.method.GetSessionSubKeyAndSaltLength()))
_, err = aead.Open(decryptionBuffer[:0], s2cNonce(), fixedLengthHeaderEncryptedBuffer.Bytes(), nil)
if err != nil {
return newError("failed to decrypt fixed length header").Base(err)
}
}
var fixedLengthHeader TCPResponseHeader2FixedLength
fixedLengthHeader.RequestSalt = newRequestSaltWithLength(t.method.GetSessionSubKeyAndSaltLength())
{
err := struc.Unpack(bytes.NewReader(fixedLengthHeaderDecryptedBuffer.Bytes()), &fixedLengthHeader)
if err != nil {
return newError("failed to unpack fixed length header").Base(err)
}
}
if fixedLengthHeader.Type != TCPHeaderTypeServerToClientStream {
return newError("unexpected TCP header type")
}
timeDifference := int64(fixedLengthHeader.Timestamp) - time.Now().Unix()
if timeDifference < -30 || timeDifference > 30 {
return newError("timestamp is too far away, timeDifference = ", timeDifference)
}
t.s2cSaltAssert = fixedLengthHeader.RequestSalt
t.s2cInitialPayloadSize = int(fixedLengthHeader.InitialPayloadLength)
return nil
}
func (t *TCPRequest) CheckC2SConnectionConstraint() error {
if !bytes.Equal(t.c2sSalt.Bytes(), t.s2cSaltAssert.Bytes()) {
return newError("c2s salt not equal to s2c salt assert")
}
return nil
}
func (t *TCPRequest) CreateClientS2CReader(in io.Reader, initialPayload *buf.Buffer) (buf.Reader, error) {
AEADAuthenticator := &crypto.AEADAuthenticator{
AEAD: t.s2cAEAD,
NonceGenerator: t.s2cNonce,
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
initialPayloadEncrypted := buf.NewWithSize(65535)
defer initialPayloadEncrypted.Release()
initialPayloadEncryptedBytes := initialPayloadEncrypted.Extend(int32(t.s2cAEAD.Overhead()) + int32(t.s2cInitialPayloadSize))
_, err := io.ReadFull(in, initialPayloadEncryptedBytes)
if err != nil {
return nil, newError("failed to read initial payload").Base(err)
}
initialPayloadBytes := initialPayload.Extend(int32(t.s2cInitialPayloadSize))
_, err = t.s2cAEAD.Open(initialPayloadBytes[:0], t.s2cNonce(), initialPayloadEncryptedBytes, nil)
if err != nil {
return nil, newError("failed to decrypt initial payload").Base(err)
}
return crypto.NewAuthenticationReader(AEADAuthenticator, &AEADChunkSizeParser{
Auth: AEADAuthenticator,
}, in, protocol.TransferTypeStream, nil), nil
}
func (t *TCPRequest) CreateClientC2SWriter(writer io.Writer) buf.Writer {
AEADAuthenticator := &crypto.AEADAuthenticator{
AEAD: t.c2sAEAD,
NonceGenerator: t.c2sNonce,
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser := &crypto.AEADChunkSizeParser{
Auth: AEADAuthenticator,
}
return crypto.NewAuthenticationWriter(AEADAuthenticator, sizeParser, writer, protocol.TransferTypeStream, nil)
}
type AEADChunkSizeParser struct {
Auth *crypto.AEADAuthenticator
}
func (p *AEADChunkSizeParser) HasConstantOffset() uint16 {
return uint16(p.Auth.Overhead())
}
func (p *AEADChunkSizeParser) SizeBytes() int32 {
return 2 + int32(p.Auth.Overhead())
}
func (p *AEADChunkSizeParser) Encode(size uint16, b []byte) []byte {
binary.BigEndian.PutUint16(b, size-uint16(p.Auth.Overhead()))
b, err := p.Auth.Seal(b[:0], b[:2])
common.Must(err)
return b
}
func (p *AEADChunkSizeParser) Decode(b []byte) (uint16, error) {
b, err := p.Auth.Open(b[:0], b)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint16(b), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks2022/method_aes256gcm.go | proxy/shadowsocks2022/method_aes256gcm.go | package shadowsocks2022
import (
"crypto/aes"
"crypto/cipher"
)
func newAES256GCMMethod() *AES256GCMMethod {
return &AES256GCMMethod{}
}
type AES256GCMMethod struct{}
func (a AES256GCMMethod) GetSessionSubKeyAndSaltLength() int {
return 32
}
func (a AES256GCMMethod) GetStreamAEAD(sessionSubKey []byte) (cipher.AEAD, error) {
aesCipher, err := aes.NewCipher(sessionSubKey)
if err != nil {
return nil, newError("failed to create AES cipher").Base(err)
}
aead, err := cipher.NewGCM(aesCipher)
if err != nil {
return nil, newError("failed to create AES-GCM AEAD").Base(err)
}
return aead, nil
}
func (a AES256GCMMethod) GenerateEIH(currentIdentitySubKey []byte, nextPskHash []byte, out []byte) error {
aesCipher, err := aes.NewCipher(currentIdentitySubKey)
if err != nil {
return newError("failed to create AES cipher").Base(err)
}
aesCipher.Encrypt(out, nextPskHash)
return nil
}
func (a AES256GCMMethod) GetUDPClientProcessor(ipsk [][]byte, psk []byte, derivation KeyDerivation) (UDPClientPacketProcessor, error) {
reqSeparateHeaderPsk := psk
if ipsk != nil {
reqSeparateHeaderPsk = ipsk[0]
}
reqSeparateHeaderCipher, err := aes.NewCipher(reqSeparateHeaderPsk)
if err != nil {
return nil, newError("failed to create AES cipher").Base(err)
}
respSeparateHeaderCipher, err := aes.NewCipher(psk)
if err != nil {
return nil, newError("failed to create AES cipher").Base(err)
}
getPacketAEAD := func(sessionID []byte) cipher.AEAD {
sessionKey := make([]byte, a.GetSessionSubKeyAndSaltLength())
derivation.GetSessionSubKey(psk, sessionID, sessionKey)
block, err := aes.NewCipher(sessionKey)
if err != nil {
panic(err)
}
aead, err := cipher.NewGCM(block)
if err != nil {
panic(err)
}
return aead
}
if len(ipsk) == 0 {
return NewAESUDPClientPacketProcessor(reqSeparateHeaderCipher, respSeparateHeaderCipher, getPacketAEAD, nil), nil
}
eihGenerator := newAESEIHGeneratorContainer(len(ipsk), psk, ipsk)
getEIH := func(mask []byte) ExtensibleIdentityHeaders {
eih, err := eihGenerator.GenerateEIHUDP(derivation, a, mask)
if err != nil {
newError("failed to generate EIH").Base(err).WriteToLog()
}
return eih
}
return NewAESUDPClientPacketProcessor(reqSeparateHeaderCipher, respSeparateHeaderCipher, getPacketAEAD, getEIH), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/socks.go | proxy/socks/socks.go | // Package socks provides implements of Socks protocol 4, 4a and 5.
package socks
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/errors.generated.go | proxy/socks/errors.generated.go | package socks
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/client.go | proxy/socks/client.go | package socks
import (
"context"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/dns"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
// Client is a Socks5 client.
type Client struct {
serverPicker protocol.ServerPicker
policyManager policy.Manager
version Version
dns dns.Client
delayAuthWrite bool
}
// NewClient create a new Socks5 client based on the given config.
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
serverList := protocol.NewServerList()
for _, rec := range config.Server {
s, err := protocol.NewServerSpecFromPB(rec)
if err != nil {
return nil, newError("failed to get server spec").Base(err)
}
serverList.AddServer(s)
}
if serverList.Size() == 0 {
return nil, newError("0 target server")
}
v := core.MustFromContext(ctx)
c := &Client{
serverPicker: protocol.NewRoundRobinServerPicker(serverList),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
version: config.Version,
delayAuthWrite: config.DelayAuthWrite,
}
if config.Version == Version_SOCKS4 {
c.dns = v.GetFeature(dns.ClientType()).(dns.Client)
}
return c, nil
}
// Process implements proxy.Outbound.Process.
func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified.")
}
// Destination of the inner request.
destination := outbound.Target
// Outbound server.
var server *protocol.ServerSpec
// Outbound server's destination.
var dest net.Destination
// Connection to the outbound server.
var conn internet.Connection
if err := retry.ExponentialBackoff(5, 100).On(func() error {
server = c.serverPicker.PickServer()
dest = server.Destination()
rawConn, err := dialer.Dial(ctx, dest)
if err != nil {
return err
}
conn = rawConn
return nil
}); err != nil {
return newError("failed to find an available destination").Base(err)
}
defer func() {
if err := conn.Close(); err != nil {
newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
}
}()
p := c.policyManager.ForLevel(0)
request := &protocol.RequestHeader{
Version: socks5Version,
Command: protocol.RequestCommandTCP,
Address: destination.Address,
Port: destination.Port,
}
switch c.version {
case Version_SOCKS4:
if request.Address.Family().IsDomain() {
ips, err := dns.LookupIPWithOption(c.dns, request.Address.Domain(), dns.IPOption{IPv4Enable: true, IPv6Enable: false, FakeEnable: false})
if err != nil {
return err
} else if len(ips) == 0 {
return dns.ErrEmptyResponse
}
request.Address = net.IPAddress(ips[0])
}
fallthrough
case Version_SOCKS4A:
request.Version = socks4Version
if destination.Network == net.Network_UDP {
return newError("udp is not supported in socks4")
} else if destination.Address.Family().IsIPv6() {
return newError("ipv6 is not supported in socks4")
}
}
if destination.Network == net.Network_UDP {
request.Command = protocol.RequestCommandUDP
}
user := server.PickUser()
if user != nil {
request.User = user
p = c.policyManager.ForLevel(user.Level)
}
if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
}
var udpRequest *protocol.RequestHeader
var err error
if request.Version == socks4Version {
err = ClientHandshake4(request, conn, conn)
if err != nil {
return newError("failed to establish connection to server").AtWarning().Base(err)
}
} else {
udpRequest, err = ClientHandshake(request, conn, conn, c.delayAuthWrite)
if err != nil {
return newError("failed to establish connection to server").AtWarning().Base(err)
}
}
if udpRequest != nil {
if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 {
udpRequest.Address = dest.Address
}
}
if err := conn.SetDeadline(time.Time{}); err != nil {
newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx))
}
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil {
udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
if err != nil {
return newError("failed to create UDP connection").Base(err)
}
defer udpConn.Close()
requestDone := func() error {
protocolWriter := NewUDPWriter(request, udpConn)
return udp.CopyPacketConn(protocolWriter, packetConn, udp.UpdateActivity(timer))
}
responseDone := func() error {
protocolReader := &UDPReader{
reader: udpConn,
}
return udp.CopyPacketConn(packetConn, protocolReader, udp.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
var requestFunc func() error
var responseFunc func() error
if request.Command == protocol.RequestCommandTCP {
requestFunc = func() error {
defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
}
responseFunc = func() error {
defer timer.SetTimeout(p.Timeouts.UplinkOnly)
return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
}
} else if request.Command == protocol.RequestCommandUDP {
udpConn, err := dialer.Dial(ctx, udpRequest.Destination())
if err != nil {
return newError("failed to create UDP connection").Base(err)
}
defer udpConn.Close()
requestFunc = func() error {
defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
return buf.Copy(link.Reader, &buf.SequentialWriter{Writer: NewUDPWriter(request, udpConn)}, buf.UpdateActivity(timer))
}
responseFunc = func() error {
defer timer.SetTimeout(p.Timeouts.UplinkOnly)
reader := &UDPReader{reader: udpConn}
return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
}
}
responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewClient(ctx, config.(*ClientConfig))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/config.go | proxy/socks/config.go | package socks
import "github.com/v2fly/v2ray-core/v5/common/protocol"
func (a *Account) Equals(another protocol.Account) bool {
if account, ok := another.(*Account); ok {
return a.Username == account.Username
}
return false
}
func (a *Account) AsAccount() (protocol.Account, error) {
return a, nil
}
func (c *ServerConfig) HasAccount(username, password string) bool {
if c.Accounts == nil {
return false
}
storedPassed, found := c.Accounts[username]
if !found {
return false
}
return storedPassed == password
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/protocol.go | proxy/socks/protocol.go | package socks
import (
"encoding/binary"
"io"
gonet "net"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
const (
socks5Version = 0x05
socks4Version = 0x04
cmdTCPConnect = 0x01
cmdTCPBind = 0x02
cmdUDPAssociate = 0x03
cmdTorResolve = 0xF0
cmdTorResolvePTR = 0xF1
socks4RequestGranted = 90
socks4RequestRejected = 91
authNotRequired = 0x00
// authGssAPI = 0x01
authPassword = 0x02
authNoMatchingMethod = 0xFF
statusSuccess = 0x00
statusConnRefused = 0x05
statusCmdNotSupport = 0x07
)
var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6),
protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain),
)
type ServerSession struct {
config *ServerConfig
address net.Address
port net.Port
clientAddress net.Address
flushLastReply func(bool) error
}
func (s *ServerSession) handshake4(cmd byte, reader io.Reader, writer io.Writer) (*protocol.RequestHeader, error) {
if s.config.AuthType == AuthType_PASSWORD {
writeSocks4Response(writer, socks4RequestRejected, net.AnyIP, net.Port(0))
return nil, newError("socks 4 is not allowed when auth is required.")
}
var port net.Port
var address net.Address
{
buffer := buf.StackNew()
if _, err := buffer.ReadFullFrom(reader, 6); err != nil {
buffer.Release()
return nil, newError("insufficient header").Base(err)
}
port = net.PortFromBytes(buffer.BytesRange(0, 2))
address = net.IPAddress(buffer.BytesRange(2, 6))
buffer.Release()
}
if _, err := ReadUntilNull(reader); /* user id */ err != nil {
return nil, err
}
if address.IP()[0] == 0x00 {
domain, err := ReadUntilNull(reader)
if err != nil {
return nil, newError("failed to read domain for socks 4a").Base(err)
}
address = net.DomainAddress(domain)
}
switch cmd {
case cmdTCPConnect:
request := &protocol.RequestHeader{
Command: protocol.RequestCommandTCP,
Address: address,
Port: port,
Version: socks4Version,
}
if err := s.setupLastReply(func(ok bool) error {
if ok {
return writeSocks4Response(writer, socks4RequestGranted, net.AnyIP, net.Port(0))
} else {
return writeSocks4Response(writer, socks4RequestRejected, net.AnyIP, net.Port(0))
}
}); err != nil {
return nil, err
}
return request, nil
default:
writeSocks4Response(writer, socks4RequestRejected, net.AnyIP, net.Port(0))
return nil, newError("unsupported command: ", cmd)
}
}
func (s *ServerSession) auth5(nMethod byte, reader io.Reader, writer io.Writer) (username string, err error) {
buffer := buf.StackNew()
defer buffer.Release()
if _, err = buffer.ReadFullFrom(reader, int32(nMethod)); err != nil {
return "", newError("failed to read auth methods").Base(err)
}
var expectedAuth byte = authNotRequired
if s.config.AuthType == AuthType_PASSWORD {
expectedAuth = authPassword
}
if !hasAuthMethod(expectedAuth, buffer.BytesRange(0, int32(nMethod))) {
writeSocks5AuthenticationResponse(writer, socks5Version, authNoMatchingMethod)
return "", newError("no matching auth method")
}
if err := writeSocks5AuthenticationResponse(writer, socks5Version, expectedAuth); err != nil {
return "", newError("failed to write auth response").Base(err)
}
if expectedAuth == authPassword {
username, password, err := ReadUsernamePassword(reader)
if err != nil {
return "", newError("failed to read username and password for authentication").Base(err)
}
if !s.config.HasAccount(username, password) {
writeSocks5AuthenticationResponse(writer, 0x01, 0xFF)
return "", newError("invalid username or password")
}
if err := writeSocks5AuthenticationResponse(writer, 0x01, 0x00); err != nil {
return "", newError("failed to write auth response").Base(err)
}
return username, nil
}
return "", nil
}
func (s *ServerSession) handshake5(nMethod byte, reader io.Reader, writer io.Writer) (*protocol.RequestHeader, error) {
var (
username string
err error
)
if username, err = s.auth5(nMethod, reader, writer); err != nil {
return nil, err
}
var cmd byte
{
buffer := buf.StackNew()
if _, err := buffer.ReadFullFrom(reader, 3); err != nil {
buffer.Release()
return nil, newError("failed to read request").Base(err)
}
cmd = buffer.Byte(1)
buffer.Release()
}
request := new(protocol.RequestHeader)
if username != "" {
request.User = &protocol.MemoryUser{Email: username}
}
switch cmd {
case cmdTCPConnect, cmdTorResolve, cmdTorResolvePTR:
// We don't have a solution for Tor case now. Simply treat it as connect command.
request.Command = protocol.RequestCommandTCP
case cmdUDPAssociate:
if !s.config.UdpEnabled {
writeSocks5Response(writer, statusCmdNotSupport, net.AnyIP, net.Port(0))
return nil, newError("UDP is not enabled.")
}
request.Command = protocol.RequestCommandUDP
case cmdTCPBind:
writeSocks5Response(writer, statusCmdNotSupport, net.AnyIP, net.Port(0))
return nil, newError("TCP bind is not supported.")
default:
writeSocks5Response(writer, statusCmdNotSupport, net.AnyIP, net.Port(0))
return nil, newError("unknown command ", cmd)
}
request.Version = socks5Version
addr, port, err := addrParser.ReadAddressPort(nil, reader)
if err != nil {
return nil, newError("failed to read address").Base(err)
}
request.Address = addr
request.Port = port
responseAddress := s.address
responsePort := s.port
//nolint:gocritic // Use if else chain for clarity
if request.Command == protocol.RequestCommandUDP {
if s.config.Address != nil {
// Use configured IP as remote address in the response to UdpAssociate
responseAddress = s.config.Address.AsAddress()
} else if s.clientAddress == net.LocalHostIP || s.clientAddress == net.LocalHostIPv6 {
// For localhost clients use loopback IP
responseAddress = s.clientAddress
} else {
// For non-localhost clients use inbound listening address
responseAddress = s.address
}
}
if err := s.setupLastReply(func(ok bool) error {
if ok {
return writeSocks5Response(writer, statusSuccess, responseAddress, responsePort)
} else {
return writeSocks5Response(writer, statusConnRefused, net.AnyIP, net.Port(0))
}
}); err != nil {
return nil, err
}
return request, nil
}
// Sets the callback and calls or postpones it based on the boolean field
func (s *ServerSession) setupLastReply(callback func(bool) error) error {
noOpCallback := func(bool) error {
return nil
}
// set the field even if we call it now because it will be called again
s.flushLastReply = func(ok bool) error {
s.flushLastReply = noOpCallback
return callback(ok)
}
if s.config.GetDeferLastReply() {
return nil
}
return s.flushLastReply(true)
}
// Handshake performs a Socks4/4a/5 handshake.
func (s *ServerSession) Handshake(reader io.Reader, writer io.Writer) (*protocol.RequestHeader, error) {
buffer := buf.StackNew()
if _, err := buffer.ReadFullFrom(reader, 2); err != nil {
buffer.Release()
return nil, newError("insufficient header").Base(err)
}
version := buffer.Byte(0)
cmd := buffer.Byte(1)
buffer.Release()
switch version {
case socks4Version:
return s.handshake4(cmd, reader, writer)
case socks5Version:
return s.handshake5(cmd, reader, writer)
default:
return nil, newError("unknown Socks version: ", version)
}
}
// ReadUsernamePassword reads Socks 5 username/password message from the given reader.
// +----+------+----------+------+----------+
// |VER | ULEN | UNAME | PLEN | PASSWD |
// +----+------+----------+------+----------+
// | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
// +----+------+----------+------+----------+
func ReadUsernamePassword(reader io.Reader) (string, string, error) {
buffer := buf.StackNew()
defer buffer.Release()
if _, err := buffer.ReadFullFrom(reader, 2); err != nil {
return "", "", err
}
nUsername := int32(buffer.Byte(1))
buffer.Clear()
if _, err := buffer.ReadFullFrom(reader, nUsername); err != nil {
return "", "", err
}
username := buffer.String()
buffer.Clear()
if _, err := buffer.ReadFullFrom(reader, 1); err != nil {
return "", "", err
}
nPassword := int32(buffer.Byte(0))
buffer.Clear()
if _, err := buffer.ReadFullFrom(reader, nPassword); err != nil {
return "", "", err
}
password := buffer.String()
return username, password, nil
}
// ReadUntilNull reads content from given reader, until a null (0x00) byte.
func ReadUntilNull(reader io.Reader) (string, error) {
b := buf.StackNew()
defer b.Release()
for {
_, err := b.ReadFullFrom(reader, 1)
if err != nil {
return "", err
}
if b.Byte(b.Len()-1) == 0x00 {
b.Resize(0, b.Len()-1)
return b.String(), nil
}
if b.IsFull() {
return "", newError("buffer overrun")
}
}
}
func hasAuthMethod(expectedAuth byte, authCandidates []byte) bool {
for _, a := range authCandidates {
if a == expectedAuth {
return true
}
}
return false
}
func writeSocks5AuthenticationResponse(writer io.Writer, version byte, auth byte) error {
return buf.WriteAllBytes(writer, []byte{version, auth})
}
func writeSocks5Response(writer io.Writer, errCode byte, address net.Address, port net.Port) error {
buffer := buf.New()
defer buffer.Release()
common.Must2(buffer.Write([]byte{socks5Version, errCode, 0x00 /* reserved */}))
if err := addrParser.WriteAddressPort(buffer, address, port); err != nil {
return err
}
return buf.WriteAllBytes(writer, buffer.Bytes())
}
func writeSocks4Response(writer io.Writer, errCode byte, address net.Address, port net.Port) error {
buffer := buf.StackNew()
defer buffer.Release()
common.Must(buffer.WriteByte(0x00))
common.Must(buffer.WriteByte(errCode))
portBytes := buffer.Extend(2)
binary.BigEndian.PutUint16(portBytes, port.Value())
common.Must2(buffer.Write(address.IP()))
return buf.WriteAllBytes(writer, buffer.Bytes())
}
func DecodeUDPPacket(packet *buf.Buffer) (*protocol.RequestHeader, error) {
if packet.Len() < 5 {
return nil, newError("insufficient length of packet.")
}
request := &protocol.RequestHeader{
Version: socks5Version,
Command: protocol.RequestCommandUDP,
}
// packet[0] and packet[1] are reserved
if packet.Byte(2) != 0 /* fragments */ {
return nil, newError("discarding fragmented payload.")
}
packet.Advance(3)
addr, port, err := addrParser.ReadAddressPort(nil, packet)
if err != nil {
return nil, newError("failed to read UDP header").Base(err)
}
request.Address = addr
request.Port = port
return request, nil
}
func EncodeUDPPacket(request *protocol.RequestHeader, data []byte) (*buf.Buffer, error) {
b := buf.New()
common.Must2(b.Write([]byte{0, 0, 0 /* Fragment */}))
if err := addrParser.WriteAddressPort(b, request.Address, request.Port); err != nil {
b.Release()
return nil, err
}
common.Must2(b.Write(data))
return b, nil
}
func EncodeUDPPacketFromAddress(address net.Destination, data []byte) (*buf.Buffer, error) {
b := buf.New()
common.Must2(b.Write([]byte{0, 0, 0 /* Fragment */}))
if err := addrParser.WriteAddressPort(b, address.Address, address.Port); err != nil {
b.Release()
return nil, err
}
common.Must2(b.Write(data))
return b, nil
}
type UDPReader struct {
reader io.Reader
}
func NewUDPReader(reader io.Reader) *UDPReader {
return &UDPReader{reader: reader}
}
func (r *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
b := buf.New()
if _, err := b.ReadFrom(r.reader); err != nil {
return nil, err
}
if _, err := DecodeUDPPacket(b); err != nil {
return nil, err
}
return buf.MultiBuffer{b}, nil
}
func (r *UDPReader) ReadFrom(p []byte) (n int, addr gonet.Addr, err error) {
buffer := buf.New()
_, err = buffer.ReadFrom(r.reader)
if err != nil {
buffer.Release()
return 0, nil, err
}
req, err := DecodeUDPPacket(buffer)
if err != nil {
buffer.Release()
return 0, nil, err
}
n = copy(p, buffer.Bytes())
buffer.Release()
return n, &gonet.UDPAddr{IP: req.Address.IP(), Port: int(req.Port)}, nil
}
type UDPWriter struct {
request *protocol.RequestHeader
writer io.Writer
}
func NewUDPWriter(request *protocol.RequestHeader, writer io.Writer) *UDPWriter {
return &UDPWriter{
request: request,
writer: writer,
}
}
// Write implements io.Writer.
func (w *UDPWriter) Write(b []byte) (int, error) {
eb, err := EncodeUDPPacket(w.request, b)
if err != nil {
return 0, err
}
defer eb.Release()
if _, err := w.writer.Write(eb.Bytes()); err != nil {
return 0, err
}
return len(b), nil
}
func (w *UDPWriter) WriteTo(payload []byte, addr gonet.Addr) (n int, err error) {
request := *w.request
udpAddr := addr.(*gonet.UDPAddr)
request.Command = protocol.RequestCommandUDP
request.Address = net.IPAddress(udpAddr.IP)
request.Port = net.Port(udpAddr.Port)
packet, err := EncodeUDPPacket(&request, payload)
if err != nil {
return 0, err
}
_, err = w.writer.Write(packet.Bytes())
packet.Release()
return len(payload), err
}
func ClientHandshake(request *protocol.RequestHeader, reader io.Reader, writer io.Writer, delayAuthWrite bool) (*protocol.RequestHeader, error) {
authByte := byte(authNotRequired)
if request.User != nil {
authByte = byte(authPassword)
}
b := buf.New()
defer b.Release()
common.Must2(b.Write([]byte{socks5Version, 0x01, authByte}))
if !delayAuthWrite {
if authByte == authPassword {
account := request.User.Account.(*Account)
common.Must(b.WriteByte(0x01))
common.Must(b.WriteByte(byte(len(account.Username))))
common.Must2(b.WriteString(account.Username))
common.Must(b.WriteByte(byte(len(account.Password))))
common.Must2(b.WriteString(account.Password))
}
}
if err := buf.WriteAllBytes(writer, b.Bytes()); err != nil {
return nil, err
}
b.Clear()
if _, err := b.ReadFullFrom(reader, 2); err != nil {
return nil, err
}
if b.Byte(0) != socks5Version {
return nil, newError("unexpected server version: ", b.Byte(0)).AtWarning()
}
if b.Byte(1) != authByte {
return nil, newError("auth method not supported.").AtWarning()
}
if authByte == authPassword {
b.Clear()
if delayAuthWrite {
account := request.User.Account.(*Account)
common.Must(b.WriteByte(0x01))
common.Must(b.WriteByte(byte(len(account.Username))))
common.Must2(b.WriteString(account.Username))
common.Must(b.WriteByte(byte(len(account.Password))))
common.Must2(b.WriteString(account.Password))
if err := buf.WriteAllBytes(writer, b.Bytes()); err != nil {
return nil, err
}
b.Clear()
}
if _, err := b.ReadFullFrom(reader, 2); err != nil {
return nil, err
}
if b.Byte(1) != 0x00 {
return nil, newError("server rejects account: ", b.Byte(1))
}
}
b.Clear()
command := byte(cmdTCPConnect)
if request.Command == protocol.RequestCommandUDP {
command = byte(cmdUDPAssociate)
}
common.Must2(b.Write([]byte{socks5Version, command, 0x00 /* reserved */}))
if err := addrParser.WriteAddressPort(b, request.Address, request.Port); err != nil {
return nil, err
}
if err := buf.WriteAllBytes(writer, b.Bytes()); err != nil {
return nil, err
}
b.Clear()
if _, err := b.ReadFullFrom(reader, 3); err != nil {
return nil, err
}
resp := b.Byte(1)
if resp != 0x00 {
return nil, newError("server rejects request: ", resp)
}
b.Clear()
address, port, err := addrParser.ReadAddressPort(b, reader)
if err != nil {
return nil, err
}
if request.Command == protocol.RequestCommandUDP {
udpRequest := &protocol.RequestHeader{
Version: socks5Version,
Command: protocol.RequestCommandUDP,
Address: address,
Port: port,
}
return udpRequest, nil
}
return nil, nil
}
func ClientHandshake4(request *protocol.RequestHeader, reader io.Reader, writer io.Writer) error {
b := buf.New()
defer b.Release()
common.Must2(b.Write([]byte{socks4Version, cmdTCPConnect}))
portBytes := b.Extend(2)
binary.BigEndian.PutUint16(portBytes, request.Port.Value())
switch request.Address.Family() {
case net.AddressFamilyIPv4:
common.Must2(b.Write(request.Address.IP()))
case net.AddressFamilyDomain:
common.Must2(b.Write([]byte{0x00, 0x00, 0x00, 0x01}))
case net.AddressFamilyIPv6:
return newError("ipv6 is not supported in socks4")
default:
panic("Unknown family type.")
}
if request.User != nil {
account := request.User.Account.(*Account)
common.Must2(b.WriteString(account.Username))
}
common.Must(b.WriteByte(0x00))
if request.Address.Family() == net.AddressFamilyDomain {
common.Must2(b.WriteString(request.Address.Domain()))
common.Must(b.WriteByte(0x00))
}
if err := buf.WriteAllBytes(writer, b.Bytes()); err != nil {
return err
}
b.Clear()
if _, err := b.ReadFullFrom(reader, 8); err != nil {
return err
}
if b.Byte(0) != 0x00 {
return newError("unexpected version of the reply code: ", b.Byte(0))
}
if b.Byte(1) != socks4RequestGranted {
return newError("server rejects request: ", b.Byte(1))
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/protocol_test.go | proxy/socks/protocol_test.go | package socks_test
import (
"bytes"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
. "github.com/v2fly/v2ray-core/v5/proxy/socks"
)
func TestUDPEncoding(t *testing.T) {
b := buf.New()
request := &protocol.RequestHeader{
Address: net.IPAddress([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}),
Port: 1024,
}
writer := &buf.SequentialWriter{Writer: NewUDPWriter(request, b)}
content := []byte{'a'}
payload := buf.New()
payload.Write(content)
common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{payload}))
reader := NewUDPReader(b)
decodedPayload, err := reader.ReadMultiBuffer()
common.Must(err)
if r := cmp.Diff(decodedPayload[0].Bytes(), content); r != "" {
t.Error(r)
}
}
func TestReadUsernamePassword(t *testing.T) {
testCases := []struct {
Input []byte
Username string
Password string
Error bool
}{
{
Input: []byte{0x05, 0x01, 'a', 0x02, 'b', 'c'},
Username: "a",
Password: "bc",
},
{
Input: []byte{0x05, 0x18, 'a', 0x02, 'b', 'c'},
Error: true,
},
}
for _, testCase := range testCases {
reader := bytes.NewReader(testCase.Input)
username, password, err := ReadUsernamePassword(reader)
if testCase.Error {
if err == nil {
t.Error("for input: ", testCase.Input, " expect error, but actually nil")
}
} else {
if err != nil {
t.Error("for input: ", testCase.Input, " expect no error, but actually ", err.Error())
}
if testCase.Username != username {
t.Error("for input: ", testCase.Input, " expect username ", testCase.Username, " but actually ", username)
}
if testCase.Password != password {
t.Error("for input: ", testCase.Input, " expect password ", testCase.Password, " but actually ", password)
}
}
}
}
func TestReadUntilNull(t *testing.T) {
testCases := []struct {
Input []byte
Output string
Error bool
}{
{
Input: []byte{'a', 'b', 0x00},
Output: "ab",
},
{
Input: []byte{'a'},
Error: true,
},
}
for _, testCase := range testCases {
reader := bytes.NewReader(testCase.Input)
value, err := ReadUntilNull(reader)
if testCase.Error {
if err == nil {
t.Error("for input: ", testCase.Input, " expect error, but actually nil")
}
} else {
if err != nil {
t.Error("for input: ", testCase.Input, " expect no error, but actually ", err.Error())
}
if testCase.Output != value {
t.Error("for input: ", testCase.Input, " expect output ", testCase.Output, " but actually ", value)
}
}
}
}
func BenchmarkReadUsernamePassword(b *testing.B) {
input := []byte{0x05, 0x01, 'a', 0x02, 'b', 'c'}
buffer := buf.New()
buffer.Write(input)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _, err := ReadUsernamePassword(buffer)
common.Must(err)
buffer.Clear()
buffer.Extend(int32(len(input)))
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/server.go | proxy/socks/server.go | package socks
import (
"context"
"io"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/log"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/protocol"
udp_proto "github.com/v2fly/v2ray-core/v5/common/protocol/udp"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
// Server is a SOCKS 5 proxy server
type Server struct {
config *ServerConfig
policyManager policy.Manager
}
// NewServer creates a new Server object.
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
v := core.MustFromContext(ctx)
s := &Server{
config: config,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}
return s, nil
}
func (s *Server) policy() policy.Session {
config := s.config
p := s.policyManager.ForLevel(config.UserLevel)
if config.Timeout > 0 {
features.PrintDeprecatedFeatureWarning("Socks timeout")
}
if config.Timeout > 0 && config.UserLevel == 0 {
p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second
}
return p
}
// Network implements proxy.Inbound.
func (s *Server) Network() []net.Network {
list := []net.Network{net.Network_TCP}
if s.config.UdpEnabled {
list = append(list, net.Network_UDP)
}
return list
}
// Process implements proxy.Inbound.
func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
if inbound := session.InboundFromContext(ctx); inbound != nil {
inbound.User = &protocol.MemoryUser{
Level: s.config.UserLevel,
}
}
switch network {
case net.Network_TCP:
return s.processTCP(ctx, conn, dispatcher)
case net.Network_UDP:
return s.handleUDPPayload(ctx, conn, dispatcher)
default:
return newError("unknown network: ", network)
}
}
func (s *Server) processTCP(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
plcy := s.policy()
if err := conn.SetReadDeadline(time.Now().Add(plcy.Timeouts.Handshake)); err != nil {
newError("failed to set deadline").Base(err).WriteToLog(session.ExportIDToError(ctx))
}
inbound := session.InboundFromContext(ctx)
if inbound == nil || !inbound.Gateway.IsValid() {
return newError("inbound gateway not specified")
}
svrSession := &ServerSession{
config: s.config,
address: inbound.Gateway.Address,
port: inbound.Gateway.Port,
clientAddress: inbound.Source.Address,
}
reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
request, err := svrSession.Handshake(reader, conn)
if err != nil {
if inbound != nil && inbound.Source.IsValid() {
log.Record(&log.AccessMessage{
From: inbound.Source,
To: "",
Status: log.AccessRejected,
Reason: err,
})
}
return newError("failed to read request").Base(err)
}
if request.User != nil {
inbound.User.Email = request.User.Email
}
if err := conn.SetReadDeadline(time.Time{}); err != nil {
newError("failed to clear deadline").Base(err).WriteToLog(session.ExportIDToError(ctx))
}
if request.Command == protocol.RequestCommandTCP {
dest := request.Destination()
newError("TCP Connect request to ", dest).WriteToLog(session.ExportIDToError(ctx))
if inbound != nil && inbound.Source.IsValid() {
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: inbound.Source,
To: dest,
Status: log.AccessAccepted,
Reason: "",
})
}
dispatcher = &handshakeFinalizingDispatcher{Feature: dispatcher, delegate: dispatcher, serverSession: svrSession}
return s.transport(ctx, reader, conn, dest, dispatcher)
}
err = svrSession.flushLastReply(true)
if err != nil {
return err
}
if request.Command == protocol.RequestCommandUDP {
return s.handleUDP(conn)
}
return nil
}
// Wrapper to send final SOCKS reply only after Dispatch() returns
type handshakeFinalizingDispatcher struct {
features.Feature // do not inherit Dispatch() in case its signature changes
delegate routing.Dispatcher
serverSession *ServerSession
}
func (d *handshakeFinalizingDispatcher) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
link, err := d.delegate.Dispatch(ctx, dest)
if err == nil {
closeInDefer := true
defer func() {
if closeInDefer {
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
}
}()
err = d.serverSession.flushLastReply(true)
if err != nil {
return nil, err
}
closeInDefer = false
} else {
d.serverSession.flushLastReply(false)
}
return link, err
}
func (*Server) handleUDP(c io.Reader) error {
// The TCP connection closes after this method returns. We need to wait until
// the client closes it.
return common.Error2(io.Copy(buf.DiscardBytes, c))
}
func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writer, dest net.Destination, dispatcher routing.Dispatcher) error {
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, s.policy().Timeouts.ConnectionIdle)
plcy := s.policy()
ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer)
link, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return err
}
requestDone := func() error {
defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
if err := buf.Copy(buf.NewReader(reader), link.Writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport all TCP request").Base(err)
}
return nil
}
responseDone := func() error {
defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
v2writer := buf.NewWriter(writer)
if err := buf.Copy(link.Reader, v2writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport all TCP response").Base(err)
}
return nil
}
requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
return newError("connection ends").Base(err)
}
return nil
}
func (s *Server) handleUDPPayload(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
udpDispatcherConstructor := udp.NewSplitDispatcher
switch s.config.PacketEncoding {
case packetaddr.PacketAddrType_None:
break
case packetaddr.PacketAddrType_Packet:
packetAddrDispatcherFactory := udp.NewPacketAddrDispatcherCreator(ctx)
udpDispatcherConstructor = packetAddrDispatcherFactory.NewPacketAddrDispatcher
}
udpServer := udpDispatcherConstructor(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
payload := packet.Payload
newError("writing back UDP response with ", payload.Len(), " bytes").AtDebug().WriteToLog(session.ExportIDToError(ctx))
request := protocol.RequestHeaderFromContext(ctx)
var packetSource net.Destination
if request == nil {
packetSource = packet.Source
} else {
packetSource = net.UDPDestination(request.Address, request.Port)
}
udpMessage, err := EncodeUDPPacketFromAddress(packetSource, payload.Bytes())
payload.Release()
defer udpMessage.Release()
if err != nil {
newError("failed to write UDP response").AtWarning().Base(err).WriteToLog(session.ExportIDToError(ctx))
}
conn.Write(udpMessage.Bytes())
})
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
newError("client UDP connection from ", inbound.Source).WriteToLog(session.ExportIDToError(ctx))
}
reader := buf.NewPacketReader(conn)
for {
mpayload, err := reader.ReadMultiBuffer()
if err != nil {
return err
}
for _, payload := range mpayload {
request, err := DecodeUDPPacket(payload)
if err != nil {
newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx))
payload.Release()
continue
}
if payload.IsEmpty() {
payload.Release()
continue
}
currentPacketCtx := ctx
newError("send packet to ", request.Destination(), " with ", payload.Len(), " bytes").AtDebug().WriteToLog(session.ExportIDToError(ctx))
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
currentPacketCtx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: inbound.Source,
To: request.Destination(),
Status: log.AccessAccepted,
Reason: "",
})
}
currentPacketCtx = protocol.ContextWithRequestHeader(currentPacketCtx, request)
udpServer.Dispatch(currentPacketCtx, request.Destination(), payload)
}
}
}
func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewServer(ctx, config.(*ServerConfig))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/config.pb.go | proxy/socks/config.pb.go | package socks
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
packetaddr "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
protocol "github.com/v2fly/v2ray-core/v5/common/protocol"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// AuthType is the authentication type of Socks proxy.
type AuthType int32
const (
// NO_AUTH is for anonymous authentication.
AuthType_NO_AUTH AuthType = 0
// PASSWORD is for username/password authentication.
AuthType_PASSWORD AuthType = 1
)
// Enum value maps for AuthType.
var (
AuthType_name = map[int32]string{
0: "NO_AUTH",
1: "PASSWORD",
}
AuthType_value = map[string]int32{
"NO_AUTH": 0,
"PASSWORD": 1,
}
)
func (x AuthType) Enum() *AuthType {
p := new(AuthType)
*p = x
return p
}
func (x AuthType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (AuthType) Descriptor() protoreflect.EnumDescriptor {
return file_proxy_socks_config_proto_enumTypes[0].Descriptor()
}
func (AuthType) Type() protoreflect.EnumType {
return &file_proxy_socks_config_proto_enumTypes[0]
}
func (x AuthType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use AuthType.Descriptor instead.
func (AuthType) EnumDescriptor() ([]byte, []int) {
return file_proxy_socks_config_proto_rawDescGZIP(), []int{0}
}
type Version int32
const (
Version_SOCKS5 Version = 0
Version_SOCKS4 Version = 1
Version_SOCKS4A Version = 2
)
// Enum value maps for Version.
var (
Version_name = map[int32]string{
0: "SOCKS5",
1: "SOCKS4",
2: "SOCKS4A",
}
Version_value = map[string]int32{
"SOCKS5": 0,
"SOCKS4": 1,
"SOCKS4A": 2,
}
)
func (x Version) Enum() *Version {
p := new(Version)
*p = x
return p
}
func (x Version) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (Version) Descriptor() protoreflect.EnumDescriptor {
return file_proxy_socks_config_proto_enumTypes[1].Descriptor()
}
func (Version) Type() protoreflect.EnumType {
return &file_proxy_socks_config_proto_enumTypes[1]
}
func (x Version) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use Version.Descriptor instead.
func (Version) EnumDescriptor() ([]byte, []int) {
return file_proxy_socks_config_proto_rawDescGZIP(), []int{1}
}
// Account represents a Socks account.
type Account struct {
state protoimpl.MessageState `protogen:"open.v1"`
Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`
Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Account) Reset() {
*x = Account{}
mi := &file_proxy_socks_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Account) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Account) ProtoMessage() {}
func (x *Account) ProtoReflect() protoreflect.Message {
mi := &file_proxy_socks_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Account.ProtoReflect.Descriptor instead.
func (*Account) Descriptor() ([]byte, []int) {
return file_proxy_socks_config_proto_rawDescGZIP(), []int{0}
}
func (x *Account) GetUsername() string {
if x != nil {
return x.Username
}
return ""
}
func (x *Account) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
// ServerConfig is the protobuf config for Socks server.
type ServerConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
AuthType AuthType `protobuf:"varint,1,opt,name=auth_type,json=authType,proto3,enum=v2ray.core.proxy.socks.AuthType" json:"auth_type,omitempty"`
Accounts map[string]string `protobuf:"bytes,2,rep,name=accounts,proto3" json:"accounts,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
Address *net.IPOrDomain `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"`
UdpEnabled bool `protobuf:"varint,4,opt,name=udp_enabled,json=udpEnabled,proto3" json:"udp_enabled,omitempty"`
// Deprecated: Marked as deprecated in proxy/socks/config.proto.
Timeout uint32 `protobuf:"varint,5,opt,name=timeout,proto3" json:"timeout,omitempty"`
UserLevel uint32 `protobuf:"varint,6,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
PacketEncoding packetaddr.PacketAddrType `protobuf:"varint,7,opt,name=packet_encoding,json=packetEncoding,proto3,enum=v2ray.core.net.packetaddr.PacketAddrType" json:"packet_encoding,omitempty"`
DeferLastReply bool `protobuf:"varint,8,opt,name=defer_last_reply,json=deferLastReply,proto3" json:"defer_last_reply,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerConfig) Reset() {
*x = ServerConfig{}
mi := &file_proxy_socks_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerConfig) ProtoMessage() {}
func (x *ServerConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_socks_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerConfig.ProtoReflect.Descriptor instead.
func (*ServerConfig) Descriptor() ([]byte, []int) {
return file_proxy_socks_config_proto_rawDescGZIP(), []int{1}
}
func (x *ServerConfig) GetAuthType() AuthType {
if x != nil {
return x.AuthType
}
return AuthType_NO_AUTH
}
func (x *ServerConfig) GetAccounts() map[string]string {
if x != nil {
return x.Accounts
}
return nil
}
func (x *ServerConfig) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *ServerConfig) GetUdpEnabled() bool {
if x != nil {
return x.UdpEnabled
}
return false
}
// Deprecated: Marked as deprecated in proxy/socks/config.proto.
func (x *ServerConfig) GetTimeout() uint32 {
if x != nil {
return x.Timeout
}
return 0
}
func (x *ServerConfig) GetUserLevel() uint32 {
if x != nil {
return x.UserLevel
}
return 0
}
func (x *ServerConfig) GetPacketEncoding() packetaddr.PacketAddrType {
if x != nil {
return x.PacketEncoding
}
return packetaddr.PacketAddrType(0)
}
func (x *ServerConfig) GetDeferLastReply() bool {
if x != nil {
return x.DeferLastReply
}
return false
}
// ClientConfig is the protobuf config for Socks client.
type ClientConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Sever is a list of Socks server addresses.
Server []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=server,proto3" json:"server,omitempty"`
Version Version `protobuf:"varint,2,opt,name=version,proto3,enum=v2ray.core.proxy.socks.Version" json:"version,omitempty"`
DelayAuthWrite bool `protobuf:"varint,3,opt,name=delay_auth_write,json=delayAuthWrite,proto3" json:"delay_auth_write,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClientConfig) Reset() {
*x = ClientConfig{}
mi := &file_proxy_socks_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ClientConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ClientConfig) ProtoMessage() {}
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_socks_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
func (*ClientConfig) Descriptor() ([]byte, []int) {
return file_proxy_socks_config_proto_rawDescGZIP(), []int{2}
}
func (x *ClientConfig) GetServer() []*protocol.ServerEndpoint {
if x != nil {
return x.Server
}
return nil
}
func (x *ClientConfig) GetVersion() Version {
if x != nil {
return x.Version
}
return Version_SOCKS5
}
func (x *ClientConfig) GetDelayAuthWrite() bool {
if x != nil {
return x.DelayAuthWrite
}
return false
}
var File_proxy_socks_config_proto protoreflect.FileDescriptor
const file_proxy_socks_config_proto_rawDesc = "" +
"\n" +
"\x18proxy/socks/config.proto\x12\x16v2ray.core.proxy.socks\x1a\x18common/net/address.proto\x1a\"common/net/packetaddr/config.proto\x1a!common/protocol/server_spec.proto\"A\n" +
"\aAccount\x12\x1a\n" +
"\busername\x18\x01 \x01(\tR\busername\x12\x1a\n" +
"\bpassword\x18\x02 \x01(\tR\bpassword\"\xf3\x03\n" +
"\fServerConfig\x12=\n" +
"\tauth_type\x18\x01 \x01(\x0e2 .v2ray.core.proxy.socks.AuthTypeR\bauthType\x12N\n" +
"\baccounts\x18\x02 \x03(\v22.v2ray.core.proxy.socks.ServerConfig.AccountsEntryR\baccounts\x12;\n" +
"\aaddress\x18\x03 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x1f\n" +
"\vudp_enabled\x18\x04 \x01(\bR\n" +
"udpEnabled\x12\x1c\n" +
"\atimeout\x18\x05 \x01(\rB\x02\x18\x01R\atimeout\x12\x1d\n" +
"\n" +
"user_level\x18\x06 \x01(\rR\tuserLevel\x12R\n" +
"\x0fpacket_encoding\x18\a \x01(\x0e2).v2ray.core.net.packetaddr.PacketAddrTypeR\x0epacketEncoding\x12(\n" +
"\x10defer_last_reply\x18\b \x01(\bR\x0edeferLastReply\x1a;\n" +
"\rAccountsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xb7\x01\n" +
"\fClientConfig\x12B\n" +
"\x06server\x18\x01 \x03(\v2*.v2ray.core.common.protocol.ServerEndpointR\x06server\x129\n" +
"\aversion\x18\x02 \x01(\x0e2\x1f.v2ray.core.proxy.socks.VersionR\aversion\x12(\n" +
"\x10delay_auth_write\x18\x03 \x01(\bR\x0edelayAuthWrite*%\n" +
"\bAuthType\x12\v\n" +
"\aNO_AUTH\x10\x00\x12\f\n" +
"\bPASSWORD\x10\x01*.\n" +
"\aVersion\x12\n" +
"\n" +
"\x06SOCKS5\x10\x00\x12\n" +
"\n" +
"\x06SOCKS4\x10\x01\x12\v\n" +
"\aSOCKS4A\x10\x02Bc\n" +
"\x1acom.v2ray.core.proxy.socksP\x01Z*github.com/v2fly/v2ray-core/v5/proxy/socks\xaa\x02\x16V2Ray.Core.Proxy.Socksb\x06proto3"
var (
file_proxy_socks_config_proto_rawDescOnce sync.Once
file_proxy_socks_config_proto_rawDescData []byte
)
func file_proxy_socks_config_proto_rawDescGZIP() []byte {
file_proxy_socks_config_proto_rawDescOnce.Do(func() {
file_proxy_socks_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_socks_config_proto_rawDesc), len(file_proxy_socks_config_proto_rawDesc)))
})
return file_proxy_socks_config_proto_rawDescData
}
var file_proxy_socks_config_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
var file_proxy_socks_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_proxy_socks_config_proto_goTypes = []any{
(AuthType)(0), // 0: v2ray.core.proxy.socks.AuthType
(Version)(0), // 1: v2ray.core.proxy.socks.Version
(*Account)(nil), // 2: v2ray.core.proxy.socks.Account
(*ServerConfig)(nil), // 3: v2ray.core.proxy.socks.ServerConfig
(*ClientConfig)(nil), // 4: v2ray.core.proxy.socks.ClientConfig
nil, // 5: v2ray.core.proxy.socks.ServerConfig.AccountsEntry
(*net.IPOrDomain)(nil), // 6: v2ray.core.common.net.IPOrDomain
(packetaddr.PacketAddrType)(0), // 7: v2ray.core.net.packetaddr.PacketAddrType
(*protocol.ServerEndpoint)(nil), // 8: v2ray.core.common.protocol.ServerEndpoint
}
var file_proxy_socks_config_proto_depIdxs = []int32{
0, // 0: v2ray.core.proxy.socks.ServerConfig.auth_type:type_name -> v2ray.core.proxy.socks.AuthType
5, // 1: v2ray.core.proxy.socks.ServerConfig.accounts:type_name -> v2ray.core.proxy.socks.ServerConfig.AccountsEntry
6, // 2: v2ray.core.proxy.socks.ServerConfig.address:type_name -> v2ray.core.common.net.IPOrDomain
7, // 3: v2ray.core.proxy.socks.ServerConfig.packet_encoding:type_name -> v2ray.core.net.packetaddr.PacketAddrType
8, // 4: v2ray.core.proxy.socks.ClientConfig.server:type_name -> v2ray.core.common.protocol.ServerEndpoint
1, // 5: v2ray.core.proxy.socks.ClientConfig.version:type_name -> v2ray.core.proxy.socks.Version
6, // [6:6] is the sub-list for method output_type
6, // [6:6] is the sub-list for method input_type
6, // [6:6] is the sub-list for extension type_name
6, // [6:6] is the sub-list for extension extendee
0, // [0:6] is the sub-list for field type_name
}
func init() { file_proxy_socks_config_proto_init() }
func file_proxy_socks_config_proto_init() {
if File_proxy_socks_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_socks_config_proto_rawDesc), len(file_proxy_socks_config_proto_rawDesc)),
NumEnums: 2,
NumMessages: 4,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_socks_config_proto_goTypes,
DependencyIndexes: file_proxy_socks_config_proto_depIdxs,
EnumInfos: file_proxy_socks_config_proto_enumTypes,
MessageInfos: file_proxy_socks_config_proto_msgTypes,
}.Build()
File_proxy_socks_config_proto = out.File
file_proxy_socks_config_proto_goTypes = nil
file_proxy_socks_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/simplified/config.go | proxy/socks/simplified/config.go | package simplified
import (
"context"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/proxy/socks"
)
func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedServer := config.(*ServerConfig)
fullServer := &socks.ServerConfig{
AuthType: socks.AuthType_NO_AUTH,
Address: simplifiedServer.Address,
UdpEnabled: simplifiedServer.UdpEnabled,
PacketEncoding: simplifiedServer.PacketEncoding,
DeferLastReply: simplifiedServer.DeferLastReply,
}
return common.CreateObject(ctx, fullServer)
}))
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedClient := config.(*ClientConfig)
fullClient := &socks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: simplifiedClient.Address,
Port: simplifiedClient.Port,
},
},
}
return common.CreateObject(ctx, fullClient)
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/socks/simplified/config.pb.go | proxy/socks/simplified/config.pb.go | package simplified
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
packetaddr "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ServerConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Address *net.IPOrDomain `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"`
UdpEnabled bool `protobuf:"varint,4,opt,name=udp_enabled,json=udpEnabled,proto3" json:"udp_enabled,omitempty"`
PacketEncoding packetaddr.PacketAddrType `protobuf:"varint,7,opt,name=packet_encoding,json=packetEncoding,proto3,enum=v2ray.core.net.packetaddr.PacketAddrType" json:"packet_encoding,omitempty"`
DeferLastReply bool `protobuf:"varint,8,opt,name=defer_last_reply,json=deferLastReply,proto3" json:"defer_last_reply,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerConfig) Reset() {
*x = ServerConfig{}
mi := &file_proxy_socks_simplified_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerConfig) ProtoMessage() {}
func (x *ServerConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_socks_simplified_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerConfig.ProtoReflect.Descriptor instead.
func (*ServerConfig) Descriptor() ([]byte, []int) {
return file_proxy_socks_simplified_config_proto_rawDescGZIP(), []int{0}
}
func (x *ServerConfig) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *ServerConfig) GetUdpEnabled() bool {
if x != nil {
return x.UdpEnabled
}
return false
}
func (x *ServerConfig) GetPacketEncoding() packetaddr.PacketAddrType {
if x != nil {
return x.PacketEncoding
}
return packetaddr.PacketAddrType(0)
}
func (x *ServerConfig) GetDeferLastReply() bool {
if x != nil {
return x.DeferLastReply
}
return false
}
type ClientConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClientConfig) Reset() {
*x = ClientConfig{}
mi := &file_proxy_socks_simplified_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ClientConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ClientConfig) ProtoMessage() {}
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_socks_simplified_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
func (*ClientConfig) Descriptor() ([]byte, []int) {
return file_proxy_socks_simplified_config_proto_rawDescGZIP(), []int{1}
}
func (x *ClientConfig) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *ClientConfig) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
var File_proxy_socks_simplified_config_proto protoreflect.FileDescriptor
const file_proxy_socks_simplified_config_proto_rawDesc = "" +
"\n" +
"#proxy/socks/simplified/config.proto\x12!v2ray.core.proxy.socks.simplified\x1a common/protoext/extensions.proto\x1a\x18common/net/address.proto\x1a\"common/net/packetaddr/config.proto\"\x80\x02\n" +
"\fServerConfig\x12;\n" +
"\aaddress\x18\x03 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x1f\n" +
"\vudp_enabled\x18\x04 \x01(\bR\n" +
"udpEnabled\x12R\n" +
"\x0fpacket_encoding\x18\a \x01(\x0e2).v2ray.core.net.packetaddr.PacketAddrTypeR\x0epacketEncoding\x12(\n" +
"\x10defer_last_reply\x18\b \x01(\bR\x0edeferLastReply:\x14\x82\xb5\x18\x10\n" +
"\ainbound\x12\x05socks\"v\n" +
"\fClientConfig\x12;\n" +
"\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" +
"\x04port\x18\x02 \x01(\rR\x04port:\x15\x82\xb5\x18\x11\n" +
"\boutbound\x12\x05socksB\x84\x01\n" +
"%com.v2ray.core.proxy.socks.simplifiedP\x01Z5github.com/v2fly/v2ray-core/v5/proxy/socks/simplified\xaa\x02!V2Ray.Core.Proxy.Socks.Simplifiedb\x06proto3"
var (
file_proxy_socks_simplified_config_proto_rawDescOnce sync.Once
file_proxy_socks_simplified_config_proto_rawDescData []byte
)
func file_proxy_socks_simplified_config_proto_rawDescGZIP() []byte {
file_proxy_socks_simplified_config_proto_rawDescOnce.Do(func() {
file_proxy_socks_simplified_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_socks_simplified_config_proto_rawDesc), len(file_proxy_socks_simplified_config_proto_rawDesc)))
})
return file_proxy_socks_simplified_config_proto_rawDescData
}
var file_proxy_socks_simplified_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_proxy_socks_simplified_config_proto_goTypes = []any{
(*ServerConfig)(nil), // 0: v2ray.core.proxy.socks.simplified.ServerConfig
(*ClientConfig)(nil), // 1: v2ray.core.proxy.socks.simplified.ClientConfig
(*net.IPOrDomain)(nil), // 2: v2ray.core.common.net.IPOrDomain
(packetaddr.PacketAddrType)(0), // 3: v2ray.core.net.packetaddr.PacketAddrType
}
var file_proxy_socks_simplified_config_proto_depIdxs = []int32{
2, // 0: v2ray.core.proxy.socks.simplified.ServerConfig.address:type_name -> v2ray.core.common.net.IPOrDomain
3, // 1: v2ray.core.proxy.socks.simplified.ServerConfig.packet_encoding:type_name -> v2ray.core.net.packetaddr.PacketAddrType
2, // 2: v2ray.core.proxy.socks.simplified.ClientConfig.address:type_name -> v2ray.core.common.net.IPOrDomain
3, // [3:3] is the sub-list for method output_type
3, // [3:3] is the sub-list for method input_type
3, // [3:3] is the sub-list for extension type_name
3, // [3:3] is the sub-list for extension extendee
0, // [0:3] is the sub-list for field type_name
}
func init() { file_proxy_socks_simplified_config_proto_init() }
func file_proxy_socks_simplified_config_proto_init() {
if File_proxy_socks_simplified_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_socks_simplified_config_proto_rawDesc), len(file_proxy_socks_simplified_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_socks_simplified_config_proto_goTypes,
DependencyIndexes: file_proxy_socks_simplified_config_proto_depIdxs,
MessageInfos: file_proxy_socks_simplified_config_proto_msgTypes,
}.Build()
File_proxy_socks_simplified_config_proto = out.File
file_proxy_socks_simplified_config_proto_goTypes = nil
file_proxy_socks_simplified_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/blackhole/errors.generated.go | proxy/blackhole/errors.generated.go | package blackhole
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/blackhole/config.go | proxy/blackhole/config.go | package blackhole
import (
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/serial"
)
const (
http403response = `HTTP/1.1 403 Forbidden
Connection: close
Cache-Control: max-age=3600, public
Content-Length: 0
`
)
// ResponseConfig is the configuration for blackhole responses.
type ResponseConfig interface {
// WriteTo writes predefined response to the give buffer.
WriteTo(buf.Writer) int32
}
// WriteTo implements ResponseConfig.WriteTo().
func (*NoneResponse) WriteTo(buf.Writer) int32 { return 0 }
// WriteTo implements ResponseConfig.WriteTo().
func (*HTTPResponse) WriteTo(writer buf.Writer) int32 {
b := buf.New()
common.Must2(b.WriteString(http403response))
n := b.Len()
writer.WriteMultiBuffer(buf.MultiBuffer{b})
return n
}
// GetInternalResponse converts response settings from proto to internal data structure.
func (c *Config) GetInternalResponse() (ResponseConfig, error) {
if c.GetResponse() == nil {
return new(NoneResponse), nil
}
config, err := serial.GetInstanceOf(c.GetResponse())
if err != nil {
return nil, err
}
return config.(ResponseConfig), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/blackhole/config_test.go | proxy/blackhole/config_test.go | package blackhole_test
import (
"bufio"
"net/http"
"testing"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
. "github.com/v2fly/v2ray-core/v5/proxy/blackhole"
)
func TestHTTPResponse(t *testing.T) {
buffer := buf.New()
httpResponse := new(HTTPResponse)
httpResponse.WriteTo(buf.NewWriter(buffer))
reader := bufio.NewReader(buffer)
response, err := http.ReadResponse(reader, nil)
common.Must(err)
defer response.Body.Close()
if response.StatusCode != 403 {
t.Error("expected status code 403, but got ", response.StatusCode)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/blackhole/blackhole.go | proxy/blackhole/blackhole.go | // Package blackhole is an outbound handler that blocks all connections.
package blackhole
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
// Handler is an outbound connection that silently swallow the entire payload.
type Handler struct {
response ResponseConfig
}
// New creates a new blackhole handler.
func New(ctx context.Context, config *Config) (*Handler, error) {
response, err := config.GetInternalResponse()
if err != nil {
return nil, err
}
return &Handler{
response: response,
}, nil
}
// Process implements OutboundHandler.Dispatch().
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
nBytes := h.response.WriteTo(link.Writer)
if nBytes > 0 {
// Sleep a little here to make sure the response is sent to client.
time.Sleep(time.Second)
}
common.Interrupt(link.Writer)
return nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedServer := config.(*SimplifiedConfig)
_ = simplifiedServer
fullConfig := &Config{}
return common.CreateObject(ctx, fullConfig)
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/blackhole/config.pb.go | proxy/blackhole/config.pb.go | package blackhole
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
anypb "google.golang.org/protobuf/types/known/anypb"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type NoneResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *NoneResponse) Reset() {
*x = NoneResponse{}
mi := &file_proxy_blackhole_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *NoneResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*NoneResponse) ProtoMessage() {}
func (x *NoneResponse) ProtoReflect() protoreflect.Message {
mi := &file_proxy_blackhole_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use NoneResponse.ProtoReflect.Descriptor instead.
func (*NoneResponse) Descriptor() ([]byte, []int) {
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{0}
}
type HTTPResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *HTTPResponse) Reset() {
*x = HTTPResponse{}
mi := &file_proxy_blackhole_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *HTTPResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HTTPResponse) ProtoMessage() {}
func (x *HTTPResponse) ProtoReflect() protoreflect.Message {
mi := &file_proxy_blackhole_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use HTTPResponse.ProtoReflect.Descriptor instead.
func (*HTTPResponse) Descriptor() ([]byte, []int) {
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{1}
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Response *anypb.Any `protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_blackhole_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_blackhole_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{2}
}
func (x *Config) GetResponse() *anypb.Any {
if x != nil {
return x.Response
}
return nil
}
type SimplifiedConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SimplifiedConfig) Reset() {
*x = SimplifiedConfig{}
mi := &file_proxy_blackhole_config_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SimplifiedConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SimplifiedConfig) ProtoMessage() {}
func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_blackhole_config_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead.
func (*SimplifiedConfig) Descriptor() ([]byte, []int) {
return file_proxy_blackhole_config_proto_rawDescGZIP(), []int{3}
}
var File_proxy_blackhole_config_proto protoreflect.FileDescriptor
const file_proxy_blackhole_config_proto_rawDesc = "" +
"\n" +
"\x1cproxy/blackhole/config.proto\x12\x1av2ray.core.proxy.blackhole\x1a\x19google/protobuf/any.proto\x1a common/protoext/extensions.proto\"\x0e\n" +
"\fNoneResponse\"\x0e\n" +
"\fHTTPResponse\":\n" +
"\x06Config\x120\n" +
"\bresponse\x18\x01 \x01(\v2\x14.google.protobuf.AnyR\bresponse\"-\n" +
"\x10SimplifiedConfig:\x19\x82\xb5\x18\x15\n" +
"\boutbound\x12\tblackholeBo\n" +
"\x1ecom.v2ray.core.proxy.blackholeP\x01Z.github.com/v2fly/v2ray-core/v5/proxy/blackhole\xaa\x02\x1aV2Ray.Core.Proxy.Blackholeb\x06proto3"
var (
file_proxy_blackhole_config_proto_rawDescOnce sync.Once
file_proxy_blackhole_config_proto_rawDescData []byte
)
func file_proxy_blackhole_config_proto_rawDescGZIP() []byte {
file_proxy_blackhole_config_proto_rawDescOnce.Do(func() {
file_proxy_blackhole_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)))
})
return file_proxy_blackhole_config_proto_rawDescData
}
var file_proxy_blackhole_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_proxy_blackhole_config_proto_goTypes = []any{
(*NoneResponse)(nil), // 0: v2ray.core.proxy.blackhole.NoneResponse
(*HTTPResponse)(nil), // 1: v2ray.core.proxy.blackhole.HTTPResponse
(*Config)(nil), // 2: v2ray.core.proxy.blackhole.Config
(*SimplifiedConfig)(nil), // 3: v2ray.core.proxy.blackhole.SimplifiedConfig
(*anypb.Any)(nil), // 4: google.protobuf.Any
}
var file_proxy_blackhole_config_proto_depIdxs = []int32{
4, // 0: v2ray.core.proxy.blackhole.Config.response:type_name -> google.protobuf.Any
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_proxy_blackhole_config_proto_init() }
func file_proxy_blackhole_config_proto_init() {
if File_proxy_blackhole_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_blackhole_config_proto_rawDesc), len(file_proxy_blackhole_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_blackhole_config_proto_goTypes,
DependencyIndexes: file_proxy_blackhole_config_proto_depIdxs,
MessageInfos: file_proxy_blackhole_config_proto_msgTypes,
}.Build()
File_proxy_blackhole_config_proto = out.File
file_proxy_blackhole_config_proto_goTypes = nil
file_proxy_blackhole_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/blackhole/blackhole_test.go | proxy/blackhole/blackhole_test.go | package blackhole_test
import (
"context"
"testing"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/proxy/blackhole"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/pipe"
)
func TestBlackHoleHTTPResponse(t *testing.T) {
handler, err := blackhole.New(context.Background(), &blackhole.Config{
Response: serial.ToTypedMessage(&blackhole.HTTPResponse{}),
})
common.Must(err)
reader, writer := pipe.New(pipe.WithoutSizeLimit())
readerError := make(chan error)
var mb buf.MultiBuffer
go func() {
b, e := reader.ReadMultiBuffer()
mb = b
readerError <- e
}()
link := transport.Link{
Reader: reader,
Writer: writer,
}
common.Must(handler.Process(context.Background(), &link, nil))
common.Must(<-readerError)
if mb.IsEmpty() {
t.Error("expect http response, but nothing")
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/freedom/errors.generated.go | proxy/freedom/errors.generated.go | package freedom
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/freedom/config.go | proxy/freedom/config.go | package freedom
func (c *Config) useIP() bool {
return c.DomainStrategy == Config_USE_IP || c.DomainStrategy == Config_USE_IP4 || c.DomainStrategy == Config_USE_IP6
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/freedom/config.pb.go | proxy/freedom/config.pb.go | package freedom
import (
protocol "github.com/v2fly/v2ray-core/v5/common/protocol"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ProtocolReplacement int32
const (
ProtocolReplacement_IDENTITY ProtocolReplacement = 0
ProtocolReplacement_FORCE_TCP ProtocolReplacement = 1
ProtocolReplacement_FORCE_UDP ProtocolReplacement = 2
)
// Enum value maps for ProtocolReplacement.
var (
ProtocolReplacement_name = map[int32]string{
0: "IDENTITY",
1: "FORCE_TCP",
2: "FORCE_UDP",
}
ProtocolReplacement_value = map[string]int32{
"IDENTITY": 0,
"FORCE_TCP": 1,
"FORCE_UDP": 2,
}
)
func (x ProtocolReplacement) Enum() *ProtocolReplacement {
p := new(ProtocolReplacement)
*p = x
return p
}
func (x ProtocolReplacement) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (ProtocolReplacement) Descriptor() protoreflect.EnumDescriptor {
return file_proxy_freedom_config_proto_enumTypes[0].Descriptor()
}
func (ProtocolReplacement) Type() protoreflect.EnumType {
return &file_proxy_freedom_config_proto_enumTypes[0]
}
func (x ProtocolReplacement) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use ProtocolReplacement.Descriptor instead.
func (ProtocolReplacement) EnumDescriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{0}
}
type Config_DomainStrategy int32
const (
Config_AS_IS Config_DomainStrategy = 0
Config_USE_IP Config_DomainStrategy = 1
Config_USE_IP4 Config_DomainStrategy = 2
Config_USE_IP6 Config_DomainStrategy = 3
)
// Enum value maps for Config_DomainStrategy.
var (
Config_DomainStrategy_name = map[int32]string{
0: "AS_IS",
1: "USE_IP",
2: "USE_IP4",
3: "USE_IP6",
}
Config_DomainStrategy_value = map[string]int32{
"AS_IS": 0,
"USE_IP": 1,
"USE_IP4": 2,
"USE_IP6": 3,
}
)
func (x Config_DomainStrategy) Enum() *Config_DomainStrategy {
p := new(Config_DomainStrategy)
*p = x
return p
}
func (x Config_DomainStrategy) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (Config_DomainStrategy) Descriptor() protoreflect.EnumDescriptor {
return file_proxy_freedom_config_proto_enumTypes[1].Descriptor()
}
func (Config_DomainStrategy) Type() protoreflect.EnumType {
return &file_proxy_freedom_config_proto_enumTypes[1]
}
func (x Config_DomainStrategy) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use Config_DomainStrategy.Descriptor instead.
func (Config_DomainStrategy) EnumDescriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{1, 0}
}
type DestinationOverride struct {
state protoimpl.MessageState `protogen:"open.v1"`
Server *protocol.ServerEndpoint `protobuf:"bytes,1,opt,name=server,proto3" json:"server,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DestinationOverride) Reset() {
*x = DestinationOverride{}
mi := &file_proxy_freedom_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *DestinationOverride) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DestinationOverride) ProtoMessage() {}
func (x *DestinationOverride) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DestinationOverride.ProtoReflect.Descriptor instead.
func (*DestinationOverride) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{0}
}
func (x *DestinationOverride) GetServer() *protocol.ServerEndpoint {
if x != nil {
return x.Server
}
return nil
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
DomainStrategy Config_DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=v2ray.core.proxy.freedom.Config_DomainStrategy" json:"domain_strategy,omitempty"`
// Deprecated: Marked as deprecated in proxy/freedom/config.proto.
Timeout uint32 `protobuf:"varint,2,opt,name=timeout,proto3" json:"timeout,omitempty"`
DestinationOverride *DestinationOverride `protobuf:"bytes,3,opt,name=destination_override,json=destinationOverride,proto3" json:"destination_override,omitempty"`
UserLevel uint32 `protobuf:"varint,4,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
ProtocolReplacement ProtocolReplacement `protobuf:"varint,5,opt,name=protocol_replacement,json=protocolReplacement,proto3,enum=v2ray.core.proxy.freedom.ProtocolReplacement" json:"protocol_replacement,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_freedom_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{1}
}
func (x *Config) GetDomainStrategy() Config_DomainStrategy {
if x != nil {
return x.DomainStrategy
}
return Config_AS_IS
}
// Deprecated: Marked as deprecated in proxy/freedom/config.proto.
func (x *Config) GetTimeout() uint32 {
if x != nil {
return x.Timeout
}
return 0
}
func (x *Config) GetDestinationOverride() *DestinationOverride {
if x != nil {
return x.DestinationOverride
}
return nil
}
func (x *Config) GetUserLevel() uint32 {
if x != nil {
return x.UserLevel
}
return 0
}
func (x *Config) GetProtocolReplacement() ProtocolReplacement {
if x != nil {
return x.ProtocolReplacement
}
return ProtocolReplacement_IDENTITY
}
type SimplifiedConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
DestinationOverride *DestinationOverride `protobuf:"bytes,3,opt,name=destination_override,json=destinationOverride,proto3" json:"destination_override,omitempty"`
ProtocolReplacement ProtocolReplacement `protobuf:"varint,5,opt,name=protocol_replacement,json=protocolReplacement,proto3,enum=v2ray.core.proxy.freedom.ProtocolReplacement" json:"protocol_replacement,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SimplifiedConfig) Reset() {
*x = SimplifiedConfig{}
mi := &file_proxy_freedom_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SimplifiedConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SimplifiedConfig) ProtoMessage() {}
func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_freedom_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead.
func (*SimplifiedConfig) Descriptor() ([]byte, []int) {
return file_proxy_freedom_config_proto_rawDescGZIP(), []int{2}
}
func (x *SimplifiedConfig) GetDestinationOverride() *DestinationOverride {
if x != nil {
return x.DestinationOverride
}
return nil
}
func (x *SimplifiedConfig) GetProtocolReplacement() ProtocolReplacement {
if x != nil {
return x.ProtocolReplacement
}
return ProtocolReplacement_IDENTITY
}
var File_proxy_freedom_config_proto protoreflect.FileDescriptor
const file_proxy_freedom_config_proto_rawDesc = "" +
"\n" +
"\x1aproxy/freedom/config.proto\x12\x18v2ray.core.proxy.freedom\x1a!common/protocol/server_spec.proto\x1a common/protoext/extensions.proto\"Y\n" +
"\x13DestinationOverride\x12B\n" +
"\x06server\x18\x01 \x01(\v2*.v2ray.core.common.protocol.ServerEndpointR\x06server\"\xa6\x03\n" +
"\x06Config\x12X\n" +
"\x0fdomain_strategy\x18\x01 \x01(\x0e2/.v2ray.core.proxy.freedom.Config.DomainStrategyR\x0edomainStrategy\x12\x1c\n" +
"\atimeout\x18\x02 \x01(\rB\x02\x18\x01R\atimeout\x12`\n" +
"\x14destination_override\x18\x03 \x01(\v2-.v2ray.core.proxy.freedom.DestinationOverrideR\x13destinationOverride\x12\x1d\n" +
"\n" +
"user_level\x18\x04 \x01(\rR\tuserLevel\x12`\n" +
"\x14protocol_replacement\x18\x05 \x01(\x0e2-.v2ray.core.proxy.freedom.ProtocolReplacementR\x13protocolReplacement\"A\n" +
"\x0eDomainStrategy\x12\t\n" +
"\x05AS_IS\x10\x00\x12\n" +
"\n" +
"\x06USE_IP\x10\x01\x12\v\n" +
"\aUSE_IP4\x10\x02\x12\v\n" +
"\aUSE_IP6\x10\x03\"\xef\x01\n" +
"\x10SimplifiedConfig\x12`\n" +
"\x14destination_override\x18\x03 \x01(\v2-.v2ray.core.proxy.freedom.DestinationOverrideR\x13destinationOverride\x12`\n" +
"\x14protocol_replacement\x18\x05 \x01(\x0e2-.v2ray.core.proxy.freedom.ProtocolReplacementR\x13protocolReplacement:\x17\x82\xb5\x18\x13\n" +
"\boutbound\x12\afreedom*A\n" +
"\x13ProtocolReplacement\x12\f\n" +
"\bIDENTITY\x10\x00\x12\r\n" +
"\tFORCE_TCP\x10\x01\x12\r\n" +
"\tFORCE_UDP\x10\x02Bi\n" +
"\x1ccom.v2ray.core.proxy.freedomP\x01Z,github.com/v2fly/v2ray-core/v5/proxy/freedom\xaa\x02\x18V2Ray.Core.Proxy.Freedomb\x06proto3"
var (
file_proxy_freedom_config_proto_rawDescOnce sync.Once
file_proxy_freedom_config_proto_rawDescData []byte
)
func file_proxy_freedom_config_proto_rawDescGZIP() []byte {
file_proxy_freedom_config_proto_rawDescOnce.Do(func() {
file_proxy_freedom_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_freedom_config_proto_rawDesc), len(file_proxy_freedom_config_proto_rawDesc)))
})
return file_proxy_freedom_config_proto_rawDescData
}
var file_proxy_freedom_config_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
var file_proxy_freedom_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_proxy_freedom_config_proto_goTypes = []any{
(ProtocolReplacement)(0), // 0: v2ray.core.proxy.freedom.ProtocolReplacement
(Config_DomainStrategy)(0), // 1: v2ray.core.proxy.freedom.Config.DomainStrategy
(*DestinationOverride)(nil), // 2: v2ray.core.proxy.freedom.DestinationOverride
(*Config)(nil), // 3: v2ray.core.proxy.freedom.Config
(*SimplifiedConfig)(nil), // 4: v2ray.core.proxy.freedom.SimplifiedConfig
(*protocol.ServerEndpoint)(nil), // 5: v2ray.core.common.protocol.ServerEndpoint
}
var file_proxy_freedom_config_proto_depIdxs = []int32{
5, // 0: v2ray.core.proxy.freedom.DestinationOverride.server:type_name -> v2ray.core.common.protocol.ServerEndpoint
1, // 1: v2ray.core.proxy.freedom.Config.domain_strategy:type_name -> v2ray.core.proxy.freedom.Config.DomainStrategy
2, // 2: v2ray.core.proxy.freedom.Config.destination_override:type_name -> v2ray.core.proxy.freedom.DestinationOverride
0, // 3: v2ray.core.proxy.freedom.Config.protocol_replacement:type_name -> v2ray.core.proxy.freedom.ProtocolReplacement
2, // 4: v2ray.core.proxy.freedom.SimplifiedConfig.destination_override:type_name -> v2ray.core.proxy.freedom.DestinationOverride
0, // 5: v2ray.core.proxy.freedom.SimplifiedConfig.protocol_replacement:type_name -> v2ray.core.proxy.freedom.ProtocolReplacement
6, // [6:6] is the sub-list for method output_type
6, // [6:6] is the sub-list for method input_type
6, // [6:6] is the sub-list for extension type_name
6, // [6:6] is the sub-list for extension extendee
0, // [0:6] is the sub-list for field type_name
}
func init() { file_proxy_freedom_config_proto_init() }
func file_proxy_freedom_config_proto_init() {
if File_proxy_freedom_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_freedom_config_proto_rawDesc), len(file_proxy_freedom_config_proto_rawDesc)),
NumEnums: 2,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_freedom_config_proto_goTypes,
DependencyIndexes: file_proxy_freedom_config_proto_depIdxs,
EnumInfos: file_proxy_freedom_config_proto_enumTypes,
MessageInfos: file_proxy_freedom_config_proto_msgTypes,
}.Build()
File_proxy_freedom_config_proto = out.File
file_proxy_freedom_config_proto_goTypes = nil
file_proxy_freedom_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/freedom/freedom.go | proxy/freedom/freedom.go | package freedom
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/dice"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/dns"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
h := new(Handler)
if err := core.RequireFeatures(ctx, func(pm policy.Manager, d dns.Client) error {
return h.Init(config.(*Config), pm, d)
}); err != nil {
return nil, err
}
return h, nil
}))
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedServer := config.(*SimplifiedConfig)
_ = simplifiedServer
fullConfig := &Config{
DestinationOverride: simplifiedServer.DestinationOverride,
ProtocolReplacement: simplifiedServer.ProtocolReplacement,
}
return common.CreateObject(ctx, fullConfig)
}))
}
// Handler handles Freedom connections.
type Handler struct {
policyManager policy.Manager
dns dns.Client
config *Config
}
// Init initializes the Handler with necessary parameters.
func (h *Handler) Init(config *Config, pm policy.Manager, d dns.Client) error {
h.config = config
h.policyManager = pm
h.dns = d
return nil
}
func (h *Handler) policy() policy.Session {
p := h.policyManager.ForLevel(h.config.UserLevel)
if h.config.Timeout > 0 && h.config.UserLevel == 0 {
p.Timeouts.ConnectionIdle = time.Duration(h.config.Timeout) * time.Second
}
return p
}
func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address {
ips, err := dns.LookupIPWithOption(h.dns, domain, dns.IPOption{
IPv4Enable: h.config.DomainStrategy == Config_USE_IP || h.config.DomainStrategy == Config_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()),
IPv6Enable: h.config.DomainStrategy == Config_USE_IP || h.config.DomainStrategy == Config_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()),
FakeEnable: false,
})
if err != nil {
newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
}
if len(ips) == 0 {
return nil
}
return net.IPAddress(ips[dice.Roll(len(ips))])
}
func isValidAddress(addr *net.IPOrDomain) bool {
if addr == nil {
return false
}
a := addr.AsAddress()
return a != net.AnyIP
}
// Process implements proxy.Outbound.
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified.")
}
destination := outbound.Target
if h.config.DestinationOverride != nil {
server := h.config.DestinationOverride.Server
if isValidAddress(server.Address) {
destination.Address = server.Address.AsAddress()
}
if server.Port != 0 {
destination.Port = net.Port(server.Port)
}
}
if h.config.ProtocolReplacement != ProtocolReplacement_IDENTITY {
if h.config.ProtocolReplacement == ProtocolReplacement_FORCE_TCP {
destination.Network = net.Network_TCP
}
if h.config.ProtocolReplacement == ProtocolReplacement_FORCE_UDP {
destination.Network = net.Network_UDP
}
}
if h.config.useIP() {
outbound.Resolver = func(ctx context.Context, domain string) net.Address {
return h.resolveIP(ctx, domain, dialer.Address())
}
}
newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
input := link.Reader
output := link.Writer
var conn internet.Connection
err := retry.ExponentialBackoff(5, 100).On(func() error {
rawConn, err := dialer.Dial(ctx, destination)
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
return newError("failed to open connection to ", destination).Base(err)
}
defer conn.Close()
plcy := h.policy()
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
requestDone := func() error {
defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
var writer buf.Writer
if destination.Network == net.Network_TCP {
writer = buf.NewWriter(conn)
} else {
writer = &buf.SequentialWriter{Writer: conn}
}
if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to process request").Base(err)
}
return nil
}
responseDone := func() error {
defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
var reader buf.Reader
if destination.Network == net.Network_TCP && h.config.ProtocolReplacement == ProtocolReplacement_IDENTITY {
reader = buf.NewReader(conn)
} else {
reader = buf.NewPacketReader(conn)
}
if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil {
return newError("failed to process response").Base(err)
}
return nil
}
if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vlite/vlite.go | proxy/vlite/vlite.go | // Package vlite contains the integration code for VLite protocol variety
//
// VLite is currently an experimental protocol, its stability is not guaranteed.
package vlite
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vlite/outbound/errors.generated.go | proxy/vlite/outbound/errors.generated.go | package outbound
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vlite/outbound/outbound.go | proxy/vlite/outbound/outbound.go | package outbound
import (
"context"
"fmt"
"sync"
"time"
"github.com/mustafaturan/bus"
"github.com/xiaokangwang/VLite/ass/udpconn2tun"
"github.com/xiaokangwang/VLite/interfaces"
"github.com/xiaokangwang/VLite/interfaces/ibus"
vltransport "github.com/xiaokangwang/VLite/transport"
udpsctpserver "github.com/xiaokangwang/VLite/transport/packetsctp/sctprelay"
"github.com/xiaokangwang/VLite/transport/packetuni/puniClient"
"github.com/xiaokangwang/VLite/transport/udp/udpClient"
"github.com/xiaokangwang/VLite/transport/udp/udpuni/udpunic"
"github.com/xiaokangwang/VLite/transport/uni/uniclient"
client2 "github.com/xiaokangwang/VLite/workers/client"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/environment"
"github.com/v2fly/v2ray-core/v5/common/environment/envctx"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
func NewUDPOutboundHandler(ctx context.Context, config *UDPProtocolConfig) (*Handler, error) {
proxyEnvironment := envctx.EnvironmentFromContext(ctx).(environment.ProxyEnvironment)
statusInstance, err := createStatusFromConfig(config)
if err != nil {
return nil, newError("unable to initialize vlite").Base(err)
}
proxyEnvironment.TransientStorage().Put(ctx, "status", statusInstance)
return &Handler{ctx: ctx}, nil
}
type Handler struct {
ctx context.Context
}
// Process implements proxy.Outbound.Process().
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
proxyEnvironment := envctx.EnvironmentFromContext(h.ctx).(environment.ProxyEnvironment)
statusInstanceIfce, err := proxyEnvironment.TransientStorage().Get(ctx, "status")
if err != nil {
return newError("uninitialized handler").Base(err)
}
statusInstance := statusInstanceIfce.(*status)
err = h.ensureStarted(statusInstance)
if err != nil {
return newError("unable to initialize").Base(err)
}
connid := session.IDFromContext(ctx)
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified")
}
destination := outbound.Target
packetConnOut := statusInstance.connAdp.DialUDP(net.UDPAddr{Port: int(connid % 65535)})
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, time.Second*600)
if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil {
requestDone := func() error {
return udp.CopyPacketConn(packetConnOut, packetConn, udp.UpdateActivity(timer))
}
responseDone := func() error {
return udp.CopyPacketConn(packetConn, packetConnOut, udp.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
}
return newError("unrecognized connection")
}
func (h *Handler) ensureStarted(s *status) error {
s.access.Lock()
defer s.access.Unlock()
if s.TunnelRxFromTun == nil {
err := enableInterface(s)
if err != nil {
return err
}
}
return nil
}
type status struct {
ctx context.Context
password []byte
msgbus *bus.Bus
udpdialer vltransport.UnderlayTransportDialer
puni *puniClient.PacketUniClient
udprelay *udpsctpserver.PacketSCTPRelay
udpserver *client2.UDPClientContext
TunnelTxToTun chan interfaces.UDPPacket
TunnelRxFromTun chan interfaces.UDPPacket
connAdp *udpconn2tun.UDPConn2Tun
config UDPProtocolConfig
access sync.Mutex
}
func createStatusFromConfig(config *UDPProtocolConfig) (*status, error) { //nolint:unparam
s := &status{password: []byte(config.Password)}
ctx := context.Background()
s.msgbus = ibus.NewMessageBus()
ctx = context.WithValue(ctx, interfaces.ExtraOptionsMessageBus, s.msgbus) //nolint:revive,staticcheck
ctx = context.WithValue(ctx, interfaces.ExtraOptionsDisableAutoQuitForClient, true) //nolint:revive,staticcheck
if config.EnableFec {
ctx = context.WithValue(ctx, interfaces.ExtraOptionsUDPFECEnabled, true) //nolint:revive,staticcheck
}
if config.ScramblePacket {
ctx = context.WithValue(ctx, interfaces.ExtraOptionsUDPShouldMask, true) //nolint:revive,staticcheck
}
ctx = context.WithValue(ctx, interfaces.ExtraOptionsUDPMask, string(s.password)) //nolint:revive,staticcheck
if config.HandshakeMaskingPaddingSize != 0 {
ctxv := &interfaces.ExtraOptionsUsePacketArmorValue{PacketArmorPaddingTo: int(config.HandshakeMaskingPaddingSize), UsePacketArmor: true}
ctx = context.WithValue(ctx, interfaces.ExtraOptionsUsePacketArmor, ctxv) //nolint:revive,staticcheck
}
destinationString := fmt.Sprintf("%v:%v", config.Address.AsAddress().String(), config.Port)
s.udpdialer = udpClient.NewUdpClient(destinationString, ctx)
if config.EnableStabilization {
s.udpdialer = udpunic.NewUdpUniClient(string(s.password), ctx, s.udpdialer)
s.udpdialer = uniclient.NewUnifiedConnectionClient(s.udpdialer, ctx)
}
s.ctx = ctx
return s, nil
}
func enableInterface(s *status) error {
conn, err, connctx := s.udpdialer.Connect(s.ctx)
if err != nil {
return newError("unable to connect to remote").Base(err)
}
C_C2STraffic := make(chan client2.UDPClientTxToServerTraffic, 8) //nolint:revive,stylecheck
C_C2SDataTraffic := make(chan client2.UDPClientTxToServerDataTraffic, 8) //nolint:revive,stylecheck
C_S2CTraffic := make(chan client2.UDPClientRxFromServerTraffic, 8) //nolint:revive,stylecheck
C_C2STraffic2 := make(chan interfaces.TrafficWithChannelTag, 8) //nolint:revive,stylecheck
C_C2SDataTraffic2 := make(chan interfaces.TrafficWithChannelTag, 8) //nolint:revive,stylecheck
C_S2CTraffic2 := make(chan interfaces.TrafficWithChannelTag, 8) //nolint:revive,stylecheck
go func(ctx context.Context) {
for {
select {
case data := <-C_C2STraffic:
C_C2STraffic2 <- interfaces.TrafficWithChannelTag(data)
case <-ctx.Done():
return
}
}
}(connctx)
go func(ctx context.Context) {
for {
select {
case data := <-C_C2SDataTraffic:
C_C2SDataTraffic2 <- interfaces.TrafficWithChannelTag(data)
case <-ctx.Done():
return
}
}
}(connctx)
go func(ctx context.Context) {
for {
select {
case data := <-C_S2CTraffic2:
C_S2CTraffic <- client2.UDPClientRxFromServerTraffic(data)
case <-ctx.Done():
return
}
}
}(connctx)
TunnelTxToTun := make(chan interfaces.UDPPacket)
TunnelRxFromTun := make(chan interfaces.UDPPacket)
s.TunnelTxToTun = TunnelTxToTun
s.TunnelRxFromTun = TunnelRxFromTun
if s.config.EnableStabilization && s.config.EnableRenegotiation {
s.puni = puniClient.NewPacketUniClient(C_C2STraffic2, C_C2SDataTraffic2, C_S2CTraffic2, s.password, connctx)
s.puni.OnAutoCarrier(conn, connctx)
s.udpserver = client2.UDPClient(connctx, C_C2STraffic, C_C2SDataTraffic, C_S2CTraffic, TunnelTxToTun, TunnelRxFromTun, s.puni)
} else {
s.udprelay = udpsctpserver.NewPacketRelayClient(conn, C_C2STraffic2, C_C2SDataTraffic2, C_S2CTraffic2, s.password, connctx)
s.udpserver = client2.UDPClient(connctx, C_C2STraffic, C_C2SDataTraffic, C_S2CTraffic, TunnelTxToTun, TunnelRxFromTun, s.udprelay)
}
s.ctx = connctx
s.connAdp = udpconn2tun.NewUDPConn2Tun(TunnelTxToTun, TunnelRxFromTun)
return nil
}
func init() {
common.Must(common.RegisterConfig((*UDPProtocolConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewUDPOutboundHandler(ctx, config.(*UDPProtocolConfig))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vlite/outbound/config.pb.go | proxy/vlite/outbound/config.pb.go | package outbound
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type UDPProtocolConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`
Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"`
ScramblePacket bool `protobuf:"varint,4,opt,name=scramble_packet,json=scramblePacket,proto3" json:"scramble_packet,omitempty"`
EnableFec bool `protobuf:"varint,5,opt,name=enable_fec,json=enableFec,proto3" json:"enable_fec,omitempty"`
EnableStabilization bool `protobuf:"varint,6,opt,name=enable_stabilization,json=enableStabilization,proto3" json:"enable_stabilization,omitempty"`
EnableRenegotiation bool `protobuf:"varint,7,opt,name=enable_renegotiation,json=enableRenegotiation,proto3" json:"enable_renegotiation,omitempty"`
HandshakeMaskingPaddingSize uint32 `protobuf:"varint,8,opt,name=handshake_masking_padding_size,json=handshakeMaskingPaddingSize,proto3" json:"handshake_masking_padding_size,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UDPProtocolConfig) Reset() {
*x = UDPProtocolConfig{}
mi := &file_proxy_vlite_outbound_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UDPProtocolConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UDPProtocolConfig) ProtoMessage() {}
func (x *UDPProtocolConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vlite_outbound_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UDPProtocolConfig.ProtoReflect.Descriptor instead.
func (*UDPProtocolConfig) Descriptor() ([]byte, []int) {
return file_proxy_vlite_outbound_config_proto_rawDescGZIP(), []int{0}
}
func (x *UDPProtocolConfig) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *UDPProtocolConfig) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
func (x *UDPProtocolConfig) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
func (x *UDPProtocolConfig) GetScramblePacket() bool {
if x != nil {
return x.ScramblePacket
}
return false
}
func (x *UDPProtocolConfig) GetEnableFec() bool {
if x != nil {
return x.EnableFec
}
return false
}
func (x *UDPProtocolConfig) GetEnableStabilization() bool {
if x != nil {
return x.EnableStabilization
}
return false
}
func (x *UDPProtocolConfig) GetEnableRenegotiation() bool {
if x != nil {
return x.EnableRenegotiation
}
return false
}
func (x *UDPProtocolConfig) GetHandshakeMaskingPaddingSize() uint32 {
if x != nil {
return x.HandshakeMaskingPaddingSize
}
return 0
}
var File_proxy_vlite_outbound_config_proto protoreflect.FileDescriptor
const file_proxy_vlite_outbound_config_proto_rawDesc = "" +
"\n" +
"!proxy/vlite/outbound/config.proto\x12\x1fv2ray.core.proxy.vlite.outbound\x1a\x18common/net/address.proto\x1a common/protoext/extensions.proto\"\x8b\x03\n" +
"\x11UDPProtocolConfig\x12;\n" +
"\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" +
"\x04port\x18\x02 \x01(\rR\x04port\x12\x1a\n" +
"\bpassword\x18\x03 \x01(\tR\bpassword\x12'\n" +
"\x0fscramble_packet\x18\x04 \x01(\bR\x0escramblePacket\x12\x1d\n" +
"\n" +
"enable_fec\x18\x05 \x01(\bR\tenableFec\x121\n" +
"\x14enable_stabilization\x18\x06 \x01(\bR\x13enableStabilization\x121\n" +
"\x14enable_renegotiation\x18\a \x01(\bR\x13enableRenegotiation\x12C\n" +
"\x1ehandshake_masking_padding_size\x18\b \x01(\rR\x1bhandshakeMaskingPaddingSize:\x16\x82\xb5\x18\x12\n" +
"\boutbound\x12\x06vliteuB~\n" +
"#com.v2ray.core.proxy.vlite.outboundP\x01Z3github.com/v2fly/v2ray-core/v5/proxy/vlite/outbound\xaa\x02\x1fV2Ray.Core.Proxy.Vlite.Outboundb\x06proto3"
var (
file_proxy_vlite_outbound_config_proto_rawDescOnce sync.Once
file_proxy_vlite_outbound_config_proto_rawDescData []byte
)
func file_proxy_vlite_outbound_config_proto_rawDescGZIP() []byte {
file_proxy_vlite_outbound_config_proto_rawDescOnce.Do(func() {
file_proxy_vlite_outbound_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vlite_outbound_config_proto_rawDesc), len(file_proxy_vlite_outbound_config_proto_rawDesc)))
})
return file_proxy_vlite_outbound_config_proto_rawDescData
}
var file_proxy_vlite_outbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_proxy_vlite_outbound_config_proto_goTypes = []any{
(*UDPProtocolConfig)(nil), // 0: v2ray.core.proxy.vlite.outbound.UDPProtocolConfig
(*net.IPOrDomain)(nil), // 1: v2ray.core.common.net.IPOrDomain
}
var file_proxy_vlite_outbound_config_proto_depIdxs = []int32{
1, // 0: v2ray.core.proxy.vlite.outbound.UDPProtocolConfig.address:type_name -> v2ray.core.common.net.IPOrDomain
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_proxy_vlite_outbound_config_proto_init() }
func file_proxy_vlite_outbound_config_proto_init() {
if File_proxy_vlite_outbound_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vlite_outbound_config_proto_rawDesc), len(file_proxy_vlite_outbound_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_vlite_outbound_config_proto_goTypes,
DependencyIndexes: file_proxy_vlite_outbound_config_proto_depIdxs,
MessageInfos: file_proxy_vlite_outbound_config_proto_msgTypes,
}.Build()
File_proxy_vlite_outbound_config_proto = out.File
file_proxy_vlite_outbound_config_proto_goTypes = nil
file_proxy_vlite_outbound_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vlite/inbound/inbound.go | proxy/vlite/inbound/inbound.go | package inbound
import (
"context"
"io"
gonet "net"
"strconv"
"sync"
"github.com/mustafaturan/bus"
"github.com/xiaokangwang/VLite/interfaces"
"github.com/xiaokangwang/VLite/interfaces/ibus"
"github.com/xiaokangwang/VLite/transport"
udpsctpserver "github.com/xiaokangwang/VLite/transport/packetsctp/sctprelay"
"github.com/xiaokangwang/VLite/transport/packetuni/puniServer"
"github.com/xiaokangwang/VLite/transport/udp/udpServer"
"github.com/xiaokangwang/VLite/transport/udp/udpuni/udpunis"
"github.com/xiaokangwang/VLite/transport/uni/uniserver"
"github.com/xiaokangwang/VLite/workers/server"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/environment"
"github.com/v2fly/v2ray-core/v5/common/environment/envctx"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal/done"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
func NewUDPInboundHandler(ctx context.Context, config *UDPProtocolConfig) (*Handler, error) {
proxyEnvironment := envctx.EnvironmentFromContext(ctx).(environment.ProxyEnvironment)
statusInstance, err := createStatusFromConfig(config)
if err != nil {
return nil, newError("unable to initialize vlite").Base(err)
}
proxyEnvironment.TransientStorage().Put(ctx, "status", statusInstance)
return &Handler{ctx: ctx}, nil
}
type Handler struct {
ctx context.Context
}
func (h *Handler) Network() []net.Network {
list := []net.Network{net.Network_UDP}
return list
}
type status struct {
config *UDPProtocolConfig
password []byte
msgbus *bus.Bus
ctx context.Context
transport transport.UnderlayTransportListener
access sync.Mutex
}
func (s *status) RelayStream(conn io.ReadWriteCloser, ctx context.Context) { //nolint:revive
}
func (s *status) Connection(conn gonet.Conn, connctx context.Context) context.Context { //nolint:revive,stylecheck
S_S2CTraffic := make(chan server.UDPServerTxToClientTraffic, 8) //nolint:revive,stylecheck
S_S2CDataTraffic := make(chan server.UDPServerTxToClientDataTraffic, 8) //nolint:revive,stylecheck
S_C2STraffic := make(chan server.UDPServerRxFromClientTraffic, 8) //nolint:revive,stylecheck
S_S2CTraffic2 := make(chan interfaces.TrafficWithChannelTag, 8) //nolint:revive,stylecheck
S_S2CDataTraffic2 := make(chan interfaces.TrafficWithChannelTag, 8) //nolint:revive,stylecheck
S_C2STraffic2 := make(chan interfaces.TrafficWithChannelTag, 8) //nolint:revive,stylecheck
go func(ctx context.Context) {
for {
select {
case data := <-S_S2CTraffic:
S_S2CTraffic2 <- interfaces.TrafficWithChannelTag(data)
case <-ctx.Done():
return
}
}
}(connctx)
go func(ctx context.Context) {
for {
select {
case data := <-S_S2CDataTraffic:
S_S2CDataTraffic2 <- interfaces.TrafficWithChannelTag(data)
case <-ctx.Done():
return
}
}
}(connctx)
go func(ctx context.Context) {
for {
select {
case data := <-S_C2STraffic2:
S_C2STraffic <- server.UDPServerRxFromClientTraffic(data)
case <-ctx.Done():
return
}
}
}(connctx)
if !s.config.EnableStabilization || !s.config.EnableRenegotiation {
relay := udpsctpserver.NewPacketRelayServer(conn, S_S2CTraffic2, S_S2CDataTraffic2, S_C2STraffic2, s, s.password, connctx)
udpserver := server.UDPServer(connctx, S_S2CTraffic, S_S2CDataTraffic, S_C2STraffic, relay)
_ = udpserver
} else {
relay := puniServer.NewPacketUniServer(S_S2CTraffic2, S_S2CDataTraffic2, S_C2STraffic2, s, s.password, connctx)
relay.OnAutoCarrier(conn, connctx)
udpserver := server.UDPServer(connctx, S_S2CTraffic, S_S2CDataTraffic, S_C2STraffic, relay)
_ = udpserver
}
return connctx
}
func createStatusFromConfig(config *UDPProtocolConfig) (*status, error) { //nolint:unparam
s := &status{ctx: context.Background(), config: config}
s.password = []byte(config.Password)
s.msgbus = ibus.NewMessageBus()
s.ctx = context.WithValue(s.ctx, interfaces.ExtraOptionsMessageBus, s.msgbus) //nolint:revive,staticcheck
if config.ScramblePacket {
s.ctx = context.WithValue(s.ctx, interfaces.ExtraOptionsUDPShouldMask, true) //nolint:revive,staticcheck
}
if s.config.EnableFec {
s.ctx = context.WithValue(s.ctx, interfaces.ExtraOptionsUDPFECEnabled, true) //nolint:revive,staticcheck
}
s.ctx = context.WithValue(s.ctx, interfaces.ExtraOptionsUDPMask, string(s.password)) //nolint:revive,staticcheck
if config.HandshakeMaskingPaddingSize != 0 {
ctxv := &interfaces.ExtraOptionsUsePacketArmorValue{PacketArmorPaddingTo: int(config.HandshakeMaskingPaddingSize), UsePacketArmor: true}
s.ctx = context.WithValue(s.ctx, interfaces.ExtraOptionsUsePacketArmor, ctxv) //nolint:revive,staticcheck
}
return s, nil
}
func enableInterface(s *status) error { //nolint: unparam
s.transport = s
if s.config.EnableStabilization {
s.transport = uniserver.NewUnifiedConnectionTransportHub(s, s.ctx)
}
if s.config.EnableStabilization {
s.transport = udpunis.NewUdpUniServer(string(s.password), s.ctx, s.transport)
}
return nil
}
func (h *Handler) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
proxyEnvironment := envctx.EnvironmentFromContext(h.ctx).(environment.ProxyEnvironment)
statusInstanceIfce, err := proxyEnvironment.TransientStorage().Get(ctx, "status")
if err != nil {
return newError("uninitialized handler").Base(err)
}
statusInstance := statusInstanceIfce.(*status)
err = h.ensureStarted(statusInstance)
if err != nil {
return newError("unable to initialize").Base(err)
}
finish := done.New()
conn = newUDPConnAdaptor(conn, finish)
var initialData [1600]byte
c, err := conn.Read(initialData[:])
if err != nil {
return newError("unable to read initial data").Base(err)
}
connID := session.IDFromContext(ctx)
vconn, connctx := udpServer.PrepareIncomingUDPConnection(conn, statusInstance.ctx, initialData[:c], strconv.FormatInt(int64(connID), 10))
connctx = statusInstance.transport.Connection(vconn, connctx)
if connctx == nil {
return newError("invalid connection discarded")
}
<-finish.Wait()
return nil
}
func (h *Handler) ensureStarted(s *status) error {
s.access.Lock()
defer s.access.Unlock()
if s.transport == nil {
err := enableInterface(s)
if err != nil {
return err
}
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*UDPProtocolConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewUDPInboundHandler(ctx, config.(*UDPProtocolConfig))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vlite/inbound/errors.generated.go | proxy/vlite/inbound/errors.generated.go | package inbound
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vlite/inbound/connAdp.go | proxy/vlite/inbound/connAdp.go | package inbound
import (
"io"
"net"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/signal/done"
)
func newUDPConnAdaptor(conn net.Conn, done *done.Instance) net.Conn {
return &udpConnAdp{
Conn: conn,
reader: buf.NewPacketReader(conn),
cachedMultiBuffer: nil,
finished: done,
}
}
type udpConnAdp struct {
net.Conn
reader buf.Reader
cachedMultiBuffer buf.MultiBuffer
finished *done.Instance
}
func (u *udpConnAdp) Read(p []byte) (n int, err error) {
if u.cachedMultiBuffer.IsEmpty() {
u.cachedMultiBuffer, err = u.reader.ReadMultiBuffer()
if err != nil {
return 0, newError("unable to read from connection").Base(err)
}
}
var buffer *buf.Buffer
u.cachedMultiBuffer, buffer = buf.SplitFirst(u.cachedMultiBuffer)
defer buffer.Release()
n = copy(p, buffer.Bytes())
if n != int(buffer.Len()) {
return 0, io.ErrShortBuffer
}
return n, nil
}
func (u *udpConnAdp) Close() error {
u.finished.Close()
return u.Conn.Close()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vlite/inbound/config.pb.go | proxy/vlite/inbound/config.pb.go | package inbound
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type UDPProtocolConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"`
ScramblePacket bool `protobuf:"varint,4,opt,name=scramble_packet,json=scramblePacket,proto3" json:"scramble_packet,omitempty"`
EnableFec bool `protobuf:"varint,5,opt,name=enable_fec,json=enableFec,proto3" json:"enable_fec,omitempty"`
EnableStabilization bool `protobuf:"varint,6,opt,name=enable_stabilization,json=enableStabilization,proto3" json:"enable_stabilization,omitempty"`
EnableRenegotiation bool `protobuf:"varint,7,opt,name=enable_renegotiation,json=enableRenegotiation,proto3" json:"enable_renegotiation,omitempty"`
HandshakeMaskingPaddingSize uint32 `protobuf:"varint,8,opt,name=handshake_masking_padding_size,json=handshakeMaskingPaddingSize,proto3" json:"handshake_masking_padding_size,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UDPProtocolConfig) Reset() {
*x = UDPProtocolConfig{}
mi := &file_proxy_vlite_inbound_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UDPProtocolConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UDPProtocolConfig) ProtoMessage() {}
func (x *UDPProtocolConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vlite_inbound_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UDPProtocolConfig.ProtoReflect.Descriptor instead.
func (*UDPProtocolConfig) Descriptor() ([]byte, []int) {
return file_proxy_vlite_inbound_config_proto_rawDescGZIP(), []int{0}
}
func (x *UDPProtocolConfig) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
func (x *UDPProtocolConfig) GetScramblePacket() bool {
if x != nil {
return x.ScramblePacket
}
return false
}
func (x *UDPProtocolConfig) GetEnableFec() bool {
if x != nil {
return x.EnableFec
}
return false
}
func (x *UDPProtocolConfig) GetEnableStabilization() bool {
if x != nil {
return x.EnableStabilization
}
return false
}
func (x *UDPProtocolConfig) GetEnableRenegotiation() bool {
if x != nil {
return x.EnableRenegotiation
}
return false
}
func (x *UDPProtocolConfig) GetHandshakeMaskingPaddingSize() uint32 {
if x != nil {
return x.HandshakeMaskingPaddingSize
}
return 0
}
var File_proxy_vlite_inbound_config_proto protoreflect.FileDescriptor
const file_proxy_vlite_inbound_config_proto_rawDesc = "" +
"\n" +
" proxy/vlite/inbound/config.proto\x12\x1ev2ray.core.proxy.vlite.inbound\x1a common/protoext/extensions.proto\"\xb9\x02\n" +
"\x11UDPProtocolConfig\x12\x1a\n" +
"\bpassword\x18\x03 \x01(\tR\bpassword\x12'\n" +
"\x0fscramble_packet\x18\x04 \x01(\bR\x0escramblePacket\x12\x1d\n" +
"\n" +
"enable_fec\x18\x05 \x01(\bR\tenableFec\x121\n" +
"\x14enable_stabilization\x18\x06 \x01(\bR\x13enableStabilization\x121\n" +
"\x14enable_renegotiation\x18\a \x01(\bR\x13enableRenegotiation\x12C\n" +
"\x1ehandshake_masking_padding_size\x18\b \x01(\rR\x1bhandshakeMaskingPaddingSize:\x15\x82\xb5\x18\x11\n" +
"\ainbound\x12\x06vliteuB{\n" +
"\"com.v2ray.core.proxy.vlite.inboundP\x01Z2github.com/v2fly/v2ray-core/v5/proxy/vlite/inbound\xaa\x02\x1eV2Ray.Core.Proxy.Vlite.Inboundb\x06proto3"
var (
file_proxy_vlite_inbound_config_proto_rawDescOnce sync.Once
file_proxy_vlite_inbound_config_proto_rawDescData []byte
)
func file_proxy_vlite_inbound_config_proto_rawDescGZIP() []byte {
file_proxy_vlite_inbound_config_proto_rawDescOnce.Do(func() {
file_proxy_vlite_inbound_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vlite_inbound_config_proto_rawDesc), len(file_proxy_vlite_inbound_config_proto_rawDesc)))
})
return file_proxy_vlite_inbound_config_proto_rawDescData
}
var file_proxy_vlite_inbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_proxy_vlite_inbound_config_proto_goTypes = []any{
(*UDPProtocolConfig)(nil), // 0: v2ray.core.proxy.vlite.inbound.UDPProtocolConfig
}
var file_proxy_vlite_inbound_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_proxy_vlite_inbound_config_proto_init() }
func file_proxy_vlite_inbound_config_proto_init() {
if File_proxy_vlite_inbound_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vlite_inbound_config_proto_rawDesc), len(file_proxy_vlite_inbound_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_vlite_inbound_config_proto_goTypes,
DependencyIndexes: file_proxy_vlite_inbound_config_proto_depIdxs,
MessageInfos: file_proxy_vlite_inbound_config_proto_msgTypes,
}.Build()
File_proxy_vlite_inbound_config_proto = out.File
file_proxy_vlite_inbound_config_proto_goTypes = nil
file_proxy_vlite_inbound_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/errors.generated.go | proxy/vless/errors.generated.go | package vless
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/vless.go | proxy/vless/vless.go | // Package vless contains the implementation of VLess protocol and transportation.
//
// VLess contains both inbound and outbound connections. VLess inbound is usually used on servers
// together with 'freedom' to talk to final destination, while VLess outbound is usually used on
// clients with 'socks' for proxying.
package vless
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/validator.go | proxy/vless/validator.go | package vless
import (
"strings"
"sync"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/uuid"
)
// Validator stores valid VLESS users.
type Validator struct {
// Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
email sync.Map
users sync.Map
}
// Add a VLESS user, Email must be empty or unique.
func (v *Validator) Add(u *protocol.MemoryUser) error {
if u.Email != "" {
_, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
if loaded {
return newError("User ", u.Email, " already exists.")
}
}
v.users.Store(u.Account.(*MemoryAccount).ID.UUID(), u)
return nil
}
// Del a VLESS user with a non-empty Email.
func (v *Validator) Del(e string) error {
if e == "" {
return newError("Email must not be empty.")
}
le := strings.ToLower(e)
u, _ := v.email.Load(le)
if u == nil {
return newError("User ", e, " not found.")
}
v.email.Delete(le)
v.users.Delete(u.(*protocol.MemoryUser).Account.(*MemoryAccount).ID.UUID())
return nil
}
// Get a VLESS user with UUID, nil if user doesn't exist.
func (v *Validator) Get(id uuid.UUID) *protocol.MemoryUser {
u, _ := v.users.Load(id)
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/account.pb.go | proxy/vless/account.pb.go | package vless
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Account struct {
state protoimpl.MessageState `protogen:"open.v1"`
// ID of the account, in the form of a UUID, e.g., "66ad4540-b58c-4ad2-9926-ea63445a9b57".
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
// Flow settings.
Flow string `protobuf:"bytes,2,opt,name=flow,proto3" json:"flow,omitempty"`
// Encryption settings. Only applies to client side, and only accepts "none" for now.
Encryption string `protobuf:"bytes,3,opt,name=encryption,proto3" json:"encryption,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Account) Reset() {
*x = Account{}
mi := &file_proxy_vless_account_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Account) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Account) ProtoMessage() {}
func (x *Account) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vless_account_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Account.ProtoReflect.Descriptor instead.
func (*Account) Descriptor() ([]byte, []int) {
return file_proxy_vless_account_proto_rawDescGZIP(), []int{0}
}
func (x *Account) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *Account) GetFlow() string {
if x != nil {
return x.Flow
}
return ""
}
func (x *Account) GetEncryption() string {
if x != nil {
return x.Encryption
}
return ""
}
var File_proxy_vless_account_proto protoreflect.FileDescriptor
const file_proxy_vless_account_proto_rawDesc = "" +
"\n" +
"\x19proxy/vless/account.proto\x12\x16v2ray.core.proxy.vless\"M\n" +
"\aAccount\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
"\x04flow\x18\x02 \x01(\tR\x04flow\x12\x1e\n" +
"\n" +
"encryption\x18\x03 \x01(\tR\n" +
"encryptionBc\n" +
"\x1acom.v2ray.core.proxy.vlessP\x01Z*github.com/v2fly/v2ray-core/v5/proxy/vless\xaa\x02\x16V2Ray.Core.Proxy.Vlessb\x06proto3"
var (
file_proxy_vless_account_proto_rawDescOnce sync.Once
file_proxy_vless_account_proto_rawDescData []byte
)
func file_proxy_vless_account_proto_rawDescGZIP() []byte {
file_proxy_vless_account_proto_rawDescOnce.Do(func() {
file_proxy_vless_account_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vless_account_proto_rawDesc), len(file_proxy_vless_account_proto_rawDesc)))
})
return file_proxy_vless_account_proto_rawDescData
}
var file_proxy_vless_account_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_proxy_vless_account_proto_goTypes = []any{
(*Account)(nil), // 0: v2ray.core.proxy.vless.Account
}
var file_proxy_vless_account_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_proxy_vless_account_proto_init() }
func file_proxy_vless_account_proto_init() {
if File_proxy_vless_account_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vless_account_proto_rawDesc), len(file_proxy_vless_account_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_vless_account_proto_goTypes,
DependencyIndexes: file_proxy_vless_account_proto_depIdxs,
MessageInfos: file_proxy_vless_account_proto_msgTypes,
}.Build()
File_proxy_vless_account_proto = out.File
file_proxy_vless_account_proto_goTypes = nil
file_proxy_vless_account_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/account.go | proxy/vless/account.go | //go:build !confonly
// +build !confonly
package vless
import (
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/uuid"
)
// AsAccount implements protocol.Account.AsAccount().
func (a *Account) AsAccount() (protocol.Account, error) {
id, err := uuid.ParseString(a.Id)
if err != nil {
return nil, newError("failed to parse ID").Base(err).AtError()
}
return &MemoryAccount{
ID: protocol.NewID(id),
Flow: a.Flow, // needs parser here?
Encryption: a.Encryption, // needs parser here?
}, nil
}
// MemoryAccount is an in-memory form of VLess account.
type MemoryAccount struct {
// ID of the account.
ID *protocol.ID
// Flow of the account.
Flow string
// Encryption of the account. Used for client connections, and only accepts "none" for now.
Encryption string
}
// Equals implements protocol.Account.Equals().
func (a *MemoryAccount) Equals(account protocol.Account) bool {
vlessAccount, ok := account.(*MemoryAccount)
if !ok {
return false
}
return a.ID.Equals(vlessAccount.ID)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/encoding/errors.generated.go | proxy/vless/encoding/errors.generated.go | package encoding
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/encoding/encoding_test.go | proxy/vless/encoding/encoding_test.go | package encoding_test
import (
"testing"
"github.com/google/go-cmp/cmp"
"google.golang.org/protobuf/testing/protocmp"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/vless"
. "github.com/v2fly/v2ray-core/v5/proxy/vless/encoding"
)
func toAccount(a *vless.Account) protocol.Account {
account, err := a.AsAccount()
common.Must(err)
return account
}
func TestRequestSerialization(t *testing.T) {
user := &protocol.MemoryUser{
Level: 0,
Email: "test@v2fly.org",
}
id := uuid.New()
account := &vless.Account{
Id: id.String(),
}
user.Account = toAccount(account)
expectedRequest := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandTCP,
Address: net.DomainAddress("www.v2fly.org"),
Port: net.Port(443),
}
expectedAddons := &Addons{}
buffer := buf.StackNew()
common.Must(EncodeRequestHeader(&buffer, expectedRequest, expectedAddons))
Validator := new(vless.Validator)
Validator.Add(user)
actualRequest, actualAddons, _, err := DecodeRequestHeader(false, nil, &buffer, Validator)
common.Must(err)
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
if r := cmp.Diff(actualAddons, expectedAddons, protocmp.Transform()); r != "" {
t.Error(r)
}
}
func TestInvalidRequest(t *testing.T) {
user := &protocol.MemoryUser{
Level: 0,
Email: "test@v2fly.org",
}
id := uuid.New()
account := &vless.Account{
Id: id.String(),
}
user.Account = toAccount(account)
expectedRequest := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommand(100),
Address: net.DomainAddress("www.v2fly.org"),
Port: net.Port(443),
}
expectedAddons := &Addons{}
buffer := buf.StackNew()
common.Must(EncodeRequestHeader(&buffer, expectedRequest, expectedAddons))
Validator := new(vless.Validator)
Validator.Add(user)
_, _, _, err := DecodeRequestHeader(false, nil, &buffer, Validator)
if err == nil {
t.Error("nil error")
}
}
func TestMuxRequest(t *testing.T) {
user := &protocol.MemoryUser{
Level: 0,
Email: "test@v2fly.org",
}
id := uuid.New()
account := &vless.Account{
Id: id.String(),
}
user.Account = toAccount(account)
expectedRequest := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandMux,
Address: net.DomainAddress("v1.mux.cool"),
}
expectedAddons := &Addons{}
buffer := buf.StackNew()
common.Must(EncodeRequestHeader(&buffer, expectedRequest, expectedAddons))
Validator := new(vless.Validator)
Validator.Add(user)
actualRequest, actualAddons, _, err := DecodeRequestHeader(false, nil, &buffer, Validator)
common.Must(err)
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
if r := cmp.Diff(actualAddons, expectedAddons, protocmp.Transform()); r != "" {
t.Error(r)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/encoding/addons.go | proxy/vless/encoding/addons.go | //go:build !confonly
// +build !confonly
package encoding
import (
"io"
"google.golang.org/protobuf/proto"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/errors"
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
// EncodeHeaderAddons Add addons byte to the header
func EncodeHeaderAddons(buffer *buf.Buffer, addons *Addons) error {
if err := buffer.WriteByte(0); err != nil {
return newError("failed to write addons protobuf length").Base(err)
}
return nil
}
func DecodeHeaderAddons(buffer *buf.Buffer, reader io.Reader) (*Addons, error) {
addons := new(Addons)
buffer.Clear()
if _, err := buffer.ReadFullFrom(reader, 1); err != nil {
return nil, newError("failed to read addons protobuf length").Base(err)
}
if length := int32(buffer.Byte(0)); length != 0 {
buffer.Clear()
if _, err := buffer.ReadFullFrom(reader, length); err != nil {
return nil, newError("failed to read addons protobuf value").Base(err)
}
if err := proto.Unmarshal(buffer.Bytes(), addons); err != nil {
return nil, newError("failed to unmarshal addons protobuf value").Base(err)
}
}
return addons, nil
}
// EncodeBodyAddons returns a Writer that auto-encrypt content written by caller.
func EncodeBodyAddons(writer io.Writer, request *protocol.RequestHeader, addons *Addons) buf.Writer {
if request.Command == protocol.RequestCommandUDP {
return NewMultiLengthPacketWriter(writer.(buf.Writer))
}
return buf.NewWriter(writer)
}
// DecodeBodyAddons returns a Reader from which caller can fetch decrypted body.
func DecodeBodyAddons(reader io.Reader, request *protocol.RequestHeader, addons *Addons) buf.Reader {
if request.Command == protocol.RequestCommandUDP {
return NewLengthPacketReader(reader)
}
return buf.NewReader(reader)
}
func NewMultiLengthPacketWriter(writer buf.Writer) *MultiLengthPacketWriter {
return &MultiLengthPacketWriter{
Writer: writer,
}
}
type MultiLengthPacketWriter struct {
buf.Writer
}
func (w *MultiLengthPacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
defer buf.ReleaseMulti(mb)
if len(mb)+1 > 64*1024*1024 {
return errors.New("value too large")
}
sliceSize := len(mb) + 1
mb2Write := make(buf.MultiBuffer, 0, sliceSize)
for _, b := range mb {
length := b.Len()
if length == 0 || length+2 > buf.Size {
continue
}
eb := buf.New()
if err := eb.WriteByte(byte(length >> 8)); err != nil {
eb.Release()
continue
}
if err := eb.WriteByte(byte(length)); err != nil {
eb.Release()
continue
}
if _, err := eb.Write(b.Bytes()); err != nil {
eb.Release()
continue
}
mb2Write = append(mb2Write, eb)
}
if mb2Write.IsEmpty() {
return nil
}
return w.Writer.WriteMultiBuffer(mb2Write)
}
type LengthPacketWriter struct {
io.Writer
cache []byte
}
func (w *LengthPacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
length := mb.Len() // none of mb is nil
if length == 0 {
return nil
}
defer func() {
w.cache = w.cache[:0]
}()
w.cache = append(w.cache, byte(length>>8), byte(length))
for i, b := range mb {
w.cache = append(w.cache, b.Bytes()...)
b.Release()
mb[i] = nil
}
if _, err := w.Write(w.cache); err != nil {
return newError("failed to write a packet").Base(err)
}
return nil
}
func NewLengthPacketReader(reader io.Reader) *LengthPacketReader {
return &LengthPacketReader{
Reader: reader,
cache: make([]byte, 2),
}
}
type LengthPacketReader struct {
io.Reader
cache []byte
}
func (r *LengthPacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
if _, err := io.ReadFull(r.Reader, r.cache); err != nil { // maybe EOF
return nil, newError("failed to read packet length").Base(err)
}
length := int32(r.cache[0])<<8 | int32(r.cache[1])
mb := make(buf.MultiBuffer, 0, length/buf.Size+1)
for length > 0 {
size := length
if size > buf.Size {
size = buf.Size
}
length -= size
b := buf.New()
if _, err := b.ReadFullFrom(r.Reader, size); err != nil {
return nil, newError("failed to read packet payload").Base(err)
}
mb = append(mb, b)
}
return mb, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/encoding/encoding.go | proxy/vless/encoding/encoding.go | package encoding
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"io"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/proxy/vless"
)
const (
Version = byte(0)
)
var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv4), net.AddressFamilyIPv4),
protocol.AddressFamilyByte(byte(protocol.AddressTypeDomain), net.AddressFamilyDomain),
protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv6), net.AddressFamilyIPv6),
protocol.PortThenAddress(),
)
// EncodeRequestHeader writes encoded request header into the given writer.
func EncodeRequestHeader(writer io.Writer, request *protocol.RequestHeader, requestAddons *Addons) error {
buffer := buf.StackNew()
defer buffer.Release()
if err := buffer.WriteByte(request.Version); err != nil {
return newError("failed to write request version").Base(err)
}
if _, err := buffer.Write(request.User.Account.(*vless.MemoryAccount).ID.Bytes()); err != nil {
return newError("failed to write request user id").Base(err)
}
if err := EncodeHeaderAddons(&buffer, requestAddons); err != nil {
return newError("failed to encode request header addons").Base(err)
}
if err := buffer.WriteByte(byte(request.Command)); err != nil {
return newError("failed to write request command").Base(err)
}
if request.Command != protocol.RequestCommandMux {
if err := addrParser.WriteAddressPort(&buffer, request.Address, request.Port); err != nil {
return newError("failed to write request address and port").Base(err)
}
}
if _, err := writer.Write(buffer.Bytes()); err != nil {
return newError("failed to write request header").Base(err)
}
return nil
}
// DecodeRequestHeader decodes and returns (if successful) a RequestHeader from an input stream.
func DecodeRequestHeader(isfb bool, first *buf.Buffer, reader io.Reader, validator *vless.Validator) (*protocol.RequestHeader, *Addons, bool, error) {
buffer := buf.StackNew()
defer buffer.Release()
request := new(protocol.RequestHeader)
if isfb {
request.Version = first.Byte(0)
} else {
if _, err := buffer.ReadFullFrom(reader, 1); err != nil {
return nil, nil, false, newError("failed to read request version").Base(err)
}
request.Version = buffer.Byte(0)
}
switch request.Version {
case 0:
var id [16]byte
if isfb {
copy(id[:], first.BytesRange(1, 17))
} else {
buffer.Clear()
if _, err := buffer.ReadFullFrom(reader, 16); err != nil {
return nil, nil, false, newError("failed to read request user id").Base(err)
}
copy(id[:], buffer.Bytes())
}
if request.User = validator.Get(id); request.User == nil {
return nil, nil, isfb, newError("invalid request user id")
}
if isfb {
first.Advance(17)
}
requestAddons, err := DecodeHeaderAddons(&buffer, reader)
if err != nil {
return nil, nil, false, newError("failed to decode request header addons").Base(err)
}
buffer.Clear()
if _, err := buffer.ReadFullFrom(reader, 1); err != nil {
return nil, nil, false, newError("failed to read request command").Base(err)
}
request.Command = protocol.RequestCommand(buffer.Byte(0))
switch request.Command {
case protocol.RequestCommandMux:
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = 0
case protocol.RequestCommandTCP, protocol.RequestCommandUDP:
if addr, port, err := addrParser.ReadAddressPort(&buffer, reader); err == nil {
request.Address = addr
request.Port = port
}
}
if request.Address == nil {
return nil, nil, false, newError("invalid request address")
}
return request, requestAddons, false, nil
default:
return nil, nil, isfb, newError("invalid request version")
}
}
// EncodeResponseHeader writes encoded response header into the given writer.
func EncodeResponseHeader(writer io.Writer, request *protocol.RequestHeader, responseAddons *Addons) error {
buffer := buf.StackNew()
defer buffer.Release()
if err := buffer.WriteByte(request.Version); err != nil {
return newError("failed to write response version").Base(err)
}
if err := EncodeHeaderAddons(&buffer, responseAddons); err != nil {
return newError("failed to encode response header addons").Base(err)
}
if _, err := writer.Write(buffer.Bytes()); err != nil {
return newError("failed to write response header").Base(err)
}
return nil
}
// DecodeResponseHeader decodes and returns (if successful) a ResponseHeader from an input stream.
func DecodeResponseHeader(reader io.Reader, request *protocol.RequestHeader) (*Addons, error) {
buffer := buf.StackNew()
defer buffer.Release()
if _, err := buffer.ReadFullFrom(reader, 1); err != nil {
return nil, newError("failed to read response version").Base(err)
}
if buffer.Byte(0) != request.Version {
return nil, newError("unexpected response version. Expecting ", int(request.Version), " but actually ", int(buffer.Byte(0)))
}
responseAddons, err := DecodeHeaderAddons(&buffer, reader)
if err != nil {
return nil, newError("failed to decode response header addons").Base(err)
}
return responseAddons, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/encoding/addons.pb.go | proxy/vless/encoding/addons.pb.go | package encoding
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Addons struct {
state protoimpl.MessageState `protogen:"open.v1"`
Flow string `protobuf:"bytes,1,opt,name=Flow,proto3" json:"Flow,omitempty"`
Seed []byte `protobuf:"bytes,2,opt,name=Seed,proto3" json:"Seed,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Addons) Reset() {
*x = Addons{}
mi := &file_proxy_vless_encoding_addons_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Addons) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Addons) ProtoMessage() {}
func (x *Addons) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vless_encoding_addons_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Addons.ProtoReflect.Descriptor instead.
func (*Addons) Descriptor() ([]byte, []int) {
return file_proxy_vless_encoding_addons_proto_rawDescGZIP(), []int{0}
}
func (x *Addons) GetFlow() string {
if x != nil {
return x.Flow
}
return ""
}
func (x *Addons) GetSeed() []byte {
if x != nil {
return x.Seed
}
return nil
}
var File_proxy_vless_encoding_addons_proto protoreflect.FileDescriptor
const file_proxy_vless_encoding_addons_proto_rawDesc = "" +
"\n" +
"!proxy/vless/encoding/addons.proto\x12\x1fv2ray.core.proxy.vless.encoding\"0\n" +
"\x06Addons\x12\x12\n" +
"\x04Flow\x18\x01 \x01(\tR\x04Flow\x12\x12\n" +
"\x04Seed\x18\x02 \x01(\fR\x04SeedB~\n" +
"#com.v2ray.core.proxy.vless.encodingP\x01Z3github.com/v2fly/v2ray-core/v5/proxy/vless/encoding\xaa\x02\x1fV2Ray.Core.Proxy.Vless.Encodingb\x06proto3"
var (
file_proxy_vless_encoding_addons_proto_rawDescOnce sync.Once
file_proxy_vless_encoding_addons_proto_rawDescData []byte
)
func file_proxy_vless_encoding_addons_proto_rawDescGZIP() []byte {
file_proxy_vless_encoding_addons_proto_rawDescOnce.Do(func() {
file_proxy_vless_encoding_addons_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vless_encoding_addons_proto_rawDesc), len(file_proxy_vless_encoding_addons_proto_rawDesc)))
})
return file_proxy_vless_encoding_addons_proto_rawDescData
}
var file_proxy_vless_encoding_addons_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_proxy_vless_encoding_addons_proto_goTypes = []any{
(*Addons)(nil), // 0: v2ray.core.proxy.vless.encoding.Addons
}
var file_proxy_vless_encoding_addons_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_proxy_vless_encoding_addons_proto_init() }
func file_proxy_vless_encoding_addons_proto_init() {
if File_proxy_vless_encoding_addons_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vless_encoding_addons_proto_rawDesc), len(file_proxy_vless_encoding_addons_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_vless_encoding_addons_proto_goTypes,
DependencyIndexes: file_proxy_vless_encoding_addons_proto_depIdxs,
MessageInfos: file_proxy_vless_encoding_addons_proto_msgTypes,
}.Build()
File_proxy_vless_encoding_addons_proto = out.File
file_proxy_vless_encoding_addons_proto_goTypes = nil
file_proxy_vless_encoding_addons_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/outbound/errors.generated.go | proxy/vless/outbound/errors.generated.go | package outbound
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/outbound/config.go | proxy/vless/outbound/config.go | package outbound
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/outbound/outbound.go | proxy/vless/outbound/outbound.go | package outbound
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/proxy"
"github.com/v2fly/v2ray-core/v5/proxy/vless"
"github.com/v2fly/v2ray-core/v5/proxy/vless/encoding"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedClient := config.(*SimplifiedConfig)
fullClient := &Config{Vnext: []*protocol.ServerEndpoint{
{
Address: simplifiedClient.Address,
Port: simplifiedClient.Port,
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vless.Account{Id: simplifiedClient.Uuid, Encryption: "none"}),
},
},
},
}}
return common.CreateObject(ctx, fullClient)
}))
}
// Handler is an outbound connection handler for VLess protocol.
type Handler struct {
serverList *protocol.ServerList
serverPicker protocol.ServerPicker
policyManager policy.Manager
}
// New creates a new VLess outbound handler.
func New(ctx context.Context, config *Config) (*Handler, error) {
serverList := protocol.NewServerList()
for _, rec := range config.Vnext {
s, err := protocol.NewServerSpecFromPB(rec)
if err != nil {
return nil, newError("failed to parse server spec").Base(err).AtError()
}
serverList.AddServer(s)
}
v := core.MustFromContext(ctx)
handler := &Handler{
serverList: serverList,
serverPicker: protocol.NewRoundRobinServerPicker(serverList),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}
return handler, nil
}
// Process implements proxy.Outbound.Process().
func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
var rec *protocol.ServerSpec
var conn internet.Connection
if err := retry.ExponentialBackoff(5, 200).On(func() error {
rec = h.serverPicker.PickServer()
var err error
conn, err = dialer.Dial(ctx, rec.Destination())
if err != nil {
return err
}
return nil
}); err != nil {
return newError("failed to find an available destination").Base(err).AtWarning()
}
defer conn.Close()
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified").AtError()
}
target := outbound.Target
newError("tunneling request to ", target, " via ", rec.Destination().NetAddr()).AtInfo().WriteToLog(session.ExportIDToError(ctx))
command := protocol.RequestCommandTCP
if target.Network == net.Network_UDP {
command = protocol.RequestCommandUDP
}
if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" {
command = protocol.RequestCommandMux
}
request := &protocol.RequestHeader{
Version: encoding.Version,
User: rec.PickUser(),
Command: command,
Address: target.Address,
Port: target.Port,
}
account := request.User.Account.(*vless.MemoryAccount)
requestAddons := &encoding.Addons{
Flow: account.Flow,
}
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
clientReader := link.Reader // .(*pipe.Reader)
clientWriter := link.Writer // .(*pipe.Writer)
postRequest := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil {
return newError("failed to encode request header").Base(err).AtWarning()
}
// default: serverWriter := bufferWriter
serverWriter := encoding.EncodeBodyAddons(bufferWriter, request, requestAddons)
if err := buf.CopyOnceTimeout(clientReader, serverWriter, proxy.FirstPayloadTimeout); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
return err // ...
}
// Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer
if err := bufferWriter.SetBuffered(false); err != nil {
return newError("failed to write A request payload").Base(err).AtWarning()
}
// from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBuffer
if err := buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transfer request payload").Base(err).AtInfo()
}
return nil
}
getResponse := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
responseAddons, err := encoding.DecodeResponseHeader(conn, request)
if err != nil {
return newError("failed to decode response header").Base(err).AtInfo()
}
// default: serverReader := buf.NewReader(conn)
serverReader := encoding.DecodeBodyAddons(conn, request, responseAddons)
// from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBuffer
if err := buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transfer response payload").Base(err).AtInfo()
}
return nil
}
if err := task.Run(ctx, postRequest, task.OnSuccess(getResponse, task.Close(clientWriter))); err != nil {
return newError("connection ends").Base(err).AtInfo()
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/outbound/config.pb.go | proxy/vless/outbound/config.pb.go | package outbound
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
protocol "github.com/v2fly/v2ray-core/v5/common/protocol"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Vnext []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=vnext,proto3" json:"vnext,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_vless_outbound_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vless_outbound_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_vless_outbound_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetVnext() []*protocol.ServerEndpoint {
if x != nil {
return x.Vnext
}
return nil
}
type SimplifiedConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`
Uuid string `protobuf:"bytes,3,opt,name=uuid,proto3" json:"uuid,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SimplifiedConfig) Reset() {
*x = SimplifiedConfig{}
mi := &file_proxy_vless_outbound_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SimplifiedConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SimplifiedConfig) ProtoMessage() {}
func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vless_outbound_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead.
func (*SimplifiedConfig) Descriptor() ([]byte, []int) {
return file_proxy_vless_outbound_config_proto_rawDescGZIP(), []int{1}
}
func (x *SimplifiedConfig) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *SimplifiedConfig) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
func (x *SimplifiedConfig) GetUuid() string {
if x != nil {
return x.Uuid
}
return ""
}
var File_proxy_vless_outbound_config_proto protoreflect.FileDescriptor
const file_proxy_vless_outbound_config_proto_rawDesc = "" +
"\n" +
"!proxy/vless/outbound/config.proto\x12\x1fv2ray.core.proxy.vless.outbound\x1a!common/protocol/server_spec.proto\x1a\x18common/net/address.proto\x1a common/protoext/extensions.proto\"J\n" +
"\x06Config\x12@\n" +
"\x05vnext\x18\x01 \x03(\v2*.v2ray.core.common.protocol.ServerEndpointR\x05vnext\"\x8e\x01\n" +
"\x10SimplifiedConfig\x12;\n" +
"\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" +
"\x04port\x18\x02 \x01(\rR\x04port\x12\x12\n" +
"\x04uuid\x18\x03 \x01(\tR\x04uuid:\x15\x82\xb5\x18\x11\n" +
"\boutbound\x12\x05vlessB~\n" +
"#com.v2ray.core.proxy.vless.outboundP\x01Z3github.com/v2fly/v2ray-core/v5/proxy/vless/outbound\xaa\x02\x1fV2Ray.Core.Proxy.Vless.Outboundb\x06proto3"
var (
file_proxy_vless_outbound_config_proto_rawDescOnce sync.Once
file_proxy_vless_outbound_config_proto_rawDescData []byte
)
func file_proxy_vless_outbound_config_proto_rawDescGZIP() []byte {
file_proxy_vless_outbound_config_proto_rawDescOnce.Do(func() {
file_proxy_vless_outbound_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vless_outbound_config_proto_rawDesc), len(file_proxy_vless_outbound_config_proto_rawDesc)))
})
return file_proxy_vless_outbound_config_proto_rawDescData
}
var file_proxy_vless_outbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_proxy_vless_outbound_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.proxy.vless.outbound.Config
(*SimplifiedConfig)(nil), // 1: v2ray.core.proxy.vless.outbound.SimplifiedConfig
(*protocol.ServerEndpoint)(nil), // 2: v2ray.core.common.protocol.ServerEndpoint
(*net.IPOrDomain)(nil), // 3: v2ray.core.common.net.IPOrDomain
}
var file_proxy_vless_outbound_config_proto_depIdxs = []int32{
2, // 0: v2ray.core.proxy.vless.outbound.Config.vnext:type_name -> v2ray.core.common.protocol.ServerEndpoint
3, // 1: v2ray.core.proxy.vless.outbound.SimplifiedConfig.address:type_name -> v2ray.core.common.net.IPOrDomain
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_proxy_vless_outbound_config_proto_init() }
func file_proxy_vless_outbound_config_proto_init() {
if File_proxy_vless_outbound_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vless_outbound_config_proto_rawDesc), len(file_proxy_vless_outbound_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_vless_outbound_config_proto_goTypes,
DependencyIndexes: file_proxy_vless_outbound_config_proto_depIdxs,
MessageInfos: file_proxy_vless_outbound_config_proto_msgTypes,
}.Build()
File_proxy_vless_outbound_config_proto = out.File
file_proxy_vless_outbound_config_proto_goTypes = nil
file_proxy_vless_outbound_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/inbound/inbound.go | proxy/vless/inbound/inbound.go | package inbound
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"io"
"strconv"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/errors"
"github.com/v2fly/v2ray-core/v5/common/log"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/dns"
feature_inbound "github.com/v2fly/v2ray-core/v5/features/inbound"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/proxy/vless"
"github.com/v2fly/v2ray-core/v5/proxy/vless/encoding"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/tls"
)
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
var dc dns.Client
if err := core.RequireFeatures(ctx, func(d dns.Client) error {
dc = d
return nil
}); err != nil {
return nil, err
}
return New(ctx, config.(*Config), dc)
}))
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedServer := config.(*SimplifiedConfig)
fullConfig := &Config{
Clients: func() (users []*protocol.User) {
for _, v := range simplifiedServer.Users {
account := &vless.Account{Id: v}
users = append(users, &protocol.User{
Account: serial.ToTypedMessage(account),
})
}
return
}(),
Decryption: "none",
}
return common.CreateObject(ctx, fullConfig)
}))
}
// Handler is an inbound connection handler that handles messages in VLess protocol.
type Handler struct {
inboundHandlerManager feature_inbound.Manager
policyManager policy.Manager
validator *vless.Validator
dns dns.Client
fallbacks map[string]map[string]*Fallback // or nil
// regexps map[string]*regexp.Regexp // or nil
}
// New creates a new VLess inbound handler.
func New(ctx context.Context, config *Config, dc dns.Client) (*Handler, error) {
v := core.MustFromContext(ctx)
handler := &Handler{
inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
validator: new(vless.Validator),
dns: dc,
}
for _, user := range config.Clients {
u, err := user.ToMemoryUser()
if err != nil {
return nil, newError("failed to get VLESS user").Base(err).AtError()
}
if err := handler.AddUser(ctx, u); err != nil {
return nil, newError("failed to initiate user").Base(err).AtError()
}
}
if config.Fallbacks != nil {
handler.fallbacks = make(map[string]map[string]*Fallback)
// handler.regexps = make(map[string]*regexp.Regexp)
for _, fb := range config.Fallbacks {
if handler.fallbacks[fb.Alpn] == nil {
handler.fallbacks[fb.Alpn] = make(map[string]*Fallback)
}
handler.fallbacks[fb.Alpn][fb.Path] = fb
/*
if fb.Path != "" {
if r, err := regexp.Compile(fb.Path); err != nil {
return nil, newError("invalid path regexp").Base(err).AtError()
} else {
handler.regexps[fb.Path] = r
}
}
*/
}
if handler.fallbacks[""] != nil {
for alpn, pfb := range handler.fallbacks {
if alpn != "" { // && alpn != "h2" {
for path, fb := range handler.fallbacks[""] {
if pfb[path] == nil {
pfb[path] = fb
}
}
}
}
}
}
return handler, nil
}
// Close implements common.Closable.Close().
func (h *Handler) Close() error {
return errors.Combine(common.Close(h.validator))
}
// AddUser implements proxy.UserManager.AddUser().
func (h *Handler) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
return h.validator.Add(u)
}
// RemoveUser implements proxy.UserManager.RemoveUser().
func (h *Handler) RemoveUser(ctx context.Context, e string) error {
return h.validator.Del(e)
}
// Network implements proxy.Inbound.Network().
func (*Handler) Network() []net.Network {
return []net.Network{net.Network_TCP, net.Network_UNIX}
}
// Process implements proxy.Inbound.Process().
func (h *Handler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher routing.Dispatcher) error {
sid := session.ExportIDToError(ctx)
iConn := connection
statConn, ok := iConn.(*internet.StatCouterConnection)
if ok {
iConn = statConn.Connection
}
sessionPolicy := h.policyManager.ForLevel(0)
if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
return newError("unable to set read deadline").Base(err).AtWarning()
}
first := buf.New()
defer first.Release()
firstLen, _ := first.ReadFrom(connection)
newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid)
reader := &buf.BufferedReader{
Reader: buf.NewReader(connection),
Buffer: buf.MultiBuffer{first},
}
var request *protocol.RequestHeader
var requestAddons *encoding.Addons
var err error
apfb := h.fallbacks
isfb := apfb != nil
if isfb && firstLen < 18 {
err = newError("fallback directly")
} else {
request, requestAddons, isfb, err = encoding.DecodeRequestHeader(isfb, first, reader, h.validator)
}
if err != nil {
if isfb {
if err := connection.SetReadDeadline(time.Time{}); err != nil {
newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
}
newError("fallback starts").Base(err).AtInfo().WriteToLog(sid)
alpn := ""
if len(apfb) > 1 || apfb[""] == nil {
if tlsConn, ok := iConn.(*tls.Conn); ok {
alpn = tlsConn.ConnectionState().NegotiatedProtocol
newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
}
if apfb[alpn] == nil {
alpn = ""
}
}
pfb := apfb[alpn]
if pfb == nil {
return newError(`failed to find the default "alpn" config`).AtWarning()
}
path := ""
if len(pfb) > 1 || pfb[""] == nil {
/*
if lines := bytes.Split(firstBytes, []byte{'\r', '\n'}); len(lines) > 1 {
if s := bytes.Split(lines[0], []byte{' '}); len(s) == 3 {
if len(s[0]) < 8 && len(s[1]) > 0 && len(s[2]) == 8 {
newError("realPath = " + string(s[1])).AtInfo().WriteToLog(sid)
for _, fb := range pfb {
if fb.Path != "" && h.regexps[fb.Path].Match(s[1]) {
path = fb.Path
break
}
}
}
}
}
*/
if firstLen >= 18 && first.Byte(4) != '*' { // not h2c
firstBytes := first.Bytes()
for i := 4; i <= 8; i++ { // 5 -> 9
if firstBytes[i] == '/' && firstBytes[i-1] == ' ' {
search := len(firstBytes)
if search > 64 {
search = 64 // up to about 60
}
for j := i + 1; j < search; j++ {
k := firstBytes[j]
if k == '\r' || k == '\n' { // avoid logging \r or \n
break
}
if k == ' ' {
path = string(firstBytes[i:j])
newError("realPath = " + path).AtInfo().WriteToLog(sid)
if pfb[path] == nil {
path = ""
}
break
}
}
break
}
}
}
}
fb := pfb[path]
if fb == nil {
return newError(`failed to find the default "path" config`).AtWarning()
}
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
var conn net.Conn
if err := retry.ExponentialBackoff(5, 100).On(func() error {
var dialer net.Dialer
conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest)
if err != nil {
return err
}
return nil
}); err != nil {
return newError("failed to dial to " + fb.Dest).Base(err).AtWarning()
}
defer conn.Close()
serverReader := buf.NewReader(conn)
serverWriter := buf.NewWriter(conn)
postRequest := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
if fb.Xver != 0 {
remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String())
if err != nil {
return err
}
localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String())
if err != nil {
return err
}
ipv4 := true
for i := 0; i < len(remoteAddr); i++ {
if remoteAddr[i] == ':' {
ipv4 = false
break
}
}
pro := buf.New()
defer pro.Release()
switch fb.Xver {
case 1:
if ipv4 {
pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
} else {
pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n"))
}
case 2:
pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A\x21")) // signature + v2 + PROXY
if ipv4 {
pro.Write([]byte("\x11\x00\x0C")) // AF_INET + STREAM + 12 bytes
pro.Write(net.ParseIP(remoteAddr).To4())
pro.Write(net.ParseIP(localAddr).To4())
} else {
pro.Write([]byte("\x21\x00\x24")) // AF_INET6 + STREAM + 36 bytes
pro.Write(net.ParseIP(remoteAddr).To16())
pro.Write(net.ParseIP(localAddr).To16())
}
p1, _ := strconv.ParseUint(remotePort, 10, 16)
p2, _ := strconv.ParseUint(localPort, 10, 16)
pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)})
}
if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil {
return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
}
}
if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to fallback request payload").Base(err).AtInfo()
}
return nil
}
writer := buf.NewWriter(connection)
getResponse := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to deliver response payload").Base(err).AtInfo()
}
return nil
}
if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil {
common.Interrupt(serverReader)
common.Interrupt(serverWriter)
return newError("fallback ends").Base(err).AtInfo()
}
return nil
}
if errors.Cause(err) != io.EOF {
log.Record(&log.AccessMessage{
From: connection.RemoteAddr(),
To: "",
Status: log.AccessRejected,
Reason: err,
})
err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo()
}
return err
}
if err := connection.SetReadDeadline(time.Time{}); err != nil {
newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
}
newError("received request for ", request.Destination()).AtInfo().WriteToLog(sid)
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
}
inbound.User = request.User
responseAddons := &encoding.Addons{}
if request.Command != protocol.RequestCommandMux {
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: connection.RemoteAddr(),
To: request.Destination(),
Status: log.AccessAccepted,
Reason: "",
Email: request.User.Email,
})
}
sessionPolicy = h.policyManager.ForLevel(request.User.Level)
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
link, err := dispatcher.Dispatch(ctx, request.Destination())
if err != nil {
return newError("failed to dispatch request to ", request.Destination()).Base(err).AtWarning()
}
serverReader := link.Reader // .(*pipe.Reader)
serverWriter := link.Writer // .(*pipe.Writer)
postRequest := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
// default: clientReader := reader
clientReader := encoding.DecodeBodyAddons(reader, request, requestAddons)
// from clientReader.ReadMultiBuffer to serverWriter.WriteMultiBuffer
if err := buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transfer request payload").Base(err).AtInfo()
}
return nil
}
getResponse := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection))
if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil {
return newError("failed to encode response header").Base(err).AtWarning()
}
// default: clientWriter := bufferWriter
clientWriter := encoding.EncodeBodyAddons(bufferWriter, request, responseAddons)
{
multiBuffer, err := serverReader.ReadMultiBuffer()
if err != nil {
return err // ...
}
if err := clientWriter.WriteMultiBuffer(multiBuffer); err != nil {
return err // ...
}
}
// Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer
if err := bufferWriter.SetBuffered(false); err != nil {
return newError("failed to write A response payload").Base(err).AtWarning()
}
// from serverReader.ReadMultiBuffer to clientWriter.WriteMultiBuffer
if err := buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transfer response payload").Base(err).AtInfo()
}
return nil
}
if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), getResponse); err != nil {
common.Interrupt(serverReader)
common.Interrupt(serverWriter)
return newError("connection ends").Base(err).AtInfo()
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/inbound/errors.generated.go | proxy/vless/inbound/errors.generated.go | package inbound
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/inbound/config.go | proxy/vless/inbound/config.go | package inbound
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vless/inbound/config.pb.go | proxy/vless/inbound/config.pb.go | package inbound
import (
protocol "github.com/v2fly/v2ray-core/v5/common/protocol"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Fallback struct {
state protoimpl.MessageState `protogen:"open.v1"`
Alpn string `protobuf:"bytes,1,opt,name=alpn,proto3" json:"alpn,omitempty"`
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"`
Dest string `protobuf:"bytes,4,opt,name=dest,proto3" json:"dest,omitempty"`
Xver uint64 `protobuf:"varint,5,opt,name=xver,proto3" json:"xver,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Fallback) Reset() {
*x = Fallback{}
mi := &file_proxy_vless_inbound_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Fallback) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Fallback) ProtoMessage() {}
func (x *Fallback) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vless_inbound_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Fallback.ProtoReflect.Descriptor instead.
func (*Fallback) Descriptor() ([]byte, []int) {
return file_proxy_vless_inbound_config_proto_rawDescGZIP(), []int{0}
}
func (x *Fallback) GetAlpn() string {
if x != nil {
return x.Alpn
}
return ""
}
func (x *Fallback) GetPath() string {
if x != nil {
return x.Path
}
return ""
}
func (x *Fallback) GetType() string {
if x != nil {
return x.Type
}
return ""
}
func (x *Fallback) GetDest() string {
if x != nil {
return x.Dest
}
return ""
}
func (x *Fallback) GetXver() uint64 {
if x != nil {
return x.Xver
}
return 0
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Clients []*protocol.User `protobuf:"bytes,1,rep,name=clients,proto3" json:"clients,omitempty"`
// Decryption settings. Only applies to server side, and only accepts "none"
// for now.
Decryption string `protobuf:"bytes,2,opt,name=decryption,proto3" json:"decryption,omitempty"`
Fallbacks []*Fallback `protobuf:"bytes,3,rep,name=fallbacks,proto3" json:"fallbacks,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_vless_inbound_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vless_inbound_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_vless_inbound_config_proto_rawDescGZIP(), []int{1}
}
func (x *Config) GetClients() []*protocol.User {
if x != nil {
return x.Clients
}
return nil
}
func (x *Config) GetDecryption() string {
if x != nil {
return x.Decryption
}
return ""
}
func (x *Config) GetFallbacks() []*Fallback {
if x != nil {
return x.Fallbacks
}
return nil
}
type SimplifiedConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Users []string `protobuf:"bytes,1,rep,name=users,proto3" json:"users,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SimplifiedConfig) Reset() {
*x = SimplifiedConfig{}
mi := &file_proxy_vless_inbound_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SimplifiedConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SimplifiedConfig) ProtoMessage() {}
func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vless_inbound_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead.
func (*SimplifiedConfig) Descriptor() ([]byte, []int) {
return file_proxy_vless_inbound_config_proto_rawDescGZIP(), []int{2}
}
func (x *SimplifiedConfig) GetUsers() []string {
if x != nil {
return x.Users
}
return nil
}
var File_proxy_vless_inbound_config_proto protoreflect.FileDescriptor
const file_proxy_vless_inbound_config_proto_rawDesc = "" +
"\n" +
" proxy/vless/inbound/config.proto\x12\x1ev2ray.core.proxy.vless.inbound\x1a\x1acommon/protocol/user.proto\x1a common/protoext/extensions.proto\"n\n" +
"\bFallback\x12\x12\n" +
"\x04alpn\x18\x01 \x01(\tR\x04alpn\x12\x12\n" +
"\x04path\x18\x02 \x01(\tR\x04path\x12\x12\n" +
"\x04type\x18\x03 \x01(\tR\x04type\x12\x12\n" +
"\x04dest\x18\x04 \x01(\tR\x04dest\x12\x12\n" +
"\x04xver\x18\x05 \x01(\x04R\x04xver\"\xac\x01\n" +
"\x06Config\x12:\n" +
"\aclients\x18\x01 \x03(\v2 .v2ray.core.common.protocol.UserR\aclients\x12\x1e\n" +
"\n" +
"decryption\x18\x02 \x01(\tR\n" +
"decryption\x12F\n" +
"\tfallbacks\x18\x03 \x03(\v2(.v2ray.core.proxy.vless.inbound.FallbackR\tfallbacks\">\n" +
"\x10SimplifiedConfig\x12\x14\n" +
"\x05users\x18\x01 \x03(\tR\x05users:\x14\x82\xb5\x18\x10\n" +
"\ainbound\x12\x05vlessB{\n" +
"\"com.v2ray.core.proxy.vless.inboundP\x01Z2github.com/v2fly/v2ray-core/v5/proxy/vless/inbound\xaa\x02\x1eV2Ray.Core.Proxy.Vless.Inboundb\x06proto3"
var (
file_proxy_vless_inbound_config_proto_rawDescOnce sync.Once
file_proxy_vless_inbound_config_proto_rawDescData []byte
)
func file_proxy_vless_inbound_config_proto_rawDescGZIP() []byte {
file_proxy_vless_inbound_config_proto_rawDescOnce.Do(func() {
file_proxy_vless_inbound_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vless_inbound_config_proto_rawDesc), len(file_proxy_vless_inbound_config_proto_rawDesc)))
})
return file_proxy_vless_inbound_config_proto_rawDescData
}
var file_proxy_vless_inbound_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_proxy_vless_inbound_config_proto_goTypes = []any{
(*Fallback)(nil), // 0: v2ray.core.proxy.vless.inbound.Fallback
(*Config)(nil), // 1: v2ray.core.proxy.vless.inbound.Config
(*SimplifiedConfig)(nil), // 2: v2ray.core.proxy.vless.inbound.SimplifiedConfig
(*protocol.User)(nil), // 3: v2ray.core.common.protocol.User
}
var file_proxy_vless_inbound_config_proto_depIdxs = []int32{
3, // 0: v2ray.core.proxy.vless.inbound.Config.clients:type_name -> v2ray.core.common.protocol.User
0, // 1: v2ray.core.proxy.vless.inbound.Config.fallbacks:type_name -> v2ray.core.proxy.vless.inbound.Fallback
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_proxy_vless_inbound_config_proto_init() }
func file_proxy_vless_inbound_config_proto_init() {
if File_proxy_vless_inbound_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vless_inbound_config_proto_rawDesc), len(file_proxy_vless_inbound_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_vless_inbound_config_proto_goTypes,
DependencyIndexes: file_proxy_vless_inbound_config_proto_depIdxs,
MessageInfos: file_proxy_vless_inbound_config_proto_msgTypes,
}.Build()
File_proxy_vless_inbound_config_proto = out.File
file_proxy_vless_inbound_config_proto_goTypes = nil
file_proxy_vless_inbound_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/errors.generated.go | proxy/shadowsocks/errors.generated.go | package shadowsocks
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/client.go | proxy/shadowsocks/client.go | package shadowsocks
import (
"context"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/proxy"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
// Client is a inbound handler for Shadowsocks protocol
type Client struct {
serverPicker protocol.ServerPicker
policyManager policy.Manager
}
// NewClient create a new Shadowsocks client.
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
serverList := protocol.NewServerList()
for _, rec := range config.Server {
s, err := protocol.NewServerSpecFromPB(rec)
if err != nil {
return nil, newError("failed to parse server spec").Base(err)
}
serverList.AddServer(s)
}
if serverList.Size() == 0 {
return nil, newError("0 server")
}
v := core.MustFromContext(ctx)
client := &Client{
serverPicker: protocol.NewRoundRobinServerPicker(serverList),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}
return client, nil
}
// Process implements OutboundHandler.Process().
func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified")
}
destination := outbound.Target
network := destination.Network
var server *protocol.ServerSpec
var conn internet.Connection
err := retry.ExponentialBackoff(5, 100).On(func() error {
server = c.serverPicker.PickServer()
dest := server.Destination()
dest.Network = network
rawConn, err := dialer.Dial(ctx, dest)
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
return newError("failed to find an available destination").AtWarning().Base(err)
}
newError("tunneling request to ", destination, " via ", network, ":", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
defer conn.Close()
request := &protocol.RequestHeader{
Version: Version,
Address: destination.Address,
Port: destination.Port,
}
if destination.Network == net.Network_TCP {
request.Command = protocol.RequestCommandTCP
} else {
request.Command = protocol.RequestCommandUDP
}
user := server.PickUser()
_, ok := user.Account.(*MemoryAccount)
if !ok {
return newError("user account is not valid")
}
request.User = user
sessionPolicy := c.policyManager.ForLevel(user.Level)
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil {
requestDone := func() error {
protocolWriter := &UDPWriter{
Writer: conn,
Request: request,
}
return udp.CopyPacketConn(protocolWriter, packetConn, udp.UpdateActivity(timer))
}
responseDone := func() error {
protocolReader := &UDPReader{
Reader: conn,
User: user,
}
return udp.CopyPacketConn(packetConn, protocolReader, udp.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
if request.Command == protocol.RequestCommandTCP {
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
if err != nil {
return newError("failed to write request").Base(err)
}
if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, proxy.FirstPayloadTimeout); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
return newError("failed to write A request payload").Base(err).AtWarning()
}
if err := bufferedWriter.SetBuffered(false); err != nil {
return err
}
return buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer))
}
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
responseReader, err := ReadTCPResponse(user, conn)
if err != nil {
return err
}
return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
if request.Command == protocol.RequestCommandUDP {
writer := &buf.SequentialWriter{Writer: &UDPWriter{
Writer: conn,
Request: request,
}}
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport all UDP request").Base(err)
}
return nil
}
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
reader := &UDPReader{
Reader: conn,
User: user,
}
if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport all UDP response").Base(err)
}
return nil
}
responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewClient(ctx, config.(*ClientConfig))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/shadowsocks.go | proxy/shadowsocks/shadowsocks.go | // Package shadowsocks provides compatible functionality to Shadowsocks.
//
// Shadowsocks client and server are implemented as outbound and inbound respectively in V2Ray's term.
//
// R.I.P Shadowsocks
package shadowsocks
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/config.go | proxy/shadowsocks/config.go | package shadowsocks
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/sha1"
"io"
"strings"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/hkdf"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/antireplay"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/crypto"
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
// MemoryAccount is an account type converted from Account.
type MemoryAccount struct {
Cipher Cipher
Key []byte
replayFilter antireplay.GeneralizedReplayFilter
ReducedIVEntropy bool
}
// Equals implements protocol.Account.Equals().
func (a *MemoryAccount) Equals(another protocol.Account) bool {
if account, ok := another.(*MemoryAccount); ok {
return bytes.Equal(a.Key, account.Key)
}
return false
}
func (a *MemoryAccount) CheckIV(iv []byte) error {
if a.replayFilter == nil {
return nil
}
if a.replayFilter.Check(iv) {
return nil
}
return newError("IV is not unique")
}
func createAesGcm(key []byte) cipher.AEAD {
block, err := aes.NewCipher(key)
common.Must(err)
gcm, err := cipher.NewGCM(block)
common.Must(err)
return gcm
}
func createChaCha20Poly1305(key []byte) cipher.AEAD {
ChaChaPoly1305, err := chacha20poly1305.New(key)
common.Must(err)
return ChaChaPoly1305
}
func (a *Account) getCipher() (Cipher, error) {
switch a.CipherType {
case CipherType_AES_128_GCM:
return &AEADCipher{
KeyBytes: 16,
IVBytes: 16,
AEADAuthCreator: createAesGcm,
}, nil
case CipherType_AES_256_GCM:
return &AEADCipher{
KeyBytes: 32,
IVBytes: 32,
AEADAuthCreator: createAesGcm,
}, nil
case CipherType_CHACHA20_POLY1305:
return &AEADCipher{
KeyBytes: 32,
IVBytes: 32,
AEADAuthCreator: createChaCha20Poly1305,
}, nil
case CipherType_NONE:
return NoneCipher{}, nil
default:
return nil, newError("Unsupported cipher.")
}
}
// AsAccount implements protocol.AsAccount.
func (a *Account) AsAccount() (protocol.Account, error) {
Cipher, err := a.getCipher()
if err != nil {
return nil, newError("failed to get cipher").Base(err)
}
return &MemoryAccount{
Cipher: Cipher,
Key: passwordToCipherKey([]byte(a.Password), Cipher.KeySize()),
replayFilter: func() antireplay.GeneralizedReplayFilter {
if a.IvCheck {
return antireplay.NewBloomRing()
}
return nil
}(),
ReducedIVEntropy: a.ExperimentReducedIvHeadEntropy,
}, nil
}
// Cipher is an interface for all Shadowsocks ciphers.
type Cipher interface {
KeySize() int32
IVSize() int32
NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error)
NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error)
IsAEAD() bool
EncodePacket(key []byte, b *buf.Buffer) error
DecodePacket(key []byte, b *buf.Buffer) error
}
type AEADCipher struct {
KeyBytes int32
IVBytes int32
AEADAuthCreator func(key []byte) cipher.AEAD
}
func (*AEADCipher) IsAEAD() bool {
return true
}
func (c *AEADCipher) KeySize() int32 {
return c.KeyBytes
}
func (c *AEADCipher) IVSize() int32 {
return c.IVBytes
}
func (c *AEADCipher) createAuthenticator(key []byte, iv []byte) *crypto.AEADAuthenticator {
nonce := crypto.GenerateInitialAEADNonce()
subkey := make([]byte, c.KeyBytes)
hkdfSHA1(key, iv, subkey)
return &crypto.AEADAuthenticator{
AEAD: c.AEADAuthCreator(subkey),
NonceGenerator: nonce,
}
}
func (c *AEADCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
auth := c.createAuthenticator(key, iv)
return crypto.NewAuthenticationWriter(auth, &crypto.AEADChunkSizeParser{
Auth: auth,
}, writer, protocol.TransferTypeStream, nil), nil
}
func (c *AEADCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
auth := c.createAuthenticator(key, iv)
return crypto.NewAuthenticationReader(auth, &crypto.AEADChunkSizeParser{
Auth: auth,
}, reader, protocol.TransferTypeStream, nil), nil
}
func (c *AEADCipher) EncodePacket(key []byte, b *buf.Buffer) error {
ivLen := c.IVSize()
payloadLen := b.Len()
auth := c.createAuthenticator(key, b.BytesTo(ivLen))
b.Extend(int32(auth.Overhead()))
_, err := auth.Seal(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen))
return err
}
func (c *AEADCipher) DecodePacket(key []byte, b *buf.Buffer) error {
if b.Len() <= c.IVSize() {
return newError("insufficient data: ", b.Len())
}
ivLen := c.IVSize()
payloadLen := b.Len()
auth := c.createAuthenticator(key, b.BytesTo(ivLen))
bbb, err := auth.Open(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen))
if err != nil {
return err
}
b.Resize(ivLen, int32(len(bbb)))
return nil
}
type NoneCipher struct{}
func (NoneCipher) KeySize() int32 { return 0 }
func (NoneCipher) IVSize() int32 { return 0 }
func (NoneCipher) IsAEAD() bool {
return false
}
func (NoneCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
return buf.NewReader(reader), nil
}
func (NoneCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
return buf.NewWriter(writer), nil
}
func (NoneCipher) EncodePacket(key []byte, b *buf.Buffer) error {
return nil
}
func (NoneCipher) DecodePacket(key []byte, b *buf.Buffer) error {
return nil
}
func CipherFromString(c string) CipherType {
switch strings.ToLower(c) {
case "aes-128-gcm", "aes_128_gcm", "aead_aes_128_gcm":
return CipherType_AES_128_GCM
case "aes-256-gcm", "aes_256_gcm", "aead_aes_256_gcm":
return CipherType_AES_256_GCM
case "chacha20-poly1305", "chacha20_poly1305", "aead_chacha20_poly1305", "chacha20-ietf-poly1305":
return CipherType_CHACHA20_POLY1305
case "none", "plain":
return CipherType_NONE
default:
return CipherType_UNKNOWN
}
}
func passwordToCipherKey(password []byte, keySize int32) []byte {
key := make([]byte, 0, keySize)
md5Sum := md5.Sum(password)
key = append(key, md5Sum[:]...)
for int32(len(key)) < keySize {
md5Hash := md5.New()
common.Must2(md5Hash.Write(md5Sum[:]))
common.Must2(md5Hash.Write(password))
md5Hash.Sum(md5Sum[:0])
key = append(key, md5Sum[:]...)
}
return key
}
func hkdfSHA1(secret, salt, outKey []byte) {
r := hkdf.New(sha1.New, secret, salt, []byte("ss-subkey"))
common.Must2(io.ReadFull(r, outKey))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/protocol.go | proxy/shadowsocks/protocol.go | package shadowsocks
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"hash/crc32"
"io"
mrand "math/rand"
gonet "net"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/drain"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
const (
Version = 1
)
var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6),
protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain),
protocol.WithAddressTypeParser(func(b byte) byte {
return b & 0x0F
}),
)
// ReadTCPSession reads a Shadowsocks TCP session from the given reader, returns its header and remaining parts.
func ReadTCPSession(user *protocol.MemoryUser, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) {
account := user.Account.(*MemoryAccount)
hashkdf := hmac.New(sha256.New, []byte("SSBSKDF"))
hashkdf.Write(account.Key)
behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil))
drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(behaviorSeed), 16+38, 3266, 64)
if err != nil {
return nil, nil, newError("failed to initialize drainer").Base(err)
}
buffer := buf.New()
defer buffer.Release()
ivLen := account.Cipher.IVSize()
var iv []byte
if ivLen > 0 {
if _, err := buffer.ReadFullFrom(reader, ivLen); err != nil {
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("failed to read IV").Base(err))
}
iv = append([]byte(nil), buffer.BytesTo(ivLen)...)
}
r, err := account.Cipher.NewDecryptionReader(account.Key, iv, reader)
if err != nil {
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("failed to initialize decoding stream").Base(err).AtError())
}
br := &buf.BufferedReader{Reader: r}
request := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandTCP,
}
drainer.AcknowledgeReceive(int(buffer.Len()))
buffer.Clear()
addr, port, err := addrParser.ReadAddressPort(buffer, br)
if err != nil {
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("failed to read address").Base(err))
}
request.Address = addr
request.Port = port
if request.Address == nil {
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("invalid remote address."))
}
if ivError := account.CheckIV(iv); ivError != nil {
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("failed iv check").Base(ivError))
}
return request, br, nil
}
// WriteTCPRequest writes Shadowsocks request into the given writer, and returns a writer for body.
func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
user := request.User
account := user.Account.(*MemoryAccount)
var iv []byte
if account.Cipher.IVSize() > 0 {
iv = make([]byte, account.Cipher.IVSize())
common.Must2(rand.Read(iv))
if account.ReducedIVEntropy {
remapToPrintable(iv[:6])
}
if ivError := account.CheckIV(iv); ivError != nil {
return nil, newError("failed to mark outgoing iv").Base(ivError)
}
if err := buf.WriteAllBytes(writer, iv); err != nil {
return nil, newError("failed to write IV")
}
}
w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
if err != nil {
return nil, newError("failed to create encoding stream").Base(err).AtError()
}
header := buf.New()
if err := addrParser.WriteAddressPort(header, request.Address, request.Port); err != nil {
return nil, newError("failed to write address").Base(err)
}
if err := w.WriteMultiBuffer(buf.MultiBuffer{header}); err != nil {
return nil, newError("failed to write header").Base(err)
}
return w, nil
}
func ReadTCPResponse(user *protocol.MemoryUser, reader io.Reader) (buf.Reader, error) {
account := user.Account.(*MemoryAccount)
hashkdf := hmac.New(sha256.New, []byte("SSBSKDF"))
hashkdf.Write(account.Key)
behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil))
drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(behaviorSeed), 16+38, 3266, 64)
if err != nil {
return nil, newError("failed to initialize drainer").Base(err)
}
var iv []byte
if account.Cipher.IVSize() > 0 {
iv = make([]byte, account.Cipher.IVSize())
if n, err := io.ReadFull(reader, iv); err != nil {
return nil, newError("failed to read IV").Base(err)
} else { // nolint: revive
drainer.AcknowledgeReceive(n)
}
}
if ivError := account.CheckIV(iv); ivError != nil {
return nil, drain.WithError(drainer, reader, newError("failed iv check").Base(ivError))
}
return account.Cipher.NewDecryptionReader(account.Key, iv, reader)
}
func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
user := request.User
account := user.Account.(*MemoryAccount)
var iv []byte
if account.Cipher.IVSize() > 0 {
iv = make([]byte, account.Cipher.IVSize())
common.Must2(rand.Read(iv))
if ivError := account.CheckIV(iv); ivError != nil {
return nil, newError("failed to mark outgoing iv").Base(ivError)
}
if err := buf.WriteAllBytes(writer, iv); err != nil {
return nil, newError("failed to write IV.").Base(err)
}
}
return account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
}
func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) {
user := request.User
account := user.Account.(*MemoryAccount)
ivLen := account.Cipher.IVSize()
// Calculate required buffer size: IV + max address length (1+255+2) + payload + AEAD overhead (16)
neededSize := ivLen + 258 + int32(len(payload)) + 16
var buffer *buf.Buffer
if neededSize > buf.Size {
buffer = buf.NewWithSize(neededSize)
} else {
buffer = buf.New()
}
if ivLen > 0 {
common.Must2(buffer.ReadFullFrom(rand.Reader, ivLen))
}
if err := addrParser.WriteAddressPort(buffer, request.Address, request.Port); err != nil {
buffer.Release()
return nil, newError("failed to write address").Base(err)
}
buffer.Write(payload)
if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil {
buffer.Release()
return nil, newError("failed to encrypt UDP payload").Base(err)
}
return buffer, nil
}
func DecodeUDPPacket(user *protocol.MemoryUser, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) {
account := user.Account.(*MemoryAccount)
var iv []byte
if !account.Cipher.IsAEAD() && account.Cipher.IVSize() > 0 {
// Keep track of IV as it gets removed from payload in DecodePacket.
iv = make([]byte, account.Cipher.IVSize())
copy(iv, payload.BytesTo(account.Cipher.IVSize()))
}
if err := account.Cipher.DecodePacket(account.Key, payload); err != nil {
return nil, nil, newError("failed to decrypt UDP payload").Base(err)
}
request := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandUDP,
}
payload.SetByte(0, payload.Byte(0)&0x0F)
addr, port, err := addrParser.ReadAddressPort(nil, payload)
if err != nil {
return nil, nil, newError("failed to parse address").Base(err)
}
request.Address = addr
request.Port = port
return request, payload, nil
}
type UDPReader struct {
Reader io.Reader
User *protocol.MemoryUser
}
func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
buffer := buf.New()
_, err := buffer.ReadFrom(v.Reader)
if err != nil {
buffer.Release()
return nil, err
}
_, payload, err := DecodeUDPPacket(v.User, buffer)
if err != nil {
buffer.Release()
return nil, err
}
return buf.MultiBuffer{payload}, nil
}
func (v *UDPReader) ReadFrom(p []byte) (n int, addr gonet.Addr, err error) {
buffer := buf.New()
_, err = buffer.ReadFrom(v.Reader)
if err != nil {
buffer.Release()
return 0, nil, err
}
vaddr, payload, err := DecodeUDPPacket(v.User, buffer)
if err != nil {
buffer.Release()
return 0, nil, err
}
n = copy(p, payload.Bytes())
payload.Release()
return n, &gonet.UDPAddr{IP: vaddr.Address.IP(), Port: int(vaddr.Port)}, nil
}
type UDPWriter struct {
Writer io.Writer
Request *protocol.RequestHeader
}
// Write implements io.Writer.
func (w *UDPWriter) Write(payload []byte) (int, error) {
packet, err := EncodeUDPPacket(w.Request, payload)
if err != nil {
return 0, err
}
_, err = w.Writer.Write(packet.Bytes())
packet.Release()
return len(payload), err
}
func (w *UDPWriter) WriteTo(payload []byte, addr gonet.Addr) (n int, err error) {
request := *w.Request
udpAddr := addr.(*gonet.UDPAddr)
request.Command = protocol.RequestCommandUDP
request.Address = net.IPAddress(udpAddr.IP)
request.Port = net.Port(udpAddr.Port)
packet, err := EncodeUDPPacket(&request, payload)
if err != nil {
return 0, err
}
_, err = w.Writer.Write(packet.Bytes())
packet.Release()
return len(payload), err
}
func remapToPrintable(input []byte) {
const charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~\\\""
seed := mrand.New(mrand.NewSource(int64(crc32.ChecksumIEEE(input))))
for i := range input {
input[i] = charSet[seed.Intn(len(charSet))]
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/protocol_test.go | proxy/shadowsocks/protocol_test.go | package shadowsocks_test
import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
. "github.com/v2fly/v2ray-core/v5/proxy/shadowsocks"
)
func toAccount(a *Account) protocol.Account {
account, err := a.AsAccount()
common.Must(err)
return account
}
func equalRequestHeader(x, y *protocol.RequestHeader) bool {
return cmp.Equal(x, y, cmp.Comparer(func(x, y protocol.RequestHeader) bool {
return x == y
}))
}
func TestUDPEncoding(t *testing.T) {
request := &protocol.RequestHeader{
Version: Version,
Command: protocol.RequestCommandUDP,
Address: net.LocalHostIP,
Port: 1234,
User: &protocol.MemoryUser{
Email: "love@v2fly.org",
Account: toAccount(&Account{
Password: "password",
CipherType: CipherType_AES_128_GCM,
}),
},
}
data := buf.New()
common.Must2(data.WriteString("test string"))
encodedData, err := EncodeUDPPacket(request, data.Bytes())
common.Must(err)
decodedRequest, decodedData, err := DecodeUDPPacket(request.User, encodedData)
common.Must(err)
if r := cmp.Diff(decodedData.Bytes(), data.Bytes()); r != "" {
t.Error("data: ", r)
}
if equalRequestHeader(decodedRequest, request) == false {
t.Error("different request")
}
}
func TestTCPRequest(t *testing.T) {
cases := []struct {
request *protocol.RequestHeader
payload []byte
}{
{
request: &protocol.RequestHeader{
Version: Version,
Command: protocol.RequestCommandTCP,
Address: net.LocalHostIP,
Port: 1234,
User: &protocol.MemoryUser{
Email: "love@v2fly.org",
Account: toAccount(&Account{
Password: "tcp-password",
CipherType: CipherType_AES_128_GCM,
}),
},
},
payload: []byte("test string"),
},
{
request: &protocol.RequestHeader{
Version: Version,
Command: protocol.RequestCommandTCP,
Address: net.LocalHostIPv6,
Port: 1234,
User: &protocol.MemoryUser{
Email: "love@v2fly.org",
Account: toAccount(&Account{
Password: "password",
CipherType: CipherType_AES_256_GCM,
}),
},
},
payload: []byte("test string"),
},
{
request: &protocol.RequestHeader{
Version: Version,
Command: protocol.RequestCommandTCP,
Address: net.DomainAddress("v2fly.org"),
Port: 1234,
User: &protocol.MemoryUser{
Email: "love@v2fly.org",
Account: toAccount(&Account{
Password: "password",
CipherType: CipherType_CHACHA20_POLY1305,
}),
},
},
payload: []byte("test string"),
},
}
runTest := func(request *protocol.RequestHeader, payload []byte) {
data := buf.New()
common.Must2(data.Write(payload))
cache := buf.New()
defer cache.Release()
writer, err := WriteTCPRequest(request, cache)
common.Must(err)
common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{data}))
decodedRequest, reader, err := ReadTCPSession(request.User, cache)
common.Must(err)
if equalRequestHeader(decodedRequest, request) == false {
t.Error("different request")
}
decodedData, err := reader.ReadMultiBuffer()
common.Must(err)
if r := cmp.Diff(decodedData[0].Bytes(), payload); r != "" {
t.Error("data: ", r)
}
}
for _, test := range cases {
runTest(test.request, test.payload)
}
}
func TestUDPReaderWriter(t *testing.T) {
user := &protocol.MemoryUser{
Account: toAccount(&Account{
Password: "test-password",
CipherType: CipherType_CHACHA20_POLY1305,
}),
}
cache := buf.New()
defer cache.Release()
writer := &buf.SequentialWriter{Writer: &UDPWriter{
Writer: cache,
Request: &protocol.RequestHeader{
Version: Version,
Address: net.DomainAddress("v2fly.org"),
Port: 123,
User: user,
},
}}
reader := &UDPReader{
Reader: cache,
User: user,
}
{
b := buf.New()
common.Must2(b.WriteString("test payload"))
common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{b}))
payload, err := reader.ReadMultiBuffer()
common.Must(err)
if payload[0].String() != "test payload" {
t.Error("unexpected output: ", payload[0].String())
}
}
{
b := buf.New()
common.Must2(b.WriteString("test payload 2"))
common.Must(writer.WriteMultiBuffer(buf.MultiBuffer{b}))
payload, err := reader.ReadMultiBuffer()
common.Must(err)
if payload[0].String() != "test payload 2" {
t.Error("unexpected output: ", payload[0].String())
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/config_test.go | proxy/shadowsocks/config_test.go | package shadowsocks_test
import (
"crypto/rand"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/proxy/shadowsocks"
)
func TestAEADCipherUDP(t *testing.T) {
rawAccount := &shadowsocks.Account{
CipherType: shadowsocks.CipherType_AES_128_GCM,
Password: "test",
}
account, err := rawAccount.AsAccount()
common.Must(err)
cipher := account.(*shadowsocks.MemoryAccount).Cipher
key := make([]byte, cipher.KeySize())
common.Must2(rand.Read(key))
payload := make([]byte, 1024)
common.Must2(rand.Read(payload))
b1 := buf.New()
common.Must2(b1.ReadFullFrom(rand.Reader, cipher.IVSize()))
common.Must2(b1.Write(payload))
common.Must(cipher.EncodePacket(key, b1))
common.Must(cipher.DecodePacket(key, b1))
if diff := cmp.Diff(b1.Bytes(), payload); diff != "" {
t.Error(diff)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/server.go | proxy/shadowsocks/server.go | package shadowsocks
import (
"context"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/log"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/protocol"
udp_proto "github.com/v2fly/v2ray-core/v5/common/protocol/udp"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
type Server struct {
config *ServerConfig
user *protocol.MemoryUser
policyManager policy.Manager
}
// NewServer create a new Shadowsocks server.
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
if config.GetUser() == nil {
return nil, newError("user is not specified")
}
mUser, err := config.User.ToMemoryUser()
if err != nil {
return nil, newError("failed to parse user account").Base(err)
}
v := core.MustFromContext(ctx)
s := &Server{
config: config,
user: mUser,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}
return s, nil
}
func (s *Server) Network() []net.Network {
list := s.config.Network
if len(list) == 0 {
list = append(list, net.Network_TCP)
}
if s.config.UdpEnabled {
list = append(list, net.Network_UDP)
}
return list
}
func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
switch network {
case net.Network_TCP:
return s.handleConnection(ctx, conn, dispatcher)
case net.Network_UDP:
return s.handlerUDPPayload(ctx, conn, dispatcher)
default:
return newError("unknown network: ", network)
}
}
func (s *Server) handlerUDPPayload(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
udpDispatcherConstructor := udp.NewSplitDispatcher
switch s.config.PacketEncoding {
case packetaddr.PacketAddrType_None:
break
case packetaddr.PacketAddrType_Packet:
packetAddrDispatcherFactory := udp.NewPacketAddrDispatcherCreator(ctx)
udpDispatcherConstructor = packetAddrDispatcherFactory.NewPacketAddrDispatcher
}
udpServer := udpDispatcherConstructor(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
request := protocol.RequestHeaderFromContext(ctx)
if request == nil {
request = &protocol.RequestHeader{
Port: packet.Source.Port,
Address: packet.Source.Address,
User: s.user,
}
}
payload := packet.Payload
data, err := EncodeUDPPacket(request, payload.Bytes())
payload.Release()
if err != nil {
newError("failed to encode UDP packet").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx))
return
}
defer data.Release()
conn.Write(data.Bytes())
})
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
}
inbound.User = s.user
reader := buf.NewPacketReader(conn)
for {
mpayload, err := reader.ReadMultiBuffer()
if err != nil {
break
}
for _, payload := range mpayload {
request, data, err := DecodeUDPPacket(s.user, payload)
if err != nil {
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
newError("dropping invalid UDP packet from: ", inbound.Source).Base(err).WriteToLog(session.ExportIDToError(ctx))
log.Record(&log.AccessMessage{
From: inbound.Source,
To: "",
Status: log.AccessRejected,
Reason: err,
})
}
payload.Release()
continue
}
currentPacketCtx := ctx
dest := request.Destination()
if inbound.Source.IsValid() {
currentPacketCtx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: inbound.Source,
To: dest,
Status: log.AccessAccepted,
Reason: "",
Email: request.User.Email,
})
}
newError("tunnelling request to ", dest).WriteToLog(session.ExportIDToError(currentPacketCtx))
currentPacketCtx = protocol.ContextWithRequestHeader(currentPacketCtx, request)
udpServer.Dispatch(currentPacketCtx, dest, data)
}
}
return nil
}
func (s *Server) handleConnection(ctx context.Context, conn internet.Connection, dispatcher routing.Dispatcher) error {
sessionPolicy := s.policyManager.ForLevel(s.user.Level)
conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake))
bufferedReader := buf.BufferedReader{Reader: buf.NewReader(conn)}
request, bodyReader, err := ReadTCPSession(s.user, &bufferedReader)
if err != nil {
log.Record(&log.AccessMessage{
From: conn.RemoteAddr(),
To: "",
Status: log.AccessRejected,
Reason: err,
})
return newError("failed to create request from: ", conn.RemoteAddr()).Base(err)
}
conn.SetReadDeadline(time.Time{})
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
}
inbound.User = s.user
dest := request.Destination()
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: conn.RemoteAddr(),
To: dest,
Status: log.AccessAccepted,
Reason: "",
Email: request.User.Email,
})
newError("tunnelling request to ", dest).WriteToLog(session.ExportIDToError(ctx))
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
link, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return err
}
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
responseWriter, err := WriteTCPResponse(request, bufferedWriter)
if err != nil {
return newError("failed to write response").Base(err)
}
{
payload, err := link.Reader.ReadMultiBuffer()
if err != nil {
return err
}
if err := responseWriter.WriteMultiBuffer(payload); err != nil {
return err
}
}
if err := bufferedWriter.SetBuffered(false); err != nil {
return err
}
if err := buf.Copy(link.Reader, responseWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport all TCP response").Base(err)
}
return nil
}
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport all TCP request").Base(err)
}
return nil
}
requestDoneAndCloseWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil {
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
return newError("connection ends").Base(err)
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewServer(ctx, config.(*ServerConfig))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/config.pb.go | proxy/shadowsocks/config.pb.go | package shadowsocks
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
packetaddr "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
protocol "github.com/v2fly/v2ray-core/v5/common/protocol"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type CipherType int32
const (
CipherType_UNKNOWN CipherType = 0
CipherType_AES_128_GCM CipherType = 1
CipherType_AES_256_GCM CipherType = 2
CipherType_CHACHA20_POLY1305 CipherType = 3
CipherType_NONE CipherType = 4
)
// Enum value maps for CipherType.
var (
CipherType_name = map[int32]string{
0: "UNKNOWN",
1: "AES_128_GCM",
2: "AES_256_GCM",
3: "CHACHA20_POLY1305",
4: "NONE",
}
CipherType_value = map[string]int32{
"UNKNOWN": 0,
"AES_128_GCM": 1,
"AES_256_GCM": 2,
"CHACHA20_POLY1305": 3,
"NONE": 4,
}
)
func (x CipherType) Enum() *CipherType {
p := new(CipherType)
*p = x
return p
}
func (x CipherType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (CipherType) Descriptor() protoreflect.EnumDescriptor {
return file_proxy_shadowsocks_config_proto_enumTypes[0].Descriptor()
}
func (CipherType) Type() protoreflect.EnumType {
return &file_proxy_shadowsocks_config_proto_enumTypes[0]
}
func (x CipherType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use CipherType.Descriptor instead.
func (CipherType) EnumDescriptor() ([]byte, []int) {
return file_proxy_shadowsocks_config_proto_rawDescGZIP(), []int{0}
}
type Account struct {
state protoimpl.MessageState `protogen:"open.v1"`
Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"`
CipherType CipherType `protobuf:"varint,2,opt,name=cipher_type,json=cipherType,proto3,enum=v2ray.core.proxy.shadowsocks.CipherType" json:"cipher_type,omitempty"`
IvCheck bool `protobuf:"varint,3,opt,name=iv_check,json=ivCheck,proto3" json:"iv_check,omitempty"`
ExperimentReducedIvHeadEntropy bool `protobuf:"varint,90001,opt,name=experiment_reduced_iv_head_entropy,json=experimentReducedIvHeadEntropy,proto3" json:"experiment_reduced_iv_head_entropy,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Account) Reset() {
*x = Account{}
mi := &file_proxy_shadowsocks_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Account) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Account) ProtoMessage() {}
func (x *Account) ProtoReflect() protoreflect.Message {
mi := &file_proxy_shadowsocks_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Account.ProtoReflect.Descriptor instead.
func (*Account) Descriptor() ([]byte, []int) {
return file_proxy_shadowsocks_config_proto_rawDescGZIP(), []int{0}
}
func (x *Account) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
func (x *Account) GetCipherType() CipherType {
if x != nil {
return x.CipherType
}
return CipherType_UNKNOWN
}
func (x *Account) GetIvCheck() bool {
if x != nil {
return x.IvCheck
}
return false
}
func (x *Account) GetExperimentReducedIvHeadEntropy() bool {
if x != nil {
return x.ExperimentReducedIvHeadEntropy
}
return false
}
type ServerConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// UdpEnabled specified whether or not to enable UDP for Shadowsocks.
// Deprecated. Use 'network' field.
//
// Deprecated: Marked as deprecated in proxy/shadowsocks/config.proto.
UdpEnabled bool `protobuf:"varint,1,opt,name=udp_enabled,json=udpEnabled,proto3" json:"udp_enabled,omitempty"`
User *protocol.User `protobuf:"bytes,2,opt,name=user,proto3" json:"user,omitempty"`
Network []net.Network `protobuf:"varint,3,rep,packed,name=network,proto3,enum=v2ray.core.common.net.Network" json:"network,omitempty"`
PacketEncoding packetaddr.PacketAddrType `protobuf:"varint,4,opt,name=packet_encoding,json=packetEncoding,proto3,enum=v2ray.core.net.packetaddr.PacketAddrType" json:"packet_encoding,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerConfig) Reset() {
*x = ServerConfig{}
mi := &file_proxy_shadowsocks_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerConfig) ProtoMessage() {}
func (x *ServerConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_shadowsocks_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerConfig.ProtoReflect.Descriptor instead.
func (*ServerConfig) Descriptor() ([]byte, []int) {
return file_proxy_shadowsocks_config_proto_rawDescGZIP(), []int{1}
}
// Deprecated: Marked as deprecated in proxy/shadowsocks/config.proto.
func (x *ServerConfig) GetUdpEnabled() bool {
if x != nil {
return x.UdpEnabled
}
return false
}
func (x *ServerConfig) GetUser() *protocol.User {
if x != nil {
return x.User
}
return nil
}
func (x *ServerConfig) GetNetwork() []net.Network {
if x != nil {
return x.Network
}
return nil
}
func (x *ServerConfig) GetPacketEncoding() packetaddr.PacketAddrType {
if x != nil {
return x.PacketEncoding
}
return packetaddr.PacketAddrType(0)
}
type ClientConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Server []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=server,proto3" json:"server,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClientConfig) Reset() {
*x = ClientConfig{}
mi := &file_proxy_shadowsocks_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ClientConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ClientConfig) ProtoMessage() {}
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_shadowsocks_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
func (*ClientConfig) Descriptor() ([]byte, []int) {
return file_proxy_shadowsocks_config_proto_rawDescGZIP(), []int{2}
}
func (x *ClientConfig) GetServer() []*protocol.ServerEndpoint {
if x != nil {
return x.Server
}
return nil
}
var File_proxy_shadowsocks_config_proto protoreflect.FileDescriptor
const file_proxy_shadowsocks_config_proto_rawDesc = "" +
"\n" +
"\x1eproxy/shadowsocks/config.proto\x12\x1cv2ray.core.proxy.shadowsocks\x1a\x18common/net/network.proto\x1a\x1acommon/protocol/user.proto\x1a!common/protocol/server_spec.proto\x1a\"common/net/packetaddr/config.proto\"\xd9\x01\n" +
"\aAccount\x12\x1a\n" +
"\bpassword\x18\x01 \x01(\tR\bpassword\x12I\n" +
"\vcipher_type\x18\x02 \x01(\x0e2(.v2ray.core.proxy.shadowsocks.CipherTypeR\n" +
"cipherType\x12\x19\n" +
"\biv_check\x18\x03 \x01(\bR\aivCheck\x12L\n" +
"\"experiment_reduced_iv_head_entropy\x18\x91\xbf\x05 \x01(\bR\x1eexperimentReducedIvHeadEntropy\"\xf7\x01\n" +
"\fServerConfig\x12#\n" +
"\vudp_enabled\x18\x01 \x01(\bB\x02\x18\x01R\n" +
"udpEnabled\x124\n" +
"\x04user\x18\x02 \x01(\v2 .v2ray.core.common.protocol.UserR\x04user\x128\n" +
"\anetwork\x18\x03 \x03(\x0e2\x1e.v2ray.core.common.net.NetworkR\anetwork\x12R\n" +
"\x0fpacket_encoding\x18\x04 \x01(\x0e2).v2ray.core.net.packetaddr.PacketAddrTypeR\x0epacketEncoding\"R\n" +
"\fClientConfig\x12B\n" +
"\x06server\x18\x01 \x03(\v2*.v2ray.core.common.protocol.ServerEndpointR\x06server*\\\n" +
"\n" +
"CipherType\x12\v\n" +
"\aUNKNOWN\x10\x00\x12\x0f\n" +
"\vAES_128_GCM\x10\x01\x12\x0f\n" +
"\vAES_256_GCM\x10\x02\x12\x15\n" +
"\x11CHACHA20_POLY1305\x10\x03\x12\b\n" +
"\x04NONE\x10\x04Bu\n" +
" com.v2ray.core.proxy.shadowsocksP\x01Z0github.com/v2fly/v2ray-core/v5/proxy/shadowsocks\xaa\x02\x1cV2Ray.Core.Proxy.Shadowsocksb\x06proto3"
var (
file_proxy_shadowsocks_config_proto_rawDescOnce sync.Once
file_proxy_shadowsocks_config_proto_rawDescData []byte
)
func file_proxy_shadowsocks_config_proto_rawDescGZIP() []byte {
file_proxy_shadowsocks_config_proto_rawDescOnce.Do(func() {
file_proxy_shadowsocks_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_shadowsocks_config_proto_rawDesc), len(file_proxy_shadowsocks_config_proto_rawDesc)))
})
return file_proxy_shadowsocks_config_proto_rawDescData
}
var file_proxy_shadowsocks_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_proxy_shadowsocks_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_proxy_shadowsocks_config_proto_goTypes = []any{
(CipherType)(0), // 0: v2ray.core.proxy.shadowsocks.CipherType
(*Account)(nil), // 1: v2ray.core.proxy.shadowsocks.Account
(*ServerConfig)(nil), // 2: v2ray.core.proxy.shadowsocks.ServerConfig
(*ClientConfig)(nil), // 3: v2ray.core.proxy.shadowsocks.ClientConfig
(*protocol.User)(nil), // 4: v2ray.core.common.protocol.User
(net.Network)(0), // 5: v2ray.core.common.net.Network
(packetaddr.PacketAddrType)(0), // 6: v2ray.core.net.packetaddr.PacketAddrType
(*protocol.ServerEndpoint)(nil), // 7: v2ray.core.common.protocol.ServerEndpoint
}
var file_proxy_shadowsocks_config_proto_depIdxs = []int32{
0, // 0: v2ray.core.proxy.shadowsocks.Account.cipher_type:type_name -> v2ray.core.proxy.shadowsocks.CipherType
4, // 1: v2ray.core.proxy.shadowsocks.ServerConfig.user:type_name -> v2ray.core.common.protocol.User
5, // 2: v2ray.core.proxy.shadowsocks.ServerConfig.network:type_name -> v2ray.core.common.net.Network
6, // 3: v2ray.core.proxy.shadowsocks.ServerConfig.packet_encoding:type_name -> v2ray.core.net.packetaddr.PacketAddrType
7, // 4: v2ray.core.proxy.shadowsocks.ClientConfig.server:type_name -> v2ray.core.common.protocol.ServerEndpoint
5, // [5:5] is the sub-list for method output_type
5, // [5:5] is the sub-list for method input_type
5, // [5:5] is the sub-list for extension type_name
5, // [5:5] is the sub-list for extension extendee
0, // [0:5] is the sub-list for field type_name
}
func init() { file_proxy_shadowsocks_config_proto_init() }
func file_proxy_shadowsocks_config_proto_init() {
if File_proxy_shadowsocks_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_shadowsocks_config_proto_rawDesc), len(file_proxy_shadowsocks_config_proto_rawDesc)),
NumEnums: 1,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_shadowsocks_config_proto_goTypes,
DependencyIndexes: file_proxy_shadowsocks_config_proto_depIdxs,
EnumInfos: file_proxy_shadowsocks_config_proto_enumTypes,
MessageInfos: file_proxy_shadowsocks_config_proto_msgTypes,
}.Build()
File_proxy_shadowsocks_config_proto = out.File
file_proxy_shadowsocks_config_proto_goTypes = nil
file_proxy_shadowsocks_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/simplified/errors.generated.go | proxy/shadowsocks/simplified/errors.generated.go | package simplified
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/simplified/config.go | proxy/shadowsocks/simplified/config.go | package simplified
import (
"context"
"encoding/json"
"github.com/golang/protobuf/jsonpb"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/proxy/shadowsocks"
)
func (c *CipherTypeWrapper) UnmarshalJSONPB(unmarshaler *jsonpb.Unmarshaler, bytes []byte) error {
var method string
if err := json.Unmarshal(bytes, &method); err != nil {
return err
}
if c.Value = shadowsocks.CipherFromString(method); c.Value == shadowsocks.CipherType_UNKNOWN {
return newError("unknown cipher method: ", method)
}
return nil
}
func (c *CipherTypeWrapper) MarshalJSONPB(marshaler *jsonpb.Marshaler) ([]byte, error) {
method := c.Value.String()
return json.Marshal(method)
}
func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedServer := config.(*ServerConfig)
fullServer := &shadowsocks.ServerConfig{
User: &protocol.User{
Account: serial.ToTypedMessage(&shadowsocks.Account{
Password: simplifiedServer.Password,
CipherType: simplifiedServer.Method.Value,
}),
},
Network: simplifiedServer.Networks.GetNetwork(),
PacketEncoding: simplifiedServer.PacketEncoding,
}
return common.CreateObject(ctx, fullServer)
}))
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedClient := config.(*ClientConfig)
fullClient := &shadowsocks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: simplifiedClient.Address,
Port: simplifiedClient.Port,
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&shadowsocks.Account{
Password: simplifiedClient.Password,
CipherType: simplifiedClient.Method.Value,
ExperimentReducedIvHeadEntropy: simplifiedClient.ExperimentReducedIvHeadEntropy,
}),
},
},
},
},
}
return common.CreateObject(ctx, fullClient)
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/shadowsocks/simplified/config.pb.go | proxy/shadowsocks/simplified/config.pb.go | package simplified
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
packetaddr "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
shadowsocks "github.com/v2fly/v2ray-core/v5/proxy/shadowsocks"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ServerConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Method *CipherTypeWrapper `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
Networks *net.NetworkList `protobuf:"bytes,3,opt,name=networks,proto3" json:"networks,omitempty"`
PacketEncoding packetaddr.PacketAddrType `protobuf:"varint,4,opt,name=packet_encoding,json=packetEncoding,proto3,enum=v2ray.core.net.packetaddr.PacketAddrType" json:"packet_encoding,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerConfig) Reset() {
*x = ServerConfig{}
mi := &file_proxy_shadowsocks_simplified_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerConfig) ProtoMessage() {}
func (x *ServerConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_shadowsocks_simplified_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerConfig.ProtoReflect.Descriptor instead.
func (*ServerConfig) Descriptor() ([]byte, []int) {
return file_proxy_shadowsocks_simplified_config_proto_rawDescGZIP(), []int{0}
}
func (x *ServerConfig) GetMethod() *CipherTypeWrapper {
if x != nil {
return x.Method
}
return nil
}
func (x *ServerConfig) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
func (x *ServerConfig) GetNetworks() *net.NetworkList {
if x != nil {
return x.Networks
}
return nil
}
func (x *ServerConfig) GetPacketEncoding() packetaddr.PacketAddrType {
if x != nil {
return x.PacketEncoding
}
return packetaddr.PacketAddrType(0)
}
type ClientConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`
Method *CipherTypeWrapper `protobuf:"bytes,3,opt,name=method,proto3" json:"method,omitempty"`
Password string `protobuf:"bytes,4,opt,name=password,proto3" json:"password,omitempty"`
ExperimentReducedIvHeadEntropy bool `protobuf:"varint,90001,opt,name=experiment_reduced_iv_head_entropy,json=experimentReducedIvHeadEntropy,proto3" json:"experiment_reduced_iv_head_entropy,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClientConfig) Reset() {
*x = ClientConfig{}
mi := &file_proxy_shadowsocks_simplified_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ClientConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ClientConfig) ProtoMessage() {}
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_shadowsocks_simplified_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
func (*ClientConfig) Descriptor() ([]byte, []int) {
return file_proxy_shadowsocks_simplified_config_proto_rawDescGZIP(), []int{1}
}
func (x *ClientConfig) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *ClientConfig) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
func (x *ClientConfig) GetMethod() *CipherTypeWrapper {
if x != nil {
return x.Method
}
return nil
}
func (x *ClientConfig) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
func (x *ClientConfig) GetExperimentReducedIvHeadEntropy() bool {
if x != nil {
return x.ExperimentReducedIvHeadEntropy
}
return false
}
type CipherTypeWrapper struct {
state protoimpl.MessageState `protogen:"open.v1"`
Value shadowsocks.CipherType `protobuf:"varint,1,opt,name=value,proto3,enum=v2ray.core.proxy.shadowsocks.CipherType" json:"value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CipherTypeWrapper) Reset() {
*x = CipherTypeWrapper{}
mi := &file_proxy_shadowsocks_simplified_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CipherTypeWrapper) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CipherTypeWrapper) ProtoMessage() {}
func (x *CipherTypeWrapper) ProtoReflect() protoreflect.Message {
mi := &file_proxy_shadowsocks_simplified_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CipherTypeWrapper.ProtoReflect.Descriptor instead.
func (*CipherTypeWrapper) Descriptor() ([]byte, []int) {
return file_proxy_shadowsocks_simplified_config_proto_rawDescGZIP(), []int{2}
}
func (x *CipherTypeWrapper) GetValue() shadowsocks.CipherType {
if x != nil {
return x.Value
}
return shadowsocks.CipherType(0)
}
var File_proxy_shadowsocks_simplified_config_proto protoreflect.FileDescriptor
const file_proxy_shadowsocks_simplified_config_proto_rawDesc = "" +
"\n" +
")proxy/shadowsocks/simplified/config.proto\x12'v2ray.core.proxy.shadowsocks.simplified\x1a common/protoext/extensions.proto\x1a\x18common/net/address.proto\x1a\x18common/net/network.proto\x1a\"common/net/packetaddr/config.proto\x1a\x1eproxy/shadowsocks/config.proto\"\xae\x02\n" +
"\fServerConfig\x12R\n" +
"\x06method\x18\x01 \x01(\v2:.v2ray.core.proxy.shadowsocks.simplified.CipherTypeWrapperR\x06method\x12\x1a\n" +
"\bpassword\x18\x02 \x01(\tR\bpassword\x12>\n" +
"\bnetworks\x18\x03 \x01(\v2\".v2ray.core.common.net.NetworkListR\bnetworks\x12R\n" +
"\x0fpacket_encoding\x18\x04 \x01(\x0e2).v2ray.core.net.packetaddr.PacketAddrTypeR\x0epacketEncoding:\x1a\x82\xb5\x18\x16\n" +
"\ainbound\x12\vshadowsocks\"\xbe\x02\n" +
"\fClientConfig\x12;\n" +
"\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" +
"\x04port\x18\x02 \x01(\rR\x04port\x12R\n" +
"\x06method\x18\x03 \x01(\v2:.v2ray.core.proxy.shadowsocks.simplified.CipherTypeWrapperR\x06method\x12\x1a\n" +
"\bpassword\x18\x04 \x01(\tR\bpassword\x12L\n" +
"\"experiment_reduced_iv_head_entropy\x18\x91\xbf\x05 \x01(\bR\x1eexperimentReducedIvHeadEntropy:\x1f\x82\xb5\x18\x1b\n" +
"\boutbound\x12\vshadowsocks\x90\xff)\x01\"S\n" +
"\x11CipherTypeWrapper\x12>\n" +
"\x05value\x18\x01 \x01(\x0e2(.v2ray.core.proxy.shadowsocks.CipherTypeR\x05valueB\x96\x01\n" +
"+com.v2ray.core.proxy.shadowsocks.simplifiedP\x01Z;github.com/v2fly/v2ray-core/v5/proxy/shadowsocks/simplified\xaa\x02'V2Ray.Core.Proxy.Shadowsocks.Simplifiedb\x06proto3"
var (
file_proxy_shadowsocks_simplified_config_proto_rawDescOnce sync.Once
file_proxy_shadowsocks_simplified_config_proto_rawDescData []byte
)
func file_proxy_shadowsocks_simplified_config_proto_rawDescGZIP() []byte {
file_proxy_shadowsocks_simplified_config_proto_rawDescOnce.Do(func() {
file_proxy_shadowsocks_simplified_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_shadowsocks_simplified_config_proto_rawDesc), len(file_proxy_shadowsocks_simplified_config_proto_rawDesc)))
})
return file_proxy_shadowsocks_simplified_config_proto_rawDescData
}
var file_proxy_shadowsocks_simplified_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_proxy_shadowsocks_simplified_config_proto_goTypes = []any{
(*ServerConfig)(nil), // 0: v2ray.core.proxy.shadowsocks.simplified.ServerConfig
(*ClientConfig)(nil), // 1: v2ray.core.proxy.shadowsocks.simplified.ClientConfig
(*CipherTypeWrapper)(nil), // 2: v2ray.core.proxy.shadowsocks.simplified.CipherTypeWrapper
(*net.NetworkList)(nil), // 3: v2ray.core.common.net.NetworkList
(packetaddr.PacketAddrType)(0), // 4: v2ray.core.net.packetaddr.PacketAddrType
(*net.IPOrDomain)(nil), // 5: v2ray.core.common.net.IPOrDomain
(shadowsocks.CipherType)(0), // 6: v2ray.core.proxy.shadowsocks.CipherType
}
var file_proxy_shadowsocks_simplified_config_proto_depIdxs = []int32{
2, // 0: v2ray.core.proxy.shadowsocks.simplified.ServerConfig.method:type_name -> v2ray.core.proxy.shadowsocks.simplified.CipherTypeWrapper
3, // 1: v2ray.core.proxy.shadowsocks.simplified.ServerConfig.networks:type_name -> v2ray.core.common.net.NetworkList
4, // 2: v2ray.core.proxy.shadowsocks.simplified.ServerConfig.packet_encoding:type_name -> v2ray.core.net.packetaddr.PacketAddrType
5, // 3: v2ray.core.proxy.shadowsocks.simplified.ClientConfig.address:type_name -> v2ray.core.common.net.IPOrDomain
2, // 4: v2ray.core.proxy.shadowsocks.simplified.ClientConfig.method:type_name -> v2ray.core.proxy.shadowsocks.simplified.CipherTypeWrapper
6, // 5: v2ray.core.proxy.shadowsocks.simplified.CipherTypeWrapper.value:type_name -> v2ray.core.proxy.shadowsocks.CipherType
6, // [6:6] is the sub-list for method output_type
6, // [6:6] is the sub-list for method input_type
6, // [6:6] is the sub-list for extension type_name
6, // [6:6] is the sub-list for extension extendee
0, // [0:6] is the sub-list for field type_name
}
func init() { file_proxy_shadowsocks_simplified_config_proto_init() }
func file_proxy_shadowsocks_simplified_config_proto_init() {
if File_proxy_shadowsocks_simplified_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_shadowsocks_simplified_config_proto_rawDesc), len(file_proxy_shadowsocks_simplified_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_shadowsocks_simplified_config_proto_goTypes,
DependencyIndexes: file_proxy_shadowsocks_simplified_config_proto_depIdxs,
MessageInfos: file_proxy_shadowsocks_simplified_config_proto_msgTypes,
}.Build()
File_proxy_shadowsocks_simplified_config_proto = out.File
file_proxy_shadowsocks_simplified_config_proto_goTypes = nil
file_proxy_shadowsocks_simplified_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/dns/dns_test.go | proxy/dns/dns_test.go | package dns_test
import (
"strconv"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/miekg/dns"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/dispatcher"
dnsapp "github.com/v2fly/v2ray-core/v5/app/dns"
"github.com/v2fly/v2ray-core/v5/app/policy"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
_ "github.com/v2fly/v2ray-core/v5/app/proxyman/inbound"
_ "github.com/v2fly/v2ray-core/v5/app/proxyman/outbound"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/serial"
dns_proxy "github.com/v2fly/v2ray-core/v5/proxy/dns"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
)
type staticHandler struct{}
func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
ans := new(dns.Msg)
ans.Id = r.Id
var clientIP net.IP
opt := r.IsEdns0()
if opt != nil {
for _, o := range opt.Option {
if o.Option() == dns.EDNS0SUBNET {
subnet := o.(*dns.EDNS0_SUBNET)
clientIP = subnet.Address
}
}
}
for _, q := range r.Question {
switch {
case q.Name == "google.com." && q.Qtype == dns.TypeA:
if clientIP == nil {
rr, _ := dns.NewRR("google.com. IN A 8.8.8.8")
ans.Answer = append(ans.Answer, rr)
} else {
rr, _ := dns.NewRR("google.com. IN A 8.8.4.4")
ans.Answer = append(ans.Answer, rr)
}
case q.Name == "facebook.com." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("facebook.com. IN A 9.9.9.9")
ans.Answer = append(ans.Answer, rr)
case q.Name == "ipv6.google.com." && q.Qtype == dns.TypeA:
rr, err := dns.NewRR("ipv6.google.com. IN A 8.8.8.7")
common.Must(err)
ans.Answer = append(ans.Answer, rr)
case q.Name == "ipv6.google.com." && q.Qtype == dns.TypeAAAA:
rr, err := dns.NewRR("ipv6.google.com. IN AAAA 2001:4860:4860::8888")
common.Must(err)
ans.Answer = append(ans.Answer, rr)
case q.Name == "notexist.google.com." && q.Qtype == dns.TypeAAAA:
ans.MsgHdr.Rcode = dns.RcodeNameError
}
}
w.WriteMsg(ans)
}
func TestUDPDNSTunnel(t *testing.T) {
port := udp.PickPort()
dnsServer := dns.Server{
Addr: "127.0.0.1:" + port.String(),
Net: "udp",
Handler: &staticHandler{},
UDPSize: 1200,
}
defer dnsServer.Shutdown()
go dnsServer.ListenAndServe()
time.Sleep(time.Second)
serverPort := udp.PickPort()
config := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dnsapp.Config{
NameServers: []*net.Endpoint{
{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
},
}),
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&policy.Config{}),
},
Inbound: []*core.InboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(port),
Networks: []net.Network{net.Network_UDP},
}),
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&dns_proxy.Config{}),
},
},
}
v, err := core.New(config)
common.Must(err)
common.Must(v.Start())
defer v.Close()
{
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{Name: "google.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}
c := new(dns.Client)
in, _, err := c.Exchange(m1, "127.0.0.1:"+strconv.Itoa(int(serverPort)))
common.Must(err)
if len(in.Answer) != 1 {
t.Fatal("len(answer): ", len(in.Answer))
}
rr, ok := in.Answer[0].(*dns.A)
if !ok {
t.Fatal("not A record")
}
if r := cmp.Diff(rr.A[:], net.IP{8, 8, 8, 8}); r != "" {
t.Error(r)
}
}
{
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{Name: "ipv4only.google.com.", Qtype: dns.TypeAAAA, Qclass: dns.ClassINET}
c := new(dns.Client)
c.Timeout = 10 * time.Second
in, _, err := c.Exchange(m1, "127.0.0.1:"+strconv.Itoa(int(serverPort)))
common.Must(err)
if len(in.Answer) != 0 {
t.Fatal("len(answer): ", len(in.Answer))
}
}
{
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{Name: "notexist.google.com.", Qtype: dns.TypeAAAA, Qclass: dns.ClassINET}
c := new(dns.Client)
in, _, err := c.Exchange(m1, "127.0.0.1:"+strconv.Itoa(int(serverPort)))
common.Must(err)
if in.Rcode != dns.RcodeNameError {
t.Error("expected NameError, but got ", in.Rcode)
}
}
}
func TestTCPDNSTunnel(t *testing.T) {
port := udp.PickPort()
dnsServer := dns.Server{
Addr: "127.0.0.1:" + port.String(),
Net: "udp",
Handler: &staticHandler{},
}
defer dnsServer.Shutdown()
go dnsServer.ListenAndServe()
time.Sleep(time.Second)
serverPort := tcp.PickPort()
config := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dnsapp.Config{
NameServer: []*dnsapp.NameServer{
{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
},
},
}),
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&policy.Config{}),
},
Inbound: []*core.InboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(port),
Networks: []net.Network{net.Network_TCP},
}),
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&dns_proxy.Config{}),
},
},
}
v, err := core.New(config)
common.Must(err)
common.Must(v.Start())
defer v.Close()
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{Name: "google.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}
c := &dns.Client{
Net: "tcp",
}
in, _, err := c.Exchange(m1, "127.0.0.1:"+serverPort.String())
common.Must(err)
if len(in.Answer) != 1 {
t.Fatal("len(answer): ", len(in.Answer))
}
rr, ok := in.Answer[0].(*dns.A)
if !ok {
t.Fatal("not A record")
}
if r := cmp.Diff(rr.A[:], net.IP{8, 8, 8, 8}); r != "" {
t.Error(r)
}
}
func TestUDP2TCPDNSTunnel(t *testing.T) {
port := tcp.PickPort()
dnsServer := dns.Server{
Addr: "127.0.0.1:" + port.String(),
Net: "tcp",
Handler: &staticHandler{},
}
defer dnsServer.Shutdown()
go dnsServer.ListenAndServe()
time.Sleep(time.Second)
serverPort := tcp.PickPort()
config := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dnsapp.Config{
NameServer: []*dnsapp.NameServer{
{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: uint32(port),
},
},
},
}),
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&policy.Config{}),
},
Inbound: []*core.InboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(port),
Networks: []net.Network{net.Network_TCP},
}),
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&dns_proxy.Config{
Server: &net.Endpoint{
Network: net.Network_TCP,
},
}),
},
},
}
v, err := core.New(config)
common.Must(err)
common.Must(v.Start())
defer v.Close()
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{Name: "google.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET}
c := &dns.Client{
Net: "tcp",
}
in, _, err := c.Exchange(m1, "127.0.0.1:"+serverPort.String())
common.Must(err)
if len(in.Answer) != 1 {
t.Fatal("len(answer): ", len(in.Answer))
}
rr, ok := in.Answer[0].(*dns.A)
if !ok {
t.Fatal("not A record")
}
if r := cmp.Diff(rr.A[:], net.IP{8, 8, 8, 8}); r != "" {
t.Error(r)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/dns/errors.generated.go | proxy/dns/errors.generated.go | package dns
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/dns/dns.go | proxy/dns/dns.go | package dns
import (
"context"
"io"
"sync"
"time"
"golang.org/x/net/dns/dnsmessage"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
dns_proto "github.com/v2fly/v2ray-core/v5/common/protocol/dns"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/strmatcher"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/dns"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
h := new(Handler)
if err := core.RequireFeatures(ctx, func(dnsClient dns.Client, policyManager policy.Manager) error {
return h.Init(config.(*Config), dnsClient, policyManager)
}); err != nil {
return nil, err
}
return h, nil
}))
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedServer := config.(*SimplifiedConfig)
_ = simplifiedServer
fullConfig := &Config{}
fullConfig.OverrideResponseTtl = simplifiedServer.OverrideResponseTtl
fullConfig.ResponseTtl = simplifiedServer.ResponseTtl
return common.CreateObject(ctx, fullConfig)
}))
}
type ownLinkVerifier interface {
IsOwnLink(ctx context.Context) bool
}
type Handler struct {
client dns.Client
ipv4Lookup dns.IPv4Lookup
ipv6Lookup dns.IPv6Lookup
ownLinkVerifier ownLinkVerifier
server net.Destination
timeout time.Duration
config *Config
nonIPQuery string
}
func (h *Handler) Init(config *Config, dnsClient dns.Client, policyManager policy.Manager) error {
// Enable FakeDNS for DNS outbound
if clientWithFakeDNS, ok := dnsClient.(dns.ClientWithFakeDNS); ok {
dnsClient = clientWithFakeDNS.AsFakeDNSClient()
}
h.client = dnsClient
h.timeout = policyManager.ForLevel(config.UserLevel).Timeouts.ConnectionIdle
if ipv4lookup, ok := dnsClient.(dns.IPv4Lookup); ok {
h.ipv4Lookup = ipv4lookup
} else {
return newError("dns.Client doesn't implement IPv4Lookup")
}
if ipv6lookup, ok := dnsClient.(dns.IPv6Lookup); ok {
h.ipv6Lookup = ipv6lookup
} else {
return newError("dns.Client doesn't implement IPv6Lookup")
}
if v, ok := dnsClient.(ownLinkVerifier); ok {
h.ownLinkVerifier = v
}
if config.Server != nil {
h.server = config.Server.AsDestination()
}
h.config = config
h.nonIPQuery = config.Non_IPQuery
return nil
}
func (h *Handler) isOwnLink(ctx context.Context) bool {
return h.ownLinkVerifier != nil && h.ownLinkVerifier.IsOwnLink(ctx)
}
func parseIPQuery(b []byte) (r bool, domain string, id uint16, qType dnsmessage.Type) {
var parser dnsmessage.Parser
header, err := parser.Start(b)
if err != nil {
newError("parser start").Base(err).WriteToLog()
return
}
id = header.ID
q, err := parser.Question()
if err != nil {
newError("question").Base(err).WriteToLog()
return
}
qType = q.Type
if qType != dnsmessage.TypeA && qType != dnsmessage.TypeAAAA {
return
}
domain = q.Name.String()
r = true
return
}
// Process implements proxy.Outbound.
func (h *Handler) Process(ctx context.Context, link *transport.Link, d internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("invalid outbound")
}
srcNetwork := outbound.Target.Network
dest := outbound.Target
if h.server.Network != net.Network_Unknown {
dest.Network = h.server.Network
}
if h.server.Address != nil {
dest.Address = h.server.Address
}
if h.server.Port != 0 {
dest.Port = h.server.Port
}
newError("handling DNS traffic to ", dest).WriteToLog(session.ExportIDToError(ctx))
conn := &outboundConn{
dialer: func() (internet.Connection, error) {
return d.Dial(ctx, dest)
},
connReady: make(chan struct{}, 1),
}
var reader dns_proto.MessageReader
var writer dns_proto.MessageWriter
if srcNetwork == net.Network_TCP {
reader = dns_proto.NewTCPReader(link.Reader)
writer = &dns_proto.TCPWriter{
Writer: link.Writer,
}
} else {
reader = &dns_proto.UDPReader{
Reader: link.Reader,
}
writer = &dns_proto.UDPWriter{
Writer: link.Writer,
}
}
var connReader dns_proto.MessageReader
var connWriter dns_proto.MessageWriter
if dest.Network == net.Network_TCP {
connReader = dns_proto.NewTCPReader(buf.NewReader(conn))
connWriter = &dns_proto.TCPWriter{
Writer: buf.NewWriter(conn),
}
} else {
connReader = &dns_proto.UDPReader{
Reader: buf.NewPacketReader(conn),
}
connWriter = &dns_proto.UDPWriter{
Writer: buf.NewWriter(conn),
}
}
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, h.timeout)
request := func() error {
defer conn.Close()
for {
b, err := reader.ReadMessage()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
timer.Update()
if !h.isOwnLink(ctx) {
isIPQuery, domain, id, qType := parseIPQuery(b.Bytes())
if isIPQuery || h.nonIPQuery != "drop" {
if domain, err := strmatcher.ToDomain(domain); err == nil {
go h.handleIPQuery(id, qType, domain, writer)
} else {
h.handleDNSError(id, dnsmessage.RCodeFormatError, writer)
}
} else {
h.handleDNSError(id, dnsmessage.RCodeNotImplemented, writer)
}
} else if err := connWriter.WriteMessage(b); err != nil {
return err
}
}
}
response := func() error {
for {
b, err := connReader.ReadMessage()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
timer.Update()
if err := writer.WriteMessage(b); err != nil {
return err
}
}
}
if err := task.Run(ctx, request, response); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
func (h *Handler) handleIPQuery(id uint16, qType dnsmessage.Type, domain string, writer dns_proto.MessageWriter) {
var ips []net.IP
var err error
var ttl uint32 = 600
if h.config.OverrideResponseTtl {
ttl = h.config.ResponseTtl
}
switch qType {
case dnsmessage.TypeA:
ips, err = h.ipv4Lookup.LookupIPv4(domain)
case dnsmessage.TypeAAAA:
ips, err = h.ipv6Lookup.LookupIPv6(domain)
}
rcode := dns.RCodeFromError(err)
if rcode == 0 && len(ips) == 0 && err != dns.ErrEmptyResponse {
newError("ip query").Base(err).WriteToLog()
return
}
b := buf.New()
rawBytes := b.Extend(buf.Size)
builder := dnsmessage.NewBuilder(rawBytes[:0], dnsmessage.Header{
ID: id,
RCode: dnsmessage.RCode(rcode),
RecursionAvailable: true,
RecursionDesired: true,
Response: true,
})
builder.EnableCompression()
common.Must(builder.StartQuestions())
common.Must(builder.Question(dnsmessage.Question{
Name: dnsmessage.MustNewName(domain),
Class: dnsmessage.ClassINET,
Type: qType,
}))
common.Must(builder.StartAnswers())
rHeader := dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(domain), Class: dnsmessage.ClassINET, TTL: ttl}
for _, ip := range ips {
if len(ip) == net.IPv4len {
var r dnsmessage.AResource
copy(r.A[:], ip)
common.Must(builder.AResource(rHeader, r))
} else {
var r dnsmessage.AAAAResource
copy(r.AAAA[:], ip)
common.Must(builder.AAAAResource(rHeader, r))
}
}
msgBytes, err := builder.Finish()
if err != nil {
newError("pack message").Base(err).WriteToLog()
b.Release()
return
}
b.Resize(0, int32(len(msgBytes)))
if err := writer.WriteMessage(b); err != nil {
newError("write IP answer").Base(err).WriteToLog()
}
}
func (h *Handler) handleDNSError(id uint16, rCode dnsmessage.RCode, writer dns_proto.MessageWriter) {
var err error
b := buf.New()
rawBytes := b.Extend(buf.Size)
builder := dnsmessage.NewBuilder(rawBytes[:0], dnsmessage.Header{
ID: id,
RCode: rCode,
RecursionAvailable: true,
RecursionDesired: true,
Response: true,
})
builder.EnableCompression()
common.Must(builder.StartQuestions())
common.Must(builder.StartAnswers())
msgBytes, err := builder.Finish()
if err != nil {
newError("pack message").Base(err).WriteToLog()
b.Release()
return
}
b.Resize(0, int32(len(msgBytes)))
if err := writer.WriteMessage(b); err != nil {
newError("write IP answer").Base(err).WriteToLog()
}
}
type outboundConn struct {
access sync.Mutex
dialer func() (internet.Connection, error)
conn net.Conn
connReady chan struct{}
}
func (c *outboundConn) dial() error {
conn, err := c.dialer()
if err != nil {
return err
}
c.conn = conn
c.connReady <- struct{}{}
return nil
}
func (c *outboundConn) Write(b []byte) (int, error) {
c.access.Lock()
if c.conn == nil {
if err := c.dial(); err != nil {
c.access.Unlock()
newError("failed to dial outbound connection").Base(err).AtWarning().WriteToLog()
return len(b), nil
}
}
c.access.Unlock()
return c.conn.Write(b)
}
func (c *outboundConn) Read(b []byte) (int, error) {
var conn net.Conn
c.access.Lock()
conn = c.conn
c.access.Unlock()
if conn == nil {
_, open := <-c.connReady
if !open {
return 0, io.EOF
}
conn = c.conn
}
return conn.Read(b)
}
func (c *outboundConn) Close() error {
c.access.Lock()
close(c.connReady)
if c.conn != nil {
c.conn.Close()
}
c.access.Unlock()
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/dns/config.pb.go | proxy/dns/config.pb.go | package dns
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Server is the DNS server address. If specified, this address overrides the
// original one.
Server *net.Endpoint `protobuf:"bytes,1,opt,name=server,proto3" json:"server,omitempty"`
UserLevel uint32 `protobuf:"varint,2,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
OverrideResponseTtl bool `protobuf:"varint,4,opt,name=override_response_ttl,json=overrideResponseTtl,proto3" json:"override_response_ttl,omitempty"`
ResponseTtl uint32 `protobuf:"varint,3,opt,name=response_ttl,json=responseTtl,proto3" json:"response_ttl,omitempty"`
Non_IPQuery string `protobuf:"bytes,5,opt,name=non_IP_query,json=nonIPQuery,proto3" json:"non_IP_query,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_dns_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_dns_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_dns_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetServer() *net.Endpoint {
if x != nil {
return x.Server
}
return nil
}
func (x *Config) GetUserLevel() uint32 {
if x != nil {
return x.UserLevel
}
return 0
}
func (x *Config) GetOverrideResponseTtl() bool {
if x != nil {
return x.OverrideResponseTtl
}
return false
}
func (x *Config) GetResponseTtl() uint32 {
if x != nil {
return x.ResponseTtl
}
return 0
}
func (x *Config) GetNon_IPQuery() string {
if x != nil {
return x.Non_IPQuery
}
return ""
}
type SimplifiedConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
OverrideResponseTtl bool `protobuf:"varint,4,opt,name=override_response_ttl,json=overrideResponseTtl,proto3" json:"override_response_ttl,omitempty"`
ResponseTtl uint32 `protobuf:"varint,3,opt,name=response_ttl,json=responseTtl,proto3" json:"response_ttl,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SimplifiedConfig) Reset() {
*x = SimplifiedConfig{}
mi := &file_proxy_dns_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SimplifiedConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SimplifiedConfig) ProtoMessage() {}
func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_dns_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead.
func (*SimplifiedConfig) Descriptor() ([]byte, []int) {
return file_proxy_dns_config_proto_rawDescGZIP(), []int{1}
}
func (x *SimplifiedConfig) GetOverrideResponseTtl() bool {
if x != nil {
return x.OverrideResponseTtl
}
return false
}
func (x *SimplifiedConfig) GetResponseTtl() uint32 {
if x != nil {
return x.ResponseTtl
}
return 0
}
var File_proxy_dns_config_proto protoreflect.FileDescriptor
const file_proxy_dns_config_proto_rawDesc = "" +
"\n" +
"\x16proxy/dns/config.proto\x12\x14v2ray.core.proxy.dns\x1a\x1ccommon/net/destination.proto\x1a common/protoext/extensions.proto\"\xd9\x01\n" +
"\x06Config\x127\n" +
"\x06server\x18\x01 \x01(\v2\x1f.v2ray.core.common.net.EndpointR\x06server\x12\x1d\n" +
"\n" +
"user_level\x18\x02 \x01(\rR\tuserLevel\x122\n" +
"\x15override_response_ttl\x18\x04 \x01(\bR\x13overrideResponseTtl\x12!\n" +
"\fresponse_ttl\x18\x03 \x01(\rR\vresponseTtl\x12 \n" +
"\fnon_IP_query\x18\x05 \x01(\tR\n" +
"nonIPQuery\"~\n" +
"\x10SimplifiedConfig\x122\n" +
"\x15override_response_ttl\x18\x04 \x01(\bR\x13overrideResponseTtl\x12!\n" +
"\fresponse_ttl\x18\x03 \x01(\rR\vresponseTtl:\x13\x82\xb5\x18\x0f\n" +
"\boutbound\x12\x03dnsB]\n" +
"\x18com.v2ray.core.proxy.dnsP\x01Z(github.com/v2fly/v2ray-core/v5/proxy/dns\xaa\x02\x14V2Ray.Core.Proxy.Dnsb\x06proto3"
var (
file_proxy_dns_config_proto_rawDescOnce sync.Once
file_proxy_dns_config_proto_rawDescData []byte
)
func file_proxy_dns_config_proto_rawDescGZIP() []byte {
file_proxy_dns_config_proto_rawDescOnce.Do(func() {
file_proxy_dns_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_dns_config_proto_rawDesc), len(file_proxy_dns_config_proto_rawDesc)))
})
return file_proxy_dns_config_proto_rawDescData
}
var file_proxy_dns_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_proxy_dns_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.proxy.dns.Config
(*SimplifiedConfig)(nil), // 1: v2ray.core.proxy.dns.SimplifiedConfig
(*net.Endpoint)(nil), // 2: v2ray.core.common.net.Endpoint
}
var file_proxy_dns_config_proto_depIdxs = []int32{
2, // 0: v2ray.core.proxy.dns.Config.server:type_name -> v2ray.core.common.net.Endpoint
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_proxy_dns_config_proto_init() }
func file_proxy_dns_config_proto_init() {
if File_proxy_dns_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_dns_config_proto_rawDesc), len(file_proxy_dns_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_dns_config_proto_goTypes,
DependencyIndexes: file_proxy_dns_config_proto_depIdxs,
MessageInfos: file_proxy_dns_config_proto_msgTypes,
}.Build()
File_proxy_dns_config_proto = out.File
file_proxy_dns_config_proto_goTypes = nil
file_proxy_dns_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/hysteria2/errors.generated.go | proxy/hysteria2/errors.generated.go | package hysteria2
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/hysteria2/client.go | proxy/hysteria2/client.go | package hysteria2
import (
"context"
hyProtocol "github.com/v2fly/hysteria/core/v2/international/protocol"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/proxy"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
hyTransport "github.com/v2fly/v2ray-core/v5/transport/internet/hysteria2"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
// Client is an inbound handler
type Client struct {
serverPicker protocol.ServerPicker
policyManager policy.Manager
}
// NewClient create a new client.
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
serverList := protocol.NewServerList()
for _, rec := range config.Server {
s, err := protocol.NewServerSpecFromPB(rec)
if err != nil {
return nil, newError("failed to parse server spec").Base(err)
}
serverList.AddServer(s)
}
if serverList.Size() == 0 {
return nil, newError("0 server")
}
v := core.MustFromContext(ctx)
client := &Client{
serverPicker: protocol.NewRoundRobinServerPicker(serverList),
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
}
return client, nil
}
// Process implements OutboundHandler.Process().
func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified")
}
destination := outbound.Target
network := destination.Network
var server *protocol.ServerSpec
var conn internet.Connection
err := retry.ExponentialBackoff(5, 100).On(func() error {
server = c.serverPicker.PickServer()
rawConn, err := dialer.Dial(ctx, server.Destination())
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
return newError("failed to find an available destination").AtWarning().Base(err)
}
newError("tunneling request to ", destination, " via ", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
defer conn.Close()
iConn := conn
if statConn, ok := conn.(*internet.StatCouterConnection); ok {
iConn = statConn.Connection // will not count the UDP traffic.
}
hyConn, IsHy2Transport := iConn.(*hyTransport.HyConn)
if !IsHy2Transport && network == net.Network_UDP {
// hysteria2 need to use udp extension to proxy UDP.
return newError(hyTransport.CanNotUseUDPExtension)
}
user := server.PickUser()
userLevel := uint32(0)
if user != nil {
userLevel = user.Level
}
sessionPolicy := c.policyManager.ForLevel(userLevel)
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil {
postRequest := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
var buffer [2048]byte
n, addr, err := packetConn.ReadFrom(buffer[:])
if err != nil {
return newError("failed to read a packet").Base(err)
}
dest := net.DestinationFromAddr(addr)
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
connWriter := &ConnWriter{Writer: bufferWriter, Target: dest}
packetWriter := &PacketWriter{Writer: connWriter, Target: dest, HyConn: hyConn}
// write some request payload to buffer
if _, err := packetWriter.WriteTo(buffer[:n], addr); err != nil {
return newError("failed to write a request payload").Base(err)
}
// Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer
if err = bufferWriter.SetBuffered(false); err != nil {
return newError("failed to flush payload").Base(err).AtWarning()
}
return udp.CopyPacketConn(packetWriter, packetConn, udp.UpdateActivity(timer))
}
getResponse := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
packetReader := &PacketReader{Reader: conn, HyConn: hyConn}
packetConnectionReader := &PacketConnectionReader{reader: packetReader}
return udp.CopyPacketConn(packetConn, packetConnectionReader, udp.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
postRequest := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
var bodyWriter buf.Writer
bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
connWriter := &ConnWriter{Writer: bufferWriter, Target: destination}
bodyWriter = connWriter
if network == net.Network_UDP {
bodyWriter = &PacketWriter{Writer: connWriter, Target: destination, HyConn: hyConn}
} else {
// write some request payload to buffer
err = buf.CopyOnceTimeout(link.Reader, bodyWriter, proxy.FirstPayloadTimeout)
switch err {
case buf.ErrNotTimeoutReader, buf.ErrReadTimeout:
if err := connWriter.WriteTCPHeader(); err != nil {
return newError("failed to write request header").Base(err).AtWarning()
}
case nil:
default:
return newError("failed to write a request payload").Base(err).AtWarning()
}
// Flush; bufferWriter.WriteMultiBuffer now is bufferWriter.writer.WriteMultiBuffer
if err = bufferWriter.SetBuffered(false); err != nil {
return newError("failed to flush payload").Base(err).AtWarning()
}
}
if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transfer request payload").Base(err).AtInfo()
}
return nil
}
getResponse := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
var reader buf.Reader
if network == net.Network_UDP {
reader = &PacketReader{
Reader: conn, HyConn: hyConn,
}
} else {
ok, msg, err := hyProtocol.ReadTCPResponse(conn)
if err != nil {
return err
}
if !ok {
return newError(msg)
}
reader = buf.NewReader(conn)
}
return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
}
responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewClient(ctx, config.(*ClientConfig))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/hysteria2/config.go | proxy/hysteria2/config.go | package hysteria2
import (
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
// MemoryAccount is an account type converted from Account.
type MemoryAccount struct{}
// AsAccount implements protocol.AsAccount.
func (a *Account) AsAccount() (protocol.Account, error) {
return &MemoryAccount{}, nil
}
// Equals implements protocol.Account.Equals().
func (a *MemoryAccount) Equals(another protocol.Account) bool {
return false
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/hysteria2/protocol.go | proxy/hysteria2/protocol.go | package hysteria2
import (
"io"
"math/rand"
"github.com/apernet/quic-go/quicvarint"
hyProtocol "github.com/v2fly/hysteria/core/v2/international/protocol"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
hyTransport "github.com/v2fly/v2ray-core/v5/transport/internet/hysteria2"
)
const (
paddingChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
// ConnWriter is TCP Connection Writer Wrapper
type ConnWriter struct {
io.Writer
Target net.Destination
TCPHeaderSent bool
}
// Write implements io.Writer
func (c *ConnWriter) Write(p []byte) (n int, err error) {
if !c.TCPHeaderSent {
if err := c.writeTCPHeader(); err != nil {
return 0, newError("failed to write request header").Base(err)
}
}
return c.Writer.Write(p)
}
// WriteMultiBuffer implements buf.Writer
func (c *ConnWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
defer buf.ReleaseMulti(mb)
for _, b := range mb {
if !b.IsEmpty() {
if _, err := c.Write(b.Bytes()); err != nil {
return err
}
}
}
return nil
}
func (c *ConnWriter) WriteTCPHeader() error {
if !c.TCPHeaderSent {
if err := c.writeTCPHeader(); err != nil {
return err
}
}
return nil
}
func QuicLen(s int) int {
return quicvarint.Len(uint64(s))
}
func (c *ConnWriter) writeTCPHeader() error {
c.TCPHeaderSent = true
paddingLen := 64 + rand.Intn(512-64)
padding := make([]byte, paddingLen)
for i := range padding {
padding[i] = paddingChars[rand.Intn(len(paddingChars))]
}
addressAndPort := c.Target.NetAddr()
addressLen := len(addressAndPort)
if addressLen > hyProtocol.MaxAddressLength {
return newError("address length too large: ", addressLen)
}
size := QuicLen(addressLen) + addressLen + QuicLen(paddingLen) + paddingLen
buf := make([]byte, size)
i := hyProtocol.VarintPut(buf, uint64(addressLen))
i += copy(buf[i:], addressAndPort)
i += hyProtocol.VarintPut(buf[i:], uint64(paddingLen))
copy(buf[i:], padding)
_, err := c.Writer.Write(buf)
return err
}
// PacketWriter UDP Connection Writer Wrapper
type PacketWriter struct {
io.Writer
HyConn *hyTransport.HyConn
Target net.Destination
}
// WriteMultiBuffer implements buf.Writer
func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
for _, b := range mb {
if b.IsEmpty() {
continue
}
if _, err := w.writePacket(b.Bytes(), w.Target); err != nil {
buf.ReleaseMulti(mb)
return err
}
}
return nil
}
// WriteMultiBufferWithMetadata writes udp packet with destination specified
func (w *PacketWriter) WriteMultiBufferWithMetadata(mb buf.MultiBuffer, dest net.Destination) error {
for _, b := range mb {
if b.IsEmpty() {
continue
}
if _, err := w.writePacket(b.Bytes(), dest); err != nil {
buf.ReleaseMulti(mb)
return err
}
}
return nil
}
func (w *PacketWriter) WriteTo(payload []byte, addr net.Addr) (int, error) {
dest := net.DestinationFromAddr(addr)
return w.writePacket(payload, dest)
}
func (w *PacketWriter) writePacket(payload []byte, dest net.Destination) (int, error) {
return w.HyConn.WritePacket(payload, dest)
}
// ConnReader is TCP Connection Reader Wrapper
type ConnReader struct {
io.Reader
Target net.Destination
}
// Read implements io.Reader
func (c *ConnReader) Read(p []byte) (int, error) {
return c.Reader.Read(p)
}
// ReadMultiBuffer implements buf.Reader
func (c *ConnReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
b := buf.New()
_, err := b.ReadFrom(c)
if err != nil {
return nil, err
}
return buf.MultiBuffer{b}, nil
}
// PacketPayload combines udp payload and destination
type PacketPayload struct {
Target net.Destination
Buffer buf.MultiBuffer
}
// PacketReader is UDP Connection Reader Wrapper
type PacketReader struct {
io.Reader
HyConn *hyTransport.HyConn
}
// ReadMultiBuffer implements buf.Reader
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
p, err := r.ReadMultiBufferWithMetadata()
if p != nil {
return p.Buffer, err
}
return nil, err
}
// ReadMultiBufferWithMetadata reads udp packet with destination
func (r *PacketReader) ReadMultiBufferWithMetadata() (*PacketPayload, error) {
_, data, dest, err := r.HyConn.ReadPacket()
if err != nil {
return nil, err
}
b := buf.FromBytes(data)
return &PacketPayload{Target: *dest, Buffer: buf.MultiBuffer{b}}, nil
}
type PacketConnectionReader struct {
reader *PacketReader
payload *PacketPayload
}
func (r *PacketConnectionReader) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
if r.payload == nil || r.payload.Buffer.IsEmpty() {
r.payload, err = r.reader.ReadMultiBufferWithMetadata()
if err != nil {
return
}
}
addr = &net.UDPAddr{
IP: r.payload.Target.Address.IP(),
Port: int(r.payload.Target.Port),
}
r.payload.Buffer, n = buf.SplitFirstBytes(r.payload.Buffer, p)
return
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/hysteria2/server.go | proxy/hysteria2/server.go | package hysteria2
import (
"context"
"io"
"time"
hyProtocol "github.com/v2fly/hysteria/core/v2/international/protocol"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/errors"
"github.com/v2fly/v2ray-core/v5/common/log"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
udp_proto "github.com/v2fly/v2ray-core/v5/common/protocol/udp"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport/internet"
hyTransport "github.com/v2fly/v2ray-core/v5/transport/internet/hysteria2"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewServer(ctx, config.(*ServerConfig))
}))
}
// Server is an inbound connection handler that handles messages in protocol.
type Server struct {
policyManager policy.Manager
packetEncoding packetaddr.PacketAddrType
}
// NewServer creates a new inbound handler.
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
v := core.MustFromContext(ctx)
server := &Server{
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
packetEncoding: config.PacketEncoding,
}
return server, nil
}
// Network implements proxy.Inbound.Network().
func (s *Server) Network() []net.Network {
return []net.Network{net.Network_TCP, net.Network_UNIX}
}
// Process implements proxy.Inbound.Process().
func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
sid := session.ExportIDToError(ctx)
iConn := conn
if statConn, ok := conn.(*internet.StatCouterConnection); ok {
iConn = statConn.Connection // will not count the UDP traffic.
}
hyConn, IsHy2Transport := iConn.(*hyTransport.HyConn)
if IsHy2Transport && hyConn.IsUDPExtension {
network = net.Network_UDP
}
if !IsHy2Transport && network == net.Network_UDP {
return newError(hyTransport.CanNotUseUDPExtension)
}
sessionPolicy := s.policyManager.ForLevel(0)
if err := conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
return newError("unable to set read deadline").Base(err).AtWarning()
}
bufferedReader := &buf.BufferedReader{
Reader: buf.NewReader(conn),
}
clientReader := &ConnReader{Reader: bufferedReader}
if err := conn.SetReadDeadline(time.Time{}); err != nil {
return newError("unable to set read deadline").Base(err).AtWarning()
}
if network == net.Network_UDP { // handle udp request
return s.handleUDPPayload(ctx,
&PacketReader{Reader: clientReader, HyConn: hyConn},
&PacketWriter{Writer: conn, HyConn: hyConn}, dispatcher)
}
var reqAddr string
var err error
reqAddr, err = hyProtocol.ReadTCPRequest(conn)
if err != nil {
return newError("failed to parse header").Base(err)
}
err = hyProtocol.WriteTCPResponse(conn, true, "")
if err != nil {
return newError("failed to send response").Base(err)
}
address, stringPort, err := net.SplitHostPort(reqAddr)
if err != nil {
return err
}
port, err := net.PortFromString(stringPort)
if err != nil {
return err
}
destination := net.Destination{Network: network, Address: net.ParseAddress(address), Port: port}
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
}
sessionPolicy = s.policyManager.ForLevel(0)
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: conn.RemoteAddr(),
To: destination,
Status: log.AccessAccepted,
Reason: "",
})
newError("received request for ", destination).WriteToLog(sid)
return s.handleConnection(ctx, sessionPolicy, destination, clientReader, buf.NewWriter(conn), dispatcher)
}
func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Session,
destination net.Destination,
clientReader buf.Reader,
clientWriter buf.Writer, dispatcher routing.Dispatcher,
) error {
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
link, err := dispatcher.Dispatch(ctx, destination)
if err != nil {
return newError("failed to dispatch request to ", destination).Base(err)
}
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
if err := buf.Copy(clientReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transfer request").Base(err)
}
return nil
}
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
if err := buf.Copy(link.Reader, clientWriter, buf.UpdateActivity(timer)); err != nil {
return newError("failed to write response").Base(err)
}
return nil
}
requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Must(common.Interrupt(link.Reader))
common.Must(common.Interrupt(link.Writer))
return newError("connection ends").Base(err)
}
return nil
}
func (s *Server) handleUDPPayload(ctx context.Context, clientReader *PacketReader, clientWriter *PacketWriter, dispatcher routing.Dispatcher) error {
udpDispatcherConstructor := udp.NewSplitDispatcher
switch s.packetEncoding {
case packetaddr.PacketAddrType_None:
case packetaddr.PacketAddrType_Packet:
packetAddrDispatcherFactory := udp.NewPacketAddrDispatcherCreator(ctx)
udpDispatcherConstructor = packetAddrDispatcherFactory.NewPacketAddrDispatcher
}
udpServer := udpDispatcherConstructor(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
if err := clientWriter.WriteMultiBufferWithMetadata(buf.MultiBuffer{packet.Payload}, packet.Source); err != nil {
newError("failed to write response").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx))
}
})
inbound := session.InboundFromContext(ctx)
for {
select {
case <-ctx.Done():
return nil
default:
p, err := clientReader.ReadMultiBufferWithMetadata()
if err != nil {
if errors.Cause(err) != io.EOF {
return newError("unexpected EOF").Base(err)
}
return nil
}
currentPacketCtx := ctx
currentPacketCtx = log.ContextWithAccessMessage(currentPacketCtx, &log.AccessMessage{
From: inbound.Source,
To: p.Target,
Status: log.AccessAccepted,
Reason: "",
})
newError("tunnelling request to ", p.Target).WriteToLog(session.ExportIDToError(ctx))
for _, b := range p.Buffer {
udpServer.Dispatch(currentPacketCtx, p.Target, b)
}
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/hysteria2/config.pb.go | proxy/hysteria2/config.pb.go | package hysteria2
import (
packetaddr "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
protocol "github.com/v2fly/v2ray-core/v5/common/protocol"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Account struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Account) Reset() {
*x = Account{}
mi := &file_proxy_hysteria2_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Account) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Account) ProtoMessage() {}
func (x *Account) ProtoReflect() protoreflect.Message {
mi := &file_proxy_hysteria2_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Account.ProtoReflect.Descriptor instead.
func (*Account) Descriptor() ([]byte, []int) {
return file_proxy_hysteria2_config_proto_rawDescGZIP(), []int{0}
}
type ClientConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Server []*protocol.ServerEndpoint `protobuf:"bytes,1,rep,name=server,proto3" json:"server,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClientConfig) Reset() {
*x = ClientConfig{}
mi := &file_proxy_hysteria2_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ClientConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ClientConfig) ProtoMessage() {}
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_hysteria2_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
func (*ClientConfig) Descriptor() ([]byte, []int) {
return file_proxy_hysteria2_config_proto_rawDescGZIP(), []int{1}
}
func (x *ClientConfig) GetServer() []*protocol.ServerEndpoint {
if x != nil {
return x.Server
}
return nil
}
type ServerConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
PacketEncoding packetaddr.PacketAddrType `protobuf:"varint,1,opt,name=packet_encoding,json=packetEncoding,proto3,enum=v2ray.core.net.packetaddr.PacketAddrType" json:"packet_encoding,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerConfig) Reset() {
*x = ServerConfig{}
mi := &file_proxy_hysteria2_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerConfig) ProtoMessage() {}
func (x *ServerConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_hysteria2_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerConfig.ProtoReflect.Descriptor instead.
func (*ServerConfig) Descriptor() ([]byte, []int) {
return file_proxy_hysteria2_config_proto_rawDescGZIP(), []int{2}
}
func (x *ServerConfig) GetPacketEncoding() packetaddr.PacketAddrType {
if x != nil {
return x.PacketEncoding
}
return packetaddr.PacketAddrType(0)
}
var File_proxy_hysteria2_config_proto protoreflect.FileDescriptor
const file_proxy_hysteria2_config_proto_rawDesc = "" +
"\n" +
"\x1cproxy/hysteria2/config.proto\x12\x1av2ray.core.proxy.hysteria2\x1a\"common/net/packetaddr/config.proto\x1a!common/protocol/server_spec.proto\x1a common/protoext/extensions.proto\"\t\n" +
"\aAccount\"m\n" +
"\fClientConfig\x12B\n" +
"\x06server\x18\x01 \x03(\v2*.v2ray.core.common.protocol.ServerEndpointR\x06server:\x19\x82\xb5\x18\x15\n" +
"\boutbound\x12\thysteria2\"|\n" +
"\fServerConfig\x12R\n" +
"\x0fpacket_encoding\x18\x01 \x01(\x0e2).v2ray.core.net.packetaddr.PacketAddrTypeR\x0epacketEncoding:\x18\x82\xb5\x18\x14\n" +
"\ainbound\x12\thysteria2Bo\n" +
"\x1ecom.v2ray.core.proxy.hysteria2P\x01Z.github.com/v2fly/v2ray-core/v5/proxy/hysteria2\xaa\x02\x1aV2Ray.Core.Proxy.Hysteria2b\x06proto3"
var (
file_proxy_hysteria2_config_proto_rawDescOnce sync.Once
file_proxy_hysteria2_config_proto_rawDescData []byte
)
func file_proxy_hysteria2_config_proto_rawDescGZIP() []byte {
file_proxy_hysteria2_config_proto_rawDescOnce.Do(func() {
file_proxy_hysteria2_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_hysteria2_config_proto_rawDesc), len(file_proxy_hysteria2_config_proto_rawDesc)))
})
return file_proxy_hysteria2_config_proto_rawDescData
}
var file_proxy_hysteria2_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_proxy_hysteria2_config_proto_goTypes = []any{
(*Account)(nil), // 0: v2ray.core.proxy.hysteria2.Account
(*ClientConfig)(nil), // 1: v2ray.core.proxy.hysteria2.ClientConfig
(*ServerConfig)(nil), // 2: v2ray.core.proxy.hysteria2.ServerConfig
(*protocol.ServerEndpoint)(nil), // 3: v2ray.core.common.protocol.ServerEndpoint
(packetaddr.PacketAddrType)(0), // 4: v2ray.core.net.packetaddr.PacketAddrType
}
var file_proxy_hysteria2_config_proto_depIdxs = []int32{
3, // 0: v2ray.core.proxy.hysteria2.ClientConfig.server:type_name -> v2ray.core.common.protocol.ServerEndpoint
4, // 1: v2ray.core.proxy.hysteria2.ServerConfig.packet_encoding:type_name -> v2ray.core.net.packetaddr.PacketAddrType
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_proxy_hysteria2_config_proto_init() }
func file_proxy_hysteria2_config_proto_init() {
if File_proxy_hysteria2_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_hysteria2_config_proto_rawDesc), len(file_proxy_hysteria2_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_hysteria2_config_proto_goTypes,
DependencyIndexes: file_proxy_hysteria2_config_proto_depIdxs,
MessageInfos: file_proxy_hysteria2_config_proto_msgTypes,
}.Build()
File_proxy_hysteria2_config_proto = out.File
file_proxy_hysteria2_config_proto_goTypes = nil
file_proxy_hysteria2_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/hysteria2/hysteria2.go | proxy/hysteria2/hysteria2.go | package hysteria2
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/dokodemo/errors.generated.go | proxy/dokodemo/errors.generated.go | package dokodemo
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/dokodemo/config.go | proxy/dokodemo/config.go | package dokodemo
import (
"github.com/v2fly/v2ray-core/v5/common/net"
)
// GetPredefinedAddress returns the defined address from proto config. Null if address is not valid.
func (v *Config) GetPredefinedAddress() net.Address {
addr := v.Address.AsAddress()
if addr == nil {
return nil
}
return addr
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/dokodemo/config.pb.go | proxy/dokodemo/config.pb.go | package dokodemo
import (
net "github.com/v2fly/v2ray-core/v5/common/net"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`
// List of networks that the Dokodemo accepts.
// Deprecated. Use networks.
//
// Deprecated: Marked as deprecated in proxy/dokodemo/config.proto.
NetworkList *net.NetworkList `protobuf:"bytes,3,opt,name=network_list,json=networkList,proto3" json:"network_list,omitempty"`
// List of networks that the Dokodemo accepts.
Networks []net.Network `protobuf:"varint,7,rep,packed,name=networks,proto3,enum=v2ray.core.common.net.Network" json:"networks,omitempty"`
// Deprecated: Marked as deprecated in proxy/dokodemo/config.proto.
Timeout uint32 `protobuf:"varint,4,opt,name=timeout,proto3" json:"timeout,omitempty"`
FollowRedirect bool `protobuf:"varint,5,opt,name=follow_redirect,json=followRedirect,proto3" json:"follow_redirect,omitempty"`
UserLevel uint32 `protobuf:"varint,6,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_dokodemo_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_dokodemo_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_dokodemo_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *Config) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
// Deprecated: Marked as deprecated in proxy/dokodemo/config.proto.
func (x *Config) GetNetworkList() *net.NetworkList {
if x != nil {
return x.NetworkList
}
return nil
}
func (x *Config) GetNetworks() []net.Network {
if x != nil {
return x.Networks
}
return nil
}
// Deprecated: Marked as deprecated in proxy/dokodemo/config.proto.
func (x *Config) GetTimeout() uint32 {
if x != nil {
return x.Timeout
}
return 0
}
func (x *Config) GetFollowRedirect() bool {
if x != nil {
return x.FollowRedirect
}
return false
}
func (x *Config) GetUserLevel() uint32 {
if x != nil {
return x.UserLevel
}
return 0
}
type SimplifiedConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
Address *net.IPOrDomain `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`
Networks *net.NetworkList `protobuf:"bytes,3,opt,name=networks,proto3" json:"networks,omitempty"`
FollowRedirect bool `protobuf:"varint,4,opt,name=follow_redirect,json=followRedirect,proto3" json:"follow_redirect,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SimplifiedConfig) Reset() {
*x = SimplifiedConfig{}
mi := &file_proxy_dokodemo_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SimplifiedConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SimplifiedConfig) ProtoMessage() {}
func (x *SimplifiedConfig) ProtoReflect() protoreflect.Message {
mi := &file_proxy_dokodemo_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SimplifiedConfig.ProtoReflect.Descriptor instead.
func (*SimplifiedConfig) Descriptor() ([]byte, []int) {
return file_proxy_dokodemo_config_proto_rawDescGZIP(), []int{1}
}
func (x *SimplifiedConfig) GetAddress() *net.IPOrDomain {
if x != nil {
return x.Address
}
return nil
}
func (x *SimplifiedConfig) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
func (x *SimplifiedConfig) GetNetworks() *net.NetworkList {
if x != nil {
return x.Networks
}
return nil
}
func (x *SimplifiedConfig) GetFollowRedirect() bool {
if x != nil {
return x.FollowRedirect
}
return false
}
var File_proxy_dokodemo_config_proto protoreflect.FileDescriptor
const file_proxy_dokodemo_config_proto_rawDesc = "" +
"\n" +
"\x1bproxy/dokodemo/config.proto\x12\x19v2ray.core.proxy.dokodemo\x1a\x18common/net/address.proto\x1a\x18common/net/network.proto\x1a common/protoext/extensions.proto\"\xc6\x02\n" +
"\x06Config\x12;\n" +
"\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" +
"\x04port\x18\x02 \x01(\rR\x04port\x12I\n" +
"\fnetwork_list\x18\x03 \x01(\v2\".v2ray.core.common.net.NetworkListB\x02\x18\x01R\vnetworkList\x12:\n" +
"\bnetworks\x18\a \x03(\x0e2\x1e.v2ray.core.common.net.NetworkR\bnetworks\x12\x1c\n" +
"\atimeout\x18\x04 \x01(\rB\x02\x18\x01R\atimeout\x12'\n" +
"\x0ffollow_redirect\x18\x05 \x01(\bR\x0efollowRedirect\x12\x1d\n" +
"\n" +
"user_level\x18\x06 \x01(\rR\tuserLevel\"\xea\x01\n" +
"\x10SimplifiedConfig\x12;\n" +
"\aaddress\x18\x01 \x01(\v2!.v2ray.core.common.net.IPOrDomainR\aaddress\x12\x12\n" +
"\x04port\x18\x02 \x01(\rR\x04port\x12>\n" +
"\bnetworks\x18\x03 \x01(\v2\".v2ray.core.common.net.NetworkListR\bnetworks\x12'\n" +
"\x0ffollow_redirect\x18\x04 \x01(\bR\x0efollowRedirect:\x1c\x82\xb5\x18\x18\n" +
"\ainbound\x12\rdokodemo-doorBl\n" +
"\x1dcom.v2ray.core.proxy.dokodemoP\x01Z-github.com/v2fly/v2ray-core/v5/proxy/dokodemo\xaa\x02\x19V2Ray.Core.Proxy.Dokodemob\x06proto3"
var (
file_proxy_dokodemo_config_proto_rawDescOnce sync.Once
file_proxy_dokodemo_config_proto_rawDescData []byte
)
func file_proxy_dokodemo_config_proto_rawDescGZIP() []byte {
file_proxy_dokodemo_config_proto_rawDescOnce.Do(func() {
file_proxy_dokodemo_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_dokodemo_config_proto_rawDesc), len(file_proxy_dokodemo_config_proto_rawDesc)))
})
return file_proxy_dokodemo_config_proto_rawDescData
}
var file_proxy_dokodemo_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_proxy_dokodemo_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.proxy.dokodemo.Config
(*SimplifiedConfig)(nil), // 1: v2ray.core.proxy.dokodemo.SimplifiedConfig
(*net.IPOrDomain)(nil), // 2: v2ray.core.common.net.IPOrDomain
(*net.NetworkList)(nil), // 3: v2ray.core.common.net.NetworkList
(net.Network)(0), // 4: v2ray.core.common.net.Network
}
var file_proxy_dokodemo_config_proto_depIdxs = []int32{
2, // 0: v2ray.core.proxy.dokodemo.Config.address:type_name -> v2ray.core.common.net.IPOrDomain
3, // 1: v2ray.core.proxy.dokodemo.Config.network_list:type_name -> v2ray.core.common.net.NetworkList
4, // 2: v2ray.core.proxy.dokodemo.Config.networks:type_name -> v2ray.core.common.net.Network
2, // 3: v2ray.core.proxy.dokodemo.SimplifiedConfig.address:type_name -> v2ray.core.common.net.IPOrDomain
3, // 4: v2ray.core.proxy.dokodemo.SimplifiedConfig.networks:type_name -> v2ray.core.common.net.NetworkList
5, // [5:5] is the sub-list for method output_type
5, // [5:5] is the sub-list for method input_type
5, // [5:5] is the sub-list for extension type_name
5, // [5:5] is the sub-list for extension extendee
0, // [0:5] is the sub-list for field type_name
}
func init() { file_proxy_dokodemo_config_proto_init() }
func file_proxy_dokodemo_config_proto_init() {
if File_proxy_dokodemo_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_dokodemo_config_proto_rawDesc), len(file_proxy_dokodemo_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_dokodemo_config_proto_goTypes,
DependencyIndexes: file_proxy_dokodemo_config_proto_depIdxs,
MessageInfos: file_proxy_dokodemo_config_proto_msgTypes,
}.Build()
File_proxy_dokodemo_config_proto = out.File
file_proxy_dokodemo_config_proto_goTypes = nil
file_proxy_dokodemo_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/dokodemo/dokodemo.go | proxy/dokodemo/dokodemo.go | package dokodemo
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"sync/atomic"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/log"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
d := new(Door)
err := core.RequireFeatures(ctx, func(pm policy.Manager) error {
return d.Init(config.(*Config), pm, session.SockoptFromContext(ctx))
})
return d, err
}))
common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
simplifiedServer := config.(*SimplifiedConfig)
fullConfig := &Config{
Address: simplifiedServer.Address,
Port: simplifiedServer.Port,
Networks: simplifiedServer.Networks.Network,
FollowRedirect: simplifiedServer.FollowRedirect,
}
return common.CreateObject(ctx, fullConfig)
}))
}
type Door struct {
policyManager policy.Manager
config *Config
address net.Address
port net.Port
sockopt *session.Sockopt
}
// Init initializes the Door instance with necessary parameters.
func (d *Door) Init(config *Config, pm policy.Manager, sockopt *session.Sockopt) error {
if (config.NetworkList == nil || len(config.NetworkList.Network) == 0) && len(config.Networks) == 0 {
return newError("no network specified")
}
d.config = config
d.address = config.GetPredefinedAddress()
d.port = net.Port(config.Port)
d.policyManager = pm
d.sockopt = sockopt
return nil
}
// Network implements proxy.Inbound.
func (d *Door) Network() []net.Network {
if len(d.config.Networks) > 0 {
return d.config.Networks
}
return d.config.NetworkList.GetNetwork()
}
func (d *Door) policy() policy.Session {
config := d.config
p := d.policyManager.ForLevel(config.UserLevel)
if config.Timeout > 0 && config.UserLevel == 0 {
p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second
}
return p
}
type hasHandshakeAddress interface {
HandshakeAddress() net.Address
}
// Process implements proxy.Inbound.
func (d *Door) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error {
newError("processing connection from: ", conn.RemoteAddr()).AtDebug().WriteToLog(session.ExportIDToError(ctx))
dest := net.Destination{
Network: network,
Address: d.address,
Port: d.port,
}
destinationOverridden := false
if d.config.FollowRedirect {
if outbound := session.OutboundFromContext(ctx); outbound != nil && outbound.Target.IsValid() {
dest = outbound.Target
destinationOverridden = true
} else if handshake, ok := conn.(hasHandshakeAddress); ok {
addr := handshake.HandshakeAddress()
if addr != nil {
dest.Address = addr
destinationOverridden = true
}
}
}
if !dest.IsValid() || dest.Address == nil {
return newError("unable to get destination")
}
if inbound := session.InboundFromContext(ctx); inbound != nil {
inbound.User = &protocol.MemoryUser{
Level: d.config.UserLevel,
}
}
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: conn.RemoteAddr(),
To: dest,
Status: log.AccessAccepted,
Reason: "",
})
newError("received request for ", conn.RemoteAddr()).WriteToLog(session.ExportIDToError(ctx))
plcy := d.policy()
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer)
link, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return newError("failed to dispatch request").Base(err)
}
requestCount := int32(1)
requestDone := func() error {
defer func() {
if atomic.AddInt32(&requestCount, -1) == 0 {
timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
}
}()
var reader buf.Reader
if dest.Network == net.Network_UDP {
reader = buf.NewPacketReader(conn)
} else {
reader = buf.NewReader(conn)
}
if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport request").Base(err)
}
return nil
}
tproxyRequest := func() error {
return nil
}
var writer buf.Writer
if network == net.Network_TCP {
writer = buf.NewWriter(conn)
} else {
// if we are in TPROXY mode, use linux's udp forging functionality
if !destinationOverridden {
writer = &buf.SequentialWriter{Writer: conn}
} else {
sockopt := &internet.SocketConfig{
Tproxy: internet.SocketConfig_TProxy,
}
if dest.Address.Family().IsIP() {
sockopt.BindAddress = dest.Address.IP()
sockopt.BindPort = uint32(dest.Port)
}
if d.sockopt != nil {
sockopt.Mark = d.sockopt.Mark
}
tConn, err := internet.DialSystem(ctx, net.DestinationFromAddr(conn.RemoteAddr()), sockopt)
if err != nil {
return err
}
defer tConn.Close()
writer = &buf.SequentialWriter{Writer: tConn}
tReader := buf.NewPacketReader(tConn)
requestCount++
tproxyRequest = func() error {
defer func() {
if atomic.AddInt32(&requestCount, -1) == 0 {
timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
}
}()
if err := buf.Copy(tReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport request (TPROXY conn)").Base(err)
}
return nil
}
}
}
responseDone := func() error {
defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport response").Base(err)
}
return nil
}
if err := task.Run(ctx, task.OnSuccess(func() error {
return task.Run(ctx, requestDone, tproxyRequest)
}, task.Close(link.Writer)), responseDone); err != nil {
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
return newError("connection ends").Base(err)
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/loopback/errors.generated.go | proxy/loopback/errors.generated.go | package loopback
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/loopback/loopback.go | proxy/loopback/loopback.go | //go:build !confonly
// +build !confonly
package loopback
import (
"context"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/retry"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
type Loopback struct {
config *Config
dispatcherInstance routing.Dispatcher
}
func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet.Dialer) error {
outbound := session.OutboundFromContext(ctx)
if outbound == nil || !outbound.Target.IsValid() {
return newError("target not specified.")
}
destination := outbound.Target
newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
input := link.Reader
output := link.Writer
var conn internet.Connection
err := retry.ExponentialBackoff(5, 100).On(func() error {
dialDest := destination
content := new(session.Content)
content.SkipDNSResolve = true
ctx = session.ContextWithContent(ctx, content)
inbound := session.InboundFromContext(ctx)
inbound.Tag = l.config.InboundTag
ctx = session.ContextWithInbound(ctx, inbound)
rawConn, err := l.dispatcherInstance.Dispatch(ctx, dialDest)
if err != nil {
return err
}
var readerOpt net.ConnectionOption
if dialDest.Network == net.Network_TCP {
readerOpt = net.ConnectionOutputMulti(rawConn.Reader)
} else {
readerOpt = net.ConnectionOutputMultiUDP(rawConn.Reader)
}
conn = net.NewConnection(net.ConnectionInputMulti(rawConn.Writer), readerOpt)
return nil
})
if err != nil {
return newError("failed to open connection to ", destination).Base(err)
}
defer conn.Close()
requestDone := func() error {
var writer buf.Writer
if destination.Network == net.Network_TCP {
writer = buf.NewWriter(conn)
} else {
writer = &buf.SequentialWriter{Writer: conn}
}
if err := buf.Copy(input, writer); err != nil {
return newError("failed to process request").Base(err)
}
return nil
}
responseDone := func() error {
var reader buf.Reader
if destination.Network == net.Network_TCP {
reader = buf.NewReader(conn)
} else {
reader = buf.NewPacketReader(conn)
}
if err := buf.Copy(reader, output); err != nil {
return newError("failed to process response").Base(err)
}
return nil
}
if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil {
return newError("connection ends").Base(err)
}
return nil
}
func (l *Loopback) init(config *Config, dispatcherInstance routing.Dispatcher) error {
l.dispatcherInstance = dispatcherInstance
l.config = config
return nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
l := new(Loopback)
err := core.RequireFeatures(ctx, func(dispatcherInstance routing.Dispatcher) error {
return l.init(config.(*Config), dispatcherInstance)
})
return l, err
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/loopback/config.go | proxy/loopback/config.go | package loopback
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/loopback/config.pb.go | proxy/loopback/config.pb.go | package loopback
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
InboundTag string `protobuf:"bytes,1,opt,name=inbound_tag,json=inboundTag,proto3" json:"inbound_tag,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_proxy_loopback_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_proxy_loopback_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_proxy_loopback_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetInboundTag() string {
if x != nil {
return x.InboundTag
}
return ""
}
var File_proxy_loopback_config_proto protoreflect.FileDescriptor
const file_proxy_loopback_config_proto_rawDesc = "" +
"\n" +
"\x1bproxy/loopback/config.proto\x12\x19v2ray.core.proxy.loopback\x1a common/protoext/extensions.proto\"C\n" +
"\x06Config\x12\x1f\n" +
"\vinbound_tag\x18\x01 \x01(\tR\n" +
"inboundTag:\x18\x82\xb5\x18\x14\n" +
"\boutbound\x12\bloopbackBl\n" +
"\x1dcom.v2ray.core.proxy.loopbackP\x01Z-github.com/v2fly/v2ray-core/v5/proxy/loopback\xaa\x02\x19V2Ray.Core.Proxy.Loopbackb\x06proto3"
var (
file_proxy_loopback_config_proto_rawDescOnce sync.Once
file_proxy_loopback_config_proto_rawDescData []byte
)
func file_proxy_loopback_config_proto_rawDescGZIP() []byte {
file_proxy_loopback_config_proto_rawDescOnce.Do(func() {
file_proxy_loopback_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_loopback_config_proto_rawDesc), len(file_proxy_loopback_config_proto_rawDesc)))
})
return file_proxy_loopback_config_proto_rawDescData
}
var file_proxy_loopback_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_proxy_loopback_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.proxy.loopback.Config
}
var file_proxy_loopback_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_proxy_loopback_config_proto_init() }
func file_proxy_loopback_config_proto_init() {
if File_proxy_loopback_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_loopback_config_proto_rawDesc), len(file_proxy_loopback_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_loopback_config_proto_goTypes,
DependencyIndexes: file_proxy_loopback_config_proto_depIdxs,
MessageInfos: file_proxy_loopback_config_proto_msgTypes,
}.Build()
File_proxy_loopback_config_proto = out.File
file_proxy_loopback_config_proto_goTypes = nil
file_proxy_loopback_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/vmess.go | proxy/vmess/vmess.go | // Package vmess contains the implementation of VMess protocol and transportation.
//
// VMess contains both inbound and outbound connections. VMess inbound is usually used on servers
// together with 'freedom' to talk to final destination, while VMess outbound is usually used on
// clients with 'socks' for proxying.
package vmess
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/errors.generated.go | proxy/vmess/errors.generated.go | package vmess
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/validator_test.go | proxy/vmess/validator_test.go | package vmess_test
import (
"testing"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
. "github.com/v2fly/v2ray-core/v5/proxy/vmess"
)
func toAccount(a *Account) protocol.Account {
account, err := a.AsAccount()
common.Must(err)
return account
}
func TestUserValidator(t *testing.T) {
hasher := protocol.DefaultIDHash
v := NewTimedUserValidator(hasher)
defer common.Close(v)
id := uuid.New()
user := &protocol.MemoryUser{
Email: "test",
Account: toAccount(&Account{
Id: id.String(),
AlterId: 8,
}),
}
common.Must(v.Add(user))
{
testSmallLag := func(lag int64) {
ts := int64(v.GetBaseTime()) + lag + 240
idHash := hasher(id.Bytes())
common.Must2(serial.WriteUint64(idHash, uint64(ts)))
userHash := idHash.Sum(nil)
euser, ets, found, _ := v.Get(userHash)
if !found {
t.Fatal("user not found")
}
if euser.Email != user.Email {
t.Error("unexpected user email: ", euser.Email, " want ", user.Email)
}
if int64(ets) != ts {
t.Error("unexpected timestamp: ", ets, " want ", ts)
}
}
testSmallLag(0)
testSmallLag(40)
testSmallLag(-40)
testSmallLag(80)
testSmallLag(-80)
testSmallLag(120)
testSmallLag(-120)
}
{
testBigLag := func(lag int64) {
ts := int64(v.GetBaseTime()) + lag + 240
idHash := hasher(id.Bytes())
common.Must2(serial.WriteUint64(idHash, uint64(ts)))
userHash := idHash.Sum(nil)
euser, _, found, _ := v.Get(userHash)
if found || euser != nil {
t.Error("unexpected user")
}
}
testBigLag(121)
testBigLag(-121)
testBigLag(310)
testBigLag(-310)
testBigLag(500)
testBigLag(-500)
}
if v := v.Remove(user.Email); !v {
t.Error("unable to remove user")
}
if v := v.Remove(user.Email); v {
t.Error("remove user twice")
}
}
func BenchmarkUserValidator(b *testing.B) {
for i := 0; i < b.N; i++ {
hasher := protocol.DefaultIDHash
v := NewTimedUserValidator(hasher)
for j := 0; j < 1500; j++ {
id := uuid.New()
v.Add(&protocol.MemoryUser{
Email: "test",
Account: toAccount(&Account{
Id: id.String(),
AlterId: 16,
}),
})
}
common.Close(v)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/validator.go | proxy/vmess/validator.go | package vmess
import (
"crypto/hmac"
"crypto/sha256"
"hash/crc64"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/dice"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/aead"
)
const (
updateInterval = 10 * time.Second
cacheDurationSec = 120
)
type user struct {
user protocol.MemoryUser
lastSec protocol.Timestamp
}
// TimedUserValidator is a user Validator based on time.
type TimedUserValidator struct {
sync.RWMutex
users []*user
userHash map[[16]byte]indexTimePair
hasher protocol.IDHash
baseTime protocol.Timestamp
task *task.Periodic
behaviorSeed uint64
behaviorFused bool
aeadDecoderHolder *aead.AuthIDDecoderHolder
legacyWarnShown bool
}
type indexTimePair struct {
user *user
timeInc uint32
taintedFuse *uint32
}
// NewTimedUserValidator creates a new TimedUserValidator.
func NewTimedUserValidator(hasher protocol.IDHash) *TimedUserValidator {
tuv := &TimedUserValidator{
users: make([]*user, 0, 16),
userHash: make(map[[16]byte]indexTimePair, 1024),
hasher: hasher,
baseTime: protocol.Timestamp(time.Now().Unix() - cacheDurationSec*2),
aeadDecoderHolder: aead.NewAuthIDDecoderHolder(),
}
tuv.task = &task.Periodic{
Interval: updateInterval,
Execute: func() error {
tuv.updateUserHash()
return nil
},
}
common.Must(tuv.task.Start())
return tuv
}
// visible for testing
func (v *TimedUserValidator) GetBaseTime() protocol.Timestamp {
return v.baseTime
}
func (v *TimedUserValidator) generateNewHashes(nowSec protocol.Timestamp, user *user) {
var hashValue [16]byte
genEndSec := nowSec + cacheDurationSec
genHashForID := func(id *protocol.ID) {
idHash := v.hasher(id.Bytes())
genBeginSec := user.lastSec
if genBeginSec < nowSec-cacheDurationSec {
genBeginSec = nowSec - cacheDurationSec
}
for ts := genBeginSec; ts <= genEndSec; ts++ {
common.Must2(serial.WriteUint64(idHash, uint64(ts)))
idHash.Sum(hashValue[:0])
idHash.Reset()
v.userHash[hashValue] = indexTimePair{
user: user,
timeInc: uint32(ts - v.baseTime),
taintedFuse: new(uint32),
}
}
}
account := user.user.Account.(*MemoryAccount)
genHashForID(account.ID)
for _, id := range account.AlterIDs {
genHashForID(id)
}
user.lastSec = genEndSec
}
func (v *TimedUserValidator) removeExpiredHashes(expire uint32) {
for key, pair := range v.userHash {
if pair.timeInc < expire {
delete(v.userHash, key)
}
}
}
func (v *TimedUserValidator) updateUserHash() {
now := time.Now()
nowSec := protocol.Timestamp(now.Unix())
v.Lock()
defer v.Unlock()
for _, user := range v.users {
v.generateNewHashes(nowSec, user)
}
expire := protocol.Timestamp(now.Unix() - cacheDurationSec)
if expire > v.baseTime {
v.removeExpiredHashes(uint32(expire - v.baseTime))
}
}
func (v *TimedUserValidator) Add(u *protocol.MemoryUser) error {
v.Lock()
defer v.Unlock()
nowSec := time.Now().Unix()
uu := &user{
user: *u,
lastSec: protocol.Timestamp(nowSec - cacheDurationSec),
}
v.users = append(v.users, uu)
v.generateNewHashes(protocol.Timestamp(nowSec), uu)
account := uu.user.Account.(*MemoryAccount)
if !v.behaviorFused {
hashkdf := hmac.New(sha256.New, []byte("VMESSBSKDF"))
hashkdf.Write(account.ID.Bytes())
v.behaviorSeed = crc64.Update(v.behaviorSeed, crc64.MakeTable(crc64.ECMA), hashkdf.Sum(nil))
}
var cmdkeyfl [16]byte
copy(cmdkeyfl[:], account.ID.CmdKey())
v.aeadDecoderHolder.AddUser(cmdkeyfl, u)
return nil
}
func (v *TimedUserValidator) Get(userHash []byte) (*protocol.MemoryUser, protocol.Timestamp, bool, error) {
v.RLock()
defer v.RUnlock()
v.behaviorFused = true
var fixedSizeHash [16]byte
copy(fixedSizeHash[:], userHash)
pair, found := v.userHash[fixedSizeHash]
if found {
user := pair.user.user
if atomic.LoadUint32(pair.taintedFuse) == 0 {
return &user, protocol.Timestamp(pair.timeInc) + v.baseTime, true, nil
}
return nil, 0, false, ErrTainted
}
return nil, 0, false, ErrNotFound
}
func (v *TimedUserValidator) GetAEAD(userHash []byte) (*protocol.MemoryUser, bool, error) {
v.RLock()
defer v.RUnlock()
var userHashFL [16]byte
copy(userHashFL[:], userHash)
userd, err := v.aeadDecoderHolder.Match(userHashFL)
if err != nil {
return nil, false, err
}
return userd.(*protocol.MemoryUser), true, err
}
func (v *TimedUserValidator) Remove(email string) bool {
v.Lock()
defer v.Unlock()
email = strings.ToLower(email)
idx := -1
for i, u := range v.users {
if strings.EqualFold(u.user.Email, email) {
idx = i
var cmdkeyfl [16]byte
copy(cmdkeyfl[:], u.user.Account.(*MemoryAccount).ID.CmdKey())
v.aeadDecoderHolder.RemoveUser(cmdkeyfl)
break
}
}
if idx == -1 {
return false
}
ulen := len(v.users)
v.users[idx] = v.users[ulen-1]
v.users[ulen-1] = nil
v.users = v.users[:ulen-1]
return true
}
// Close implements common.Closable.
func (v *TimedUserValidator) Close() error {
return v.task.Close()
}
func (v *TimedUserValidator) GetBehaviorSeed() uint64 {
v.Lock()
defer v.Unlock()
v.behaviorFused = true
if v.behaviorSeed == 0 {
v.behaviorSeed = dice.RollUint64()
}
return v.behaviorSeed
}
func (v *TimedUserValidator) BurnTaintFuse(userHash []byte) error {
v.RLock()
defer v.RUnlock()
var userHashFL [16]byte
copy(userHashFL[:], userHash)
pair, found := v.userHash[userHashFL]
if found {
if atomic.CompareAndSwapUint32(pair.taintedFuse, 0, 1) {
return nil
}
return ErrTainted
}
return ErrNotFound
}
/*
ShouldShowLegacyWarn will return whether a Legacy Warning should be shown
Not guaranteed to only return true once for every inbound, but it is okay.
*/
func (v *TimedUserValidator) ShouldShowLegacyWarn() bool {
if v.legacyWarnShown {
return false
}
v.legacyWarnShown = true
return true
}
var ErrNotFound = newError("Not Found")
var ErrTainted = newError("ErrTainted")
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/vmessCtxInterface.go | proxy/vmess/vmessCtxInterface.go | package vmess
// example
const AlterID = "VMessCtxInterface_AlterID"
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/account.pb.go | proxy/vmess/account.pb.go | package vmess
import (
protocol "github.com/v2fly/v2ray-core/v5/common/protocol"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Account struct {
state protoimpl.MessageState `protogen:"open.v1"`
// ID of the account, in the form of a UUID, e.g.,
// "66ad4540-b58c-4ad2-9926-ea63445a9b57".
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
// Number of alternative IDs. Client and server must share the same number.
AlterId uint32 `protobuf:"varint,2,opt,name=alter_id,json=alterId,proto3" json:"alter_id,omitempty"`
// Security settings. Only applies to client side.
SecuritySettings *protocol.SecurityConfig `protobuf:"bytes,3,opt,name=security_settings,json=securitySettings,proto3" json:"security_settings,omitempty"`
// Define tests enabled for this account
TestsEnabled string `protobuf:"bytes,4,opt,name=tests_enabled,json=testsEnabled,proto3" json:"tests_enabled,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Account) Reset() {
*x = Account{}
mi := &file_proxy_vmess_account_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Account) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Account) ProtoMessage() {}
func (x *Account) ProtoReflect() protoreflect.Message {
mi := &file_proxy_vmess_account_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Account.ProtoReflect.Descriptor instead.
func (*Account) Descriptor() ([]byte, []int) {
return file_proxy_vmess_account_proto_rawDescGZIP(), []int{0}
}
func (x *Account) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *Account) GetAlterId() uint32 {
if x != nil {
return x.AlterId
}
return 0
}
func (x *Account) GetSecuritySettings() *protocol.SecurityConfig {
if x != nil {
return x.SecuritySettings
}
return nil
}
func (x *Account) GetTestsEnabled() string {
if x != nil {
return x.TestsEnabled
}
return ""
}
var File_proxy_vmess_account_proto protoreflect.FileDescriptor
const file_proxy_vmess_account_proto_rawDesc = "" +
"\n" +
"\x19proxy/vmess/account.proto\x12\x16v2ray.core.proxy.vmess\x1a\x1dcommon/protocol/headers.proto\"\xb2\x01\n" +
"\aAccount\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12\x19\n" +
"\balter_id\x18\x02 \x01(\rR\aalterId\x12W\n" +
"\x11security_settings\x18\x03 \x01(\v2*.v2ray.core.common.protocol.SecurityConfigR\x10securitySettings\x12#\n" +
"\rtests_enabled\x18\x04 \x01(\tR\ftestsEnabledBc\n" +
"\x1acom.v2ray.core.proxy.vmessP\x01Z*github.com/v2fly/v2ray-core/v5/proxy/vmess\xaa\x02\x16V2Ray.Core.Proxy.Vmessb\x06proto3"
var (
file_proxy_vmess_account_proto_rawDescOnce sync.Once
file_proxy_vmess_account_proto_rawDescData []byte
)
func file_proxy_vmess_account_proto_rawDescGZIP() []byte {
file_proxy_vmess_account_proto_rawDescOnce.Do(func() {
file_proxy_vmess_account_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proxy_vmess_account_proto_rawDesc), len(file_proxy_vmess_account_proto_rawDesc)))
})
return file_proxy_vmess_account_proto_rawDescData
}
var file_proxy_vmess_account_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_proxy_vmess_account_proto_goTypes = []any{
(*Account)(nil), // 0: v2ray.core.proxy.vmess.Account
(*protocol.SecurityConfig)(nil), // 1: v2ray.core.common.protocol.SecurityConfig
}
var file_proxy_vmess_account_proto_depIdxs = []int32{
1, // 0: v2ray.core.proxy.vmess.Account.security_settings:type_name -> v2ray.core.common.protocol.SecurityConfig
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_proxy_vmess_account_proto_init() }
func file_proxy_vmess_account_proto_init() {
if File_proxy_vmess_account_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proxy_vmess_account_proto_rawDesc), len(file_proxy_vmess_account_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_proxy_vmess_account_proto_goTypes,
DependencyIndexes: file_proxy_vmess_account_proto_depIdxs,
MessageInfos: file_proxy_vmess_account_proto_msgTypes,
}.Build()
File_proxy_vmess_account_proto = out.File
file_proxy_vmess_account_proto_goTypes = nil
file_proxy_vmess_account_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/account.go | proxy/vmess/account.go | //go:build !confonly
// +build !confonly
package vmess
import (
"strings"
"github.com/v2fly/v2ray-core/v5/common/dice"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/uuid"
)
// MemoryAccount is an in-memory form of VMess account.
type MemoryAccount struct {
// ID is the main ID of the account.
ID *protocol.ID
// AlterIDs are the alternative IDs of the account.
AlterIDs []*protocol.ID
// Security type of the account. Used for client connections.
Security protocol.SecurityType
AuthenticatedLengthExperiment bool
NoTerminationSignal bool
}
// AnyValidID returns an ID that is either the main ID or one of the alternative IDs if any.
func (a *MemoryAccount) AnyValidID() *protocol.ID {
if len(a.AlterIDs) == 0 {
return a.ID
}
return a.AlterIDs[dice.Roll(len(a.AlterIDs))]
}
// Equals implements protocol.Account.
func (a *MemoryAccount) Equals(account protocol.Account) bool {
vmessAccount, ok := account.(*MemoryAccount)
if !ok {
return false
}
// TODO: handle AlterIds difference
return a.ID.Equals(vmessAccount.ID)
}
// AsAccount implements protocol.Account.
func (a *Account) AsAccount() (protocol.Account, error) {
id, err := uuid.ParseString(a.Id)
if err != nil {
return nil, newError("failed to parse ID").Base(err).AtError()
}
protoID := protocol.NewID(id)
var AuthenticatedLength, NoTerminationSignal bool
if strings.Contains(a.TestsEnabled, "AuthenticatedLength") {
AuthenticatedLength = true
}
if strings.Contains(a.TestsEnabled, "NoTerminationSignal") {
NoTerminationSignal = true
}
return &MemoryAccount{
ID: protoID,
AlterIDs: protocol.NewAlterIDs(protoID, uint16(a.AlterId)),
Security: a.SecuritySettings.GetSecurityType(),
AuthenticatedLengthExperiment: AuthenticatedLength,
NoTerminationSignal: NoTerminationSignal,
}, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/encoding/commands.go | proxy/vmess/encoding/commands.go | package encoding
import (
"encoding/binary"
"io"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
)
var (
ErrCommandTypeMismatch = newError("Command type mismatch.")
ErrUnknownCommand = newError("Unknown command.")
ErrCommandTooLarge = newError("Command too large.")
ErrInsufficientLength = newError("Insufficient length.")
ErrInvalidAuth = newError("Invalid auth.")
)
func MarshalCommand(command interface{}, writer io.Writer) error {
if command == nil {
return ErrUnknownCommand
}
var cmdID byte
var factory CommandFactory
switch command.(type) {
case *protocol.CommandSwitchAccount:
factory = new(CommandSwitchAccountFactory)
cmdID = 1
default:
return ErrUnknownCommand
}
buffer := buf.New()
defer buffer.Release()
err := factory.Marshal(command, buffer)
if err != nil {
return err
}
auth := Authenticate(buffer.Bytes())
length := buffer.Len() + 4
if length > 255 {
return ErrCommandTooLarge
}
common.Must2(writer.Write([]byte{cmdID, byte(length), byte(auth >> 24), byte(auth >> 16), byte(auth >> 8), byte(auth)}))
common.Must2(writer.Write(buffer.Bytes()))
return nil
}
func UnmarshalCommand(cmdID byte, data []byte) (protocol.ResponseCommand, error) {
if len(data) <= 4 {
return nil, ErrInsufficientLength
}
expectedAuth := Authenticate(data[4:])
actualAuth := binary.BigEndian.Uint32(data[:4])
if expectedAuth != actualAuth {
return nil, ErrInvalidAuth
}
var factory CommandFactory
switch cmdID {
case 1:
factory = new(CommandSwitchAccountFactory)
default:
return nil, ErrUnknownCommand
}
return factory.Unmarshal(data[4:])
}
type CommandFactory interface {
Marshal(command interface{}, writer io.Writer) error
Unmarshal(data []byte) (interface{}, error)
}
type CommandSwitchAccountFactory struct{}
func (f *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error {
cmd, ok := command.(*protocol.CommandSwitchAccount)
if !ok {
return ErrCommandTypeMismatch
}
hostStr := ""
if cmd.Host != nil {
hostStr = cmd.Host.String()
}
common.Must2(writer.Write([]byte{byte(len(hostStr))}))
if len(hostStr) > 0 {
common.Must2(writer.Write([]byte(hostStr)))
}
common.Must2(serial.WriteUint16(writer, cmd.Port.Value()))
idBytes := cmd.ID.Bytes()
common.Must2(writer.Write(idBytes))
common.Must2(serial.WriteUint16(writer, cmd.AlterIds))
common.Must2(writer.Write([]byte{byte(cmd.Level)}))
common.Must2(writer.Write([]byte{cmd.ValidMin}))
return nil
}
func (f *CommandSwitchAccountFactory) Unmarshal(data []byte) (interface{}, error) {
cmd := new(protocol.CommandSwitchAccount)
if len(data) == 0 {
return nil, ErrInsufficientLength
}
lenHost := int(data[0])
if len(data) < lenHost+1 {
return nil, ErrInsufficientLength
}
if lenHost > 0 {
cmd.Host = net.ParseAddress(string(data[1 : 1+lenHost]))
}
portStart := 1 + lenHost
if len(data) < portStart+2 {
return nil, ErrInsufficientLength
}
cmd.Port = net.PortFromBytes(data[portStart : portStart+2])
idStart := portStart + 2
if len(data) < idStart+16 {
return nil, ErrInsufficientLength
}
cmd.ID, _ = uuid.ParseBytes(data[idStart : idStart+16])
alterIDStart := idStart + 16
if len(data) < alterIDStart+2 {
return nil, ErrInsufficientLength
}
cmd.AlterIds = binary.BigEndian.Uint16(data[alterIDStart : alterIDStart+2])
levelStart := alterIDStart + 2
if len(data) < levelStart+1 {
return nil, ErrInsufficientLength
}
cmd.Level = uint32(data[levelStart])
timeStart := levelStart + 1
if len(data) < timeStart+1 {
return nil, ErrInsufficientLength
}
cmd.ValidMin = data[timeStart]
return cmd, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/encoding/errors.generated.go | proxy/vmess/encoding/errors.generated.go | package encoding
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/encoding/client.go | proxy/vmess/encoding/client.go | package encoding
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"hash"
"hash/fnv"
"io"
"golang.org/x/crypto/chacha20poly1305"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/bitmask"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/crypto"
"github.com/v2fly/v2ray-core/v5/common/dice"
"github.com/v2fly/v2ray-core/v5/common/drain"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
vmessaead "github.com/v2fly/v2ray-core/v5/proxy/vmess/aead"
)
func hashTimestamp(h hash.Hash, t protocol.Timestamp) []byte {
common.Must2(serial.WriteUint64(h, uint64(t)))
common.Must2(serial.WriteUint64(h, uint64(t)))
common.Must2(serial.WriteUint64(h, uint64(t)))
common.Must2(serial.WriteUint64(h, uint64(t)))
return h.Sum(nil)
}
// ClientSession stores connection session info for VMess client.
type ClientSession struct {
isAEAD bool
idHash protocol.IDHash
requestBodyKey [16]byte
requestBodyIV [16]byte
responseBodyKey [16]byte
responseBodyIV [16]byte
responseReader io.Reader
responseHeader byte
readDrainer drain.Drainer
}
// NewClientSession creates a new ClientSession.
func NewClientSession(ctx context.Context, isAEAD bool, idHash protocol.IDHash, behaviorSeed int64) *ClientSession {
session := &ClientSession{
isAEAD: isAEAD,
idHash: idHash,
}
randomBytes := make([]byte, 33) // 16 + 16 + 1
common.Must2(rand.Read(randomBytes))
copy(session.requestBodyKey[:], randomBytes[:16])
copy(session.requestBodyIV[:], randomBytes[16:32])
session.responseHeader = randomBytes[32]
if !session.isAEAD {
session.responseBodyKey = md5.Sum(session.requestBodyKey[:])
session.responseBodyIV = md5.Sum(session.requestBodyIV[:])
} else {
BodyKey := sha256.Sum256(session.requestBodyKey[:])
copy(session.responseBodyKey[:], BodyKey[:16])
BodyIV := sha256.Sum256(session.requestBodyIV[:])
copy(session.responseBodyIV[:], BodyIV[:16])
}
{
var err error
session.readDrainer, err = drain.NewBehaviorSeedLimitedDrainer(behaviorSeed, 18, 3266, 64)
if err != nil {
newError("unable to initialize drainer").Base(err).WriteToLog()
session.readDrainer = drain.NewNopDrainer()
}
}
return session
}
func (c *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writer io.Writer) error {
timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)()
account := header.User.Account.(*vmess.MemoryAccount)
if !c.isAEAD {
idHash := c.idHash(account.AnyValidID().Bytes())
common.Must2(serial.WriteUint64(idHash, uint64(timestamp)))
common.Must2(writer.Write(idHash.Sum(nil)))
}
buffer := buf.New()
defer buffer.Release()
common.Must(buffer.WriteByte(Version))
common.Must2(buffer.Write(c.requestBodyIV[:]))
common.Must2(buffer.Write(c.requestBodyKey[:]))
common.Must(buffer.WriteByte(c.responseHeader))
common.Must(buffer.WriteByte(byte(header.Option)))
paddingLen := dice.RollWith(16, rand.Reader)
security := byte(paddingLen<<4) | byte(header.Security)
common.Must2(buffer.Write([]byte{security, byte(0), byte(header.Command)}))
if header.Command != protocol.RequestCommandMux {
if err := addrParser.WriteAddressPort(buffer, header.Address, header.Port); err != nil {
return newError("failed to writer address and port").Base(err)
}
}
if paddingLen > 0 {
common.Must2(buffer.ReadFullFrom(rand.Reader, int32(paddingLen)))
}
{
fnv1a := fnv.New32a()
common.Must2(fnv1a.Write(buffer.Bytes()))
hashBytes := buffer.Extend(int32(fnv1a.Size()))
fnv1a.Sum(hashBytes[:0])
}
if !c.isAEAD {
iv := hashTimestamp(md5.New(), timestamp)
aesStream := crypto.NewAesEncryptionStream(account.ID.CmdKey(), iv)
aesStream.XORKeyStream(buffer.Bytes(), buffer.Bytes())
common.Must2(writer.Write(buffer.Bytes()))
} else {
var fixedLengthCmdKey [16]byte
copy(fixedLengthCmdKey[:], account.ID.CmdKey())
vmessout := vmessaead.SealVMessAEADHeader(fixedLengthCmdKey, buffer.Bytes())
common.Must2(io.Copy(writer, bytes.NewReader(vmessout)))
}
return nil
}
func (c *ClientSession) EncodeRequestBody(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{}
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeParser = NewShakeSizeParser(c.requestBodyIV[:])
}
var padding crypto.PaddingLengthGenerator
if request.Option.Has(protocol.RequestOptionGlobalPadding) {
var ok bool
padding, ok = sizeParser.(crypto.PaddingLengthGenerator)
if !ok {
return nil, newError("invalid option: RequestOptionGlobalPadding")
}
}
switch request.Security {
case protocol.SecurityType_NONE:
if request.Option.Has(protocol.RequestOptionChunkStream) {
if request.Command.TransferType() == protocol.TransferTypeStream {
return crypto.NewChunkStreamWriter(sizeParser, writer), nil
}
auth := &crypto.AEADAuthenticator{
AEAD: new(NoOpAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding), nil
}
return buf.NewWriter(writer), nil
case protocol.SecurityType_LEGACY:
aesStream := crypto.NewAesEncryptionStream(c.requestBodyKey[:], c.requestBodyIV[:])
cryptionWriter := crypto.NewCryptionWriter(aesStream, writer)
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationWriter(auth, sizeParser, cryptionWriter, request.Command.TransferType(), padding), nil
}
return &buf.SequentialWriter{Writer: cryptionWriter}, nil
case protocol.SecurityType_AES128_GCM:
aead := crypto.NewAesGcm(c.requestBodyKey[:])
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
AuthenticatedLengthKey := vmessaead.KDF16(c.requestBodyKey[:], "auth_len")
AuthenticatedLengthKeyAEAD := crypto.NewAesGcm(AuthenticatedLengthKey)
lengthAuth := &crypto.AEADAuthenticator{
AEAD: AuthenticatedLengthKeyAEAD,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser = NewAEADSizeParser(lengthAuth)
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding), nil
case protocol.SecurityType_CHACHA20_POLY1305:
aead, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(c.requestBodyKey[:]))
common.Must(err)
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
AuthenticatedLengthKey := vmessaead.KDF16(c.requestBodyKey[:], "auth_len")
AuthenticatedLengthKeyAEAD, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(AuthenticatedLengthKey))
common.Must(err)
lengthAuth := &crypto.AEADAuthenticator{
AEAD: AuthenticatedLengthKeyAEAD,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser = NewAEADSizeParser(lengthAuth)
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding), nil
default:
return nil, newError("invalid option: Security")
}
}
func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.ResponseHeader, error) {
if !c.isAEAD {
aesStream := crypto.NewAesDecryptionStream(c.responseBodyKey[:], c.responseBodyIV[:])
c.responseReader = crypto.NewCryptionReader(aesStream, reader)
} else {
aeadResponseHeaderLengthEncryptionKey := vmessaead.KDF16(c.responseBodyKey[:], vmessaead.KDFSaltConstAEADRespHeaderLenKey)
aeadResponseHeaderLengthEncryptionIV := vmessaead.KDF(c.responseBodyIV[:], vmessaead.KDFSaltConstAEADRespHeaderLenIV)[:12]
aeadResponseHeaderLengthEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderLengthEncryptionKey)).(cipher.Block)
aeadResponseHeaderLengthEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderLengthEncryptionKeyAESBlock)).(cipher.AEAD)
var aeadEncryptedResponseHeaderLength [18]byte
var decryptedResponseHeaderLength int
var decryptedResponseHeaderLengthBinaryDeserializeBuffer uint16
if n, err := io.ReadFull(reader, aeadEncryptedResponseHeaderLength[:]); err != nil {
c.readDrainer.AcknowledgeReceive(n)
return nil, drain.WithError(c.readDrainer, reader, newError("Unable to Read Header Len").Base(err))
} else { // nolint: revive
c.readDrainer.AcknowledgeReceive(n)
}
if decryptedResponseHeaderLengthBinaryBuffer, err := aeadResponseHeaderLengthEncryptionAEAD.Open(nil, aeadResponseHeaderLengthEncryptionIV, aeadEncryptedResponseHeaderLength[:], nil); err != nil {
return nil, drain.WithError(c.readDrainer, reader, newError("Failed To Decrypt Length").Base(err))
} else { // nolint: revive
common.Must(binary.Read(bytes.NewReader(decryptedResponseHeaderLengthBinaryBuffer), binary.BigEndian, &decryptedResponseHeaderLengthBinaryDeserializeBuffer))
decryptedResponseHeaderLength = int(decryptedResponseHeaderLengthBinaryDeserializeBuffer)
}
aeadResponseHeaderPayloadEncryptionKey := vmessaead.KDF16(c.responseBodyKey[:], vmessaead.KDFSaltConstAEADRespHeaderPayloadKey)
aeadResponseHeaderPayloadEncryptionIV := vmessaead.KDF(c.responseBodyIV[:], vmessaead.KDFSaltConstAEADRespHeaderPayloadIV)[:12]
aeadResponseHeaderPayloadEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderPayloadEncryptionKey)).(cipher.Block)
aeadResponseHeaderPayloadEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderPayloadEncryptionKeyAESBlock)).(cipher.AEAD)
encryptedResponseHeaderBuffer := make([]byte, decryptedResponseHeaderLength+16)
if n, err := io.ReadFull(reader, encryptedResponseHeaderBuffer); err != nil {
c.readDrainer.AcknowledgeReceive(n)
return nil, drain.WithError(c.readDrainer, reader, newError("Unable to Read Header Data").Base(err))
} else { // nolint: revive
c.readDrainer.AcknowledgeReceive(n)
}
if decryptedResponseHeaderBuffer, err := aeadResponseHeaderPayloadEncryptionAEAD.Open(nil, aeadResponseHeaderPayloadEncryptionIV, encryptedResponseHeaderBuffer, nil); err != nil {
return nil, drain.WithError(c.readDrainer, reader, newError("Failed To Decrypt Payload").Base(err))
} else { // nolint: revive
c.responseReader = bytes.NewReader(decryptedResponseHeaderBuffer)
}
}
buffer := buf.StackNew()
defer buffer.Release()
if _, err := buffer.ReadFullFrom(c.responseReader, 4); err != nil {
return nil, newError("failed to read response header").Base(err).AtWarning()
}
if buffer.Byte(0) != c.responseHeader {
return nil, newError("unexpected response header. Expecting ", int(c.responseHeader), " but actually ", int(buffer.Byte(0)))
}
header := &protocol.ResponseHeader{
Option: bitmask.Byte(buffer.Byte(1)),
}
if buffer.Byte(2) != 0 {
cmdID := buffer.Byte(2)
dataLen := int32(buffer.Byte(3))
buffer.Clear()
if _, err := buffer.ReadFullFrom(c.responseReader, dataLen); err != nil {
return nil, newError("failed to read response command").Base(err)
}
command, err := UnmarshalCommand(cmdID, buffer.Bytes())
if err == nil {
header.Command = command
}
}
if c.isAEAD {
aesStream := crypto.NewAesDecryptionStream(c.responseBodyKey[:], c.responseBodyIV[:])
c.responseReader = crypto.NewCryptionReader(aesStream, reader)
}
return header, nil
}
func (c *ClientSession) DecodeResponseBody(request *protocol.RequestHeader, reader io.Reader) (buf.Reader, error) {
var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{}
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeParser = NewShakeSizeParser(c.responseBodyIV[:])
}
var padding crypto.PaddingLengthGenerator
if request.Option.Has(protocol.RequestOptionGlobalPadding) {
var ok bool
padding, ok = sizeParser.(crypto.PaddingLengthGenerator)
if !ok {
return nil, newError("invalid option: RequestOptionGlobalPadding")
}
}
switch request.Security {
case protocol.SecurityType_NONE:
if request.Option.Has(protocol.RequestOptionChunkStream) {
if request.Command.TransferType() == protocol.TransferTypeStream {
return crypto.NewChunkStreamReader(sizeParser, reader), nil
}
auth := &crypto.AEADAuthenticator{
AEAD: new(NoOpAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding), nil
}
return buf.NewReader(reader), nil
case protocol.SecurityType_LEGACY:
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationReader(auth, sizeParser, c.responseReader, request.Command.TransferType(), padding), nil
}
return buf.NewReader(c.responseReader), nil
case protocol.SecurityType_AES128_GCM:
aead := crypto.NewAesGcm(c.responseBodyKey[:])
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.responseBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
AuthenticatedLengthKey := vmessaead.KDF16(c.requestBodyKey[:], "auth_len")
AuthenticatedLengthKeyAEAD := crypto.NewAesGcm(AuthenticatedLengthKey)
lengthAuth := &crypto.AEADAuthenticator{
AEAD: AuthenticatedLengthKeyAEAD,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser = NewAEADSizeParser(lengthAuth)
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding), nil
case protocol.SecurityType_CHACHA20_POLY1305:
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(c.responseBodyKey[:]))
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.responseBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
AuthenticatedLengthKey := vmessaead.KDF16(c.requestBodyKey[:], "auth_len")
AuthenticatedLengthKeyAEAD, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(AuthenticatedLengthKey))
common.Must(err)
lengthAuth := &crypto.AEADAuthenticator{
AEAD: AuthenticatedLengthKeyAEAD,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser = NewAEADSizeParser(lengthAuth)
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding), nil
default:
return nil, newError("invalid option: Security")
}
}
func GenerateChunkNonce(nonce []byte, size uint32) crypto.BytesGenerator {
c := append([]byte(nil), nonce...)
count := uint16(0)
return func() []byte {
binary.BigEndian.PutUint16(c, count)
count++
return c[:size]
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/encoding/commands_test.go | proxy/vmess/encoding/commands_test.go | package encoding_test
import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/uuid"
. "github.com/v2fly/v2ray-core/v5/proxy/vmess/encoding"
)
func TestSwitchAccount(t *testing.T) {
sa := &protocol.CommandSwitchAccount{
Port: 1234,
ID: uuid.New(),
AlterIds: 1024,
Level: 128,
ValidMin: 16,
}
buffer := buf.New()
common.Must(MarshalCommand(sa, buffer))
cmd, err := UnmarshalCommand(1, buffer.BytesFrom(2))
common.Must(err)
sa2, ok := cmd.(*protocol.CommandSwitchAccount)
if !ok {
t.Fatal("failed to convert command to CommandSwitchAccount")
}
if r := cmp.Diff(sa2, sa); r != "" {
t.Error(r)
}
}
func TestSwitchAccountBugOffByOne(t *testing.T) {
sa := &protocol.CommandSwitchAccount{
Port: 1234,
ID: uuid.New(),
AlterIds: 1024,
Level: 128,
ValidMin: 16,
}
buffer := buf.New()
csaf := CommandSwitchAccountFactory{}
common.Must(csaf.Marshal(sa, buffer))
Payload := buffer.Bytes()
cmd, err := csaf.Unmarshal(Payload[:len(Payload)-1])
assert.Error(t, err)
assert.Nil(t, cmd)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/encoding/server.go | proxy/vmess/encoding/server.go | package encoding
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/sha256"
"encoding/binary"
"hash/fnv"
"io"
"sync"
"time"
"golang.org/x/crypto/chacha20poly1305"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/bitmask"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/crypto"
"github.com/v2fly/v2ray-core/v5/common/drain"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
vmessaead "github.com/v2fly/v2ray-core/v5/proxy/vmess/aead"
)
type sessionID struct {
user [16]byte
key [16]byte
nonce [16]byte
}
// SessionHistory keeps track of historical session ids, to prevent replay attacks.
type SessionHistory struct {
sync.RWMutex
cache map[sessionID]time.Time
task *task.Periodic
}
// NewSessionHistory creates a new SessionHistory object.
func NewSessionHistory() *SessionHistory {
h := &SessionHistory{
cache: make(map[sessionID]time.Time, 128),
}
h.task = &task.Periodic{
Interval: time.Second * 30,
Execute: h.removeExpiredEntries,
}
return h
}
// Close implements common.Closable.
func (h *SessionHistory) Close() error {
return h.task.Close()
}
func (h *SessionHistory) addIfNotExits(session sessionID) bool {
h.Lock()
if expire, found := h.cache[session]; found && expire.After(time.Now()) {
h.Unlock()
return false
}
h.cache[session] = time.Now().Add(time.Minute * 3)
h.Unlock()
common.Must(h.task.Start())
return true
}
func (h *SessionHistory) removeExpiredEntries() error {
now := time.Now()
h.Lock()
defer h.Unlock()
if len(h.cache) == 0 {
return newError("nothing to do")
}
for session, expire := range h.cache {
if expire.Before(now) {
delete(h.cache, session)
}
}
if len(h.cache) == 0 {
h.cache = make(map[sessionID]time.Time, 128)
}
return nil
}
// ServerSession keeps information for a session in VMess server.
type ServerSession struct {
userValidator *vmess.TimedUserValidator
sessionHistory *SessionHistory
requestBodyKey [16]byte
requestBodyIV [16]byte
responseBodyKey [16]byte
responseBodyIV [16]byte
responseWriter io.Writer
responseHeader byte
isAEADRequest bool
isAEADForced bool
}
// NewServerSession creates a new ServerSession, using the given UserValidator.
// The ServerSession instance doesn't take ownership of the validator.
func NewServerSession(validator *vmess.TimedUserValidator, sessionHistory *SessionHistory) *ServerSession {
return &ServerSession{
userValidator: validator,
sessionHistory: sessionHistory,
}
}
// SetAEADForced sets isAEADForced for a ServerSession.
func (s *ServerSession) SetAEADForced(isAEADForced bool) {
s.isAEADForced = isAEADForced
}
func parseSecurityType(b byte) protocol.SecurityType {
if _, f := protocol.SecurityType_name[int32(b)]; f {
st := protocol.SecurityType(b)
// For backward compatibility.
if st == protocol.SecurityType_UNKNOWN {
st = protocol.SecurityType_LEGACY
}
return st
}
return protocol.SecurityType_UNKNOWN
}
// DecodeRequestHeader decodes and returns (if successful) a RequestHeader from an input stream.
func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) {
buffer := buf.New()
drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(s.userValidator.GetBehaviorSeed()), 16+38, 3266, 64)
if err != nil {
return nil, newError("failed to initialize drainer").Base(err)
}
drainConnection := func(e error) error {
// We read a deterministic generated length of data before closing the connection to offset padding read pattern
drainer.AcknowledgeReceive(int(buffer.Len()))
return drain.WithError(drainer, reader, e)
}
defer func() {
buffer.Release()
}()
if _, err := buffer.ReadFullFrom(reader, protocol.IDBytesLen); err != nil {
return nil, newError("failed to read request header").Base(err)
}
var decryptor io.Reader
var vmessAccount *vmess.MemoryAccount
user, foundAEAD, errorAEAD := s.userValidator.GetAEAD(buffer.Bytes())
var fixedSizeAuthID [16]byte
copy(fixedSizeAuthID[:], buffer.Bytes())
switch {
case foundAEAD:
vmessAccount = user.Account.(*vmess.MemoryAccount)
var fixedSizeCmdKey [16]byte
copy(fixedSizeCmdKey[:], vmessAccount.ID.CmdKey())
aeadData, shouldDrain, bytesRead, errorReason := vmessaead.OpenVMessAEADHeader(fixedSizeCmdKey, fixedSizeAuthID, reader)
if errorReason != nil {
if shouldDrain {
drainer.AcknowledgeReceive(bytesRead)
return nil, drainConnection(newError("AEAD read failed").Base(errorReason))
}
return nil, drainConnection(newError("AEAD read failed, drain skipped").Base(errorReason))
}
decryptor = bytes.NewReader(aeadData)
s.isAEADRequest = true
case errorAEAD == vmessaead.ErrNotFound:
userLegacy, timestamp, valid, userValidationError := s.userValidator.Get(buffer.Bytes())
if !valid || userValidationError != nil {
return nil, drainConnection(newError("invalid user").Base(userValidationError))
}
if s.isAEADForced {
return nil, drainConnection(newError("invalid user: VMessAEAD is enforced and a non VMessAEAD connection is received. You can still disable this security feature with environment variable v2ray.vmess.aead.forced = false . You will not be able to enable legacy header workaround in the future."))
}
if s.userValidator.ShouldShowLegacyWarn() {
newError("Critical Warning: potentially invalid user: a non VMessAEAD connection is received. From 2022 Jan 1st, this kind of connection will be rejected by default. You should update or replace your client software now. This message will not be shown for further violation on this inbound.").AtWarning().WriteToLog()
}
user = userLegacy
iv := hashTimestamp(md5.New(), timestamp)
vmessAccount = userLegacy.Account.(*vmess.MemoryAccount)
aesStream := crypto.NewAesDecryptionStream(vmessAccount.ID.CmdKey(), iv)
decryptor = crypto.NewCryptionReader(aesStream, reader)
default:
return nil, drainConnection(newError("invalid user").Base(errorAEAD))
}
drainer.AcknowledgeReceive(int(buffer.Len()))
buffer.Clear()
if _, err := buffer.ReadFullFrom(decryptor, 38); err != nil {
return nil, newError("failed to read request header").Base(err)
}
request := &protocol.RequestHeader{
User: user,
Version: buffer.Byte(0),
}
copy(s.requestBodyIV[:], buffer.BytesRange(1, 17)) // 16 bytes
copy(s.requestBodyKey[:], buffer.BytesRange(17, 33)) // 16 bytes
var sid sessionID
copy(sid.user[:], vmessAccount.ID.Bytes())
sid.key = s.requestBodyKey
sid.nonce = s.requestBodyIV
if !s.sessionHistory.addIfNotExits(sid) {
if !s.isAEADRequest {
drainErr := s.userValidator.BurnTaintFuse(fixedSizeAuthID[:])
if drainErr != nil {
return nil, drainConnection(newError("duplicated session id, possibly under replay attack, and failed to taint userHash").Base(drainErr))
}
return nil, drainConnection(newError("duplicated session id, possibly under replay attack, userHash tainted"))
}
return nil, newError("duplicated session id, possibly under replay attack, but this is a AEAD request")
}
s.responseHeader = buffer.Byte(33) // 1 byte
request.Option = bitmask.Byte(buffer.Byte(34)) // 1 byte
paddingLen := int(buffer.Byte(35) >> 4)
request.Security = parseSecurityType(buffer.Byte(35) & 0x0F)
// 1 bytes reserved
request.Command = protocol.RequestCommand(buffer.Byte(37))
switch request.Command {
case protocol.RequestCommandMux:
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = 0
case protocol.RequestCommandTCP, protocol.RequestCommandUDP:
if addr, port, err := addrParser.ReadAddressPort(buffer, decryptor); err == nil {
request.Address = addr
request.Port = port
}
}
if paddingLen > 0 {
if _, err := buffer.ReadFullFrom(decryptor, int32(paddingLen)); err != nil {
if !s.isAEADRequest {
burnErr := s.userValidator.BurnTaintFuse(fixedSizeAuthID[:])
if burnErr != nil {
return nil, newError("failed to read padding, failed to taint userHash").Base(burnErr).Base(err)
}
return nil, newError("failed to read padding, userHash tainted").Base(err)
}
return nil, newError("failed to read padding").Base(err)
}
}
if _, err := buffer.ReadFullFrom(decryptor, 4); err != nil {
if !s.isAEADRequest {
burnErr := s.userValidator.BurnTaintFuse(fixedSizeAuthID[:])
if burnErr != nil {
return nil, newError("failed to read checksum, failed to taint userHash").Base(burnErr).Base(err)
}
return nil, newError("failed to read checksum, userHash tainted").Base(err)
}
return nil, newError("failed to read checksum").Base(err)
}
fnv1a := fnv.New32a()
common.Must2(fnv1a.Write(buffer.BytesTo(-4)))
actualHash := fnv1a.Sum32()
expectedHash := binary.BigEndian.Uint32(buffer.BytesFrom(-4))
if actualHash != expectedHash {
if !s.isAEADRequest {
Autherr := newError("invalid auth, legacy userHash tainted")
burnErr := s.userValidator.BurnTaintFuse(fixedSizeAuthID[:])
if burnErr != nil {
Autherr = newError("invalid auth, can't taint legacy userHash").Base(burnErr)
}
// It is possible that we are under attack described in https://github.com/v2ray/v2ray-core/issues/2523
return nil, drainConnection(Autherr)
}
return nil, newError("invalid auth, but this is a AEAD request")
}
if request.Address == nil {
return nil, newError("invalid remote address")
}
if request.Security == protocol.SecurityType_UNKNOWN || request.Security == protocol.SecurityType_AUTO {
return nil, newError("unknown security type: ", request.Security)
}
return request, nil
}
// DecodeRequestBody returns Reader from which caller can fetch decrypted body.
func (s *ServerSession) DecodeRequestBody(request *protocol.RequestHeader, reader io.Reader) (buf.Reader, error) {
var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{}
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeParser = NewShakeSizeParser(s.requestBodyIV[:])
}
var padding crypto.PaddingLengthGenerator
if request.Option.Has(protocol.RequestOptionGlobalPadding) {
var ok bool
padding, ok = sizeParser.(crypto.PaddingLengthGenerator)
if !ok {
return nil, newError("invalid option: RequestOptionGlobalPadding")
}
}
switch request.Security {
case protocol.SecurityType_NONE:
if request.Option.Has(protocol.RequestOptionChunkStream) {
if request.Command.TransferType() == protocol.TransferTypeStream {
return crypto.NewChunkStreamReader(sizeParser, reader), nil
}
auth := &crypto.AEADAuthenticator{
AEAD: new(NoOpAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding), nil
}
return buf.NewReader(reader), nil
case protocol.SecurityType_LEGACY:
aesStream := crypto.NewAesDecryptionStream(s.requestBodyKey[:], s.requestBodyIV[:])
cryptionReader := crypto.NewCryptionReader(aesStream, reader)
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationReader(auth, sizeParser, cryptionReader, request.Command.TransferType(), padding), nil
}
return buf.NewReader(cryptionReader), nil
case protocol.SecurityType_AES128_GCM:
aead := crypto.NewAesGcm(s.requestBodyKey[:])
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
AuthenticatedLengthKey := vmessaead.KDF16(s.requestBodyKey[:], "auth_len")
AuthenticatedLengthKeyAEAD := crypto.NewAesGcm(AuthenticatedLengthKey)
lengthAuth := &crypto.AEADAuthenticator{
AEAD: AuthenticatedLengthKeyAEAD,
NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser = NewAEADSizeParser(lengthAuth)
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding), nil
case protocol.SecurityType_CHACHA20_POLY1305:
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.requestBodyKey[:]))
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
AuthenticatedLengthKey := vmessaead.KDF16(s.requestBodyKey[:], "auth_len")
AuthenticatedLengthKeyAEAD, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(AuthenticatedLengthKey))
common.Must(err)
lengthAuth := &crypto.AEADAuthenticator{
AEAD: AuthenticatedLengthKeyAEAD,
NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser = NewAEADSizeParser(lengthAuth)
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding), nil
default:
return nil, newError("invalid option: Security")
}
}
// EncodeResponseHeader writes encoded response header into the given writer.
func (s *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) {
var encryptionWriter io.Writer
if !s.isAEADRequest {
s.responseBodyKey = md5.Sum(s.requestBodyKey[:])
s.responseBodyIV = md5.Sum(s.requestBodyIV[:])
} else {
BodyKey := sha256.Sum256(s.requestBodyKey[:])
copy(s.responseBodyKey[:], BodyKey[:16])
BodyIV := sha256.Sum256(s.requestBodyIV[:])
copy(s.responseBodyIV[:], BodyIV[:16])
}
aesStream := crypto.NewAesEncryptionStream(s.responseBodyKey[:], s.responseBodyIV[:])
encryptionWriter = crypto.NewCryptionWriter(aesStream, writer)
s.responseWriter = encryptionWriter
aeadEncryptedHeaderBuffer := bytes.NewBuffer(nil)
if s.isAEADRequest {
encryptionWriter = aeadEncryptedHeaderBuffer
}
common.Must2(encryptionWriter.Write([]byte{s.responseHeader, byte(header.Option)}))
err := MarshalCommand(header.Command, encryptionWriter)
if err != nil {
common.Must2(encryptionWriter.Write([]byte{0x00, 0x00}))
}
if s.isAEADRequest {
aeadResponseHeaderLengthEncryptionKey := vmessaead.KDF16(s.responseBodyKey[:], vmessaead.KDFSaltConstAEADRespHeaderLenKey)
aeadResponseHeaderLengthEncryptionIV := vmessaead.KDF(s.responseBodyIV[:], vmessaead.KDFSaltConstAEADRespHeaderLenIV)[:12]
aeadResponseHeaderLengthEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderLengthEncryptionKey)).(cipher.Block)
aeadResponseHeaderLengthEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderLengthEncryptionKeyAESBlock)).(cipher.AEAD)
aeadResponseHeaderLengthEncryptionBuffer := bytes.NewBuffer(nil)
decryptedResponseHeaderLengthBinaryDeserializeBuffer := uint16(aeadEncryptedHeaderBuffer.Len())
common.Must(binary.Write(aeadResponseHeaderLengthEncryptionBuffer, binary.BigEndian, decryptedResponseHeaderLengthBinaryDeserializeBuffer))
AEADEncryptedLength := aeadResponseHeaderLengthEncryptionAEAD.Seal(nil, aeadResponseHeaderLengthEncryptionIV, aeadResponseHeaderLengthEncryptionBuffer.Bytes(), nil)
common.Must2(io.Copy(writer, bytes.NewReader(AEADEncryptedLength)))
aeadResponseHeaderPayloadEncryptionKey := vmessaead.KDF16(s.responseBodyKey[:], vmessaead.KDFSaltConstAEADRespHeaderPayloadKey)
aeadResponseHeaderPayloadEncryptionIV := vmessaead.KDF(s.responseBodyIV[:], vmessaead.KDFSaltConstAEADRespHeaderPayloadIV)[:12]
aeadResponseHeaderPayloadEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderPayloadEncryptionKey)).(cipher.Block)
aeadResponseHeaderPayloadEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderPayloadEncryptionKeyAESBlock)).(cipher.AEAD)
aeadEncryptedHeaderPayload := aeadResponseHeaderPayloadEncryptionAEAD.Seal(nil, aeadResponseHeaderPayloadEncryptionIV, aeadEncryptedHeaderBuffer.Bytes(), nil)
common.Must2(io.Copy(writer, bytes.NewReader(aeadEncryptedHeaderPayload)))
}
}
// EncodeResponseBody returns a Writer that auto-encrypt content written by caller.
func (s *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{}
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeParser = NewShakeSizeParser(s.responseBodyIV[:])
}
var padding crypto.PaddingLengthGenerator
if request.Option.Has(protocol.RequestOptionGlobalPadding) {
var ok bool
padding, ok = sizeParser.(crypto.PaddingLengthGenerator)
if !ok {
return nil, newError("invalid option: RequestOptionGlobalPadding")
}
}
switch request.Security {
case protocol.SecurityType_NONE:
if request.Option.Has(protocol.RequestOptionChunkStream) {
if request.Command.TransferType() == protocol.TransferTypeStream {
return crypto.NewChunkStreamWriter(sizeParser, writer), nil
}
auth := &crypto.AEADAuthenticator{
AEAD: new(NoOpAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding), nil
}
return buf.NewWriter(writer), nil
case protocol.SecurityType_LEGACY:
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationWriter(auth, sizeParser, s.responseWriter, request.Command.TransferType(), padding), nil
}
return &buf.SequentialWriter{Writer: s.responseWriter}, nil
case protocol.SecurityType_AES128_GCM:
aead := crypto.NewAesGcm(s.responseBodyKey[:])
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
AuthenticatedLengthKey := vmessaead.KDF16(s.requestBodyKey[:], "auth_len")
AuthenticatedLengthKeyAEAD := crypto.NewAesGcm(AuthenticatedLengthKey)
lengthAuth := &crypto.AEADAuthenticator{
AEAD: AuthenticatedLengthKeyAEAD,
NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser = NewAEADSizeParser(lengthAuth)
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding), nil
case protocol.SecurityType_CHACHA20_POLY1305:
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.responseBodyKey[:]))
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
AuthenticatedLengthKey := vmessaead.KDF16(s.requestBodyKey[:], "auth_len")
AuthenticatedLengthKeyAEAD, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(AuthenticatedLengthKey))
common.Must(err)
lengthAuth := &crypto.AEADAuthenticator{
AEAD: AuthenticatedLengthKeyAEAD,
NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
sizeParser = NewAEADSizeParser(lengthAuth)
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding), nil
default:
return nil, newError("invalid option: Security")
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/encoding/encoding_test.go | proxy/vmess/encoding/encoding_test.go | package encoding_test
import (
"context"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
. "github.com/v2fly/v2ray-core/v5/proxy/vmess/encoding"
)
func toAccount(a *vmess.Account) protocol.Account {
account, err := a.AsAccount()
common.Must(err)
return account
}
func TestRequestSerialization(t *testing.T) {
user := &protocol.MemoryUser{
Level: 0,
Email: "test@v2fly.org",
}
id := uuid.New()
account := &vmess.Account{
Id: id.String(),
AlterId: 0,
}
user.Account = toAccount(account)
expectedRequest := &protocol.RequestHeader{
Version: 1,
User: user,
Command: protocol.RequestCommandTCP,
Address: net.DomainAddress("www.v2fly.org"),
Port: net.Port(443),
Security: protocol.SecurityType_AES128_GCM,
}
buffer := buf.New()
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash, 0)
common.Must(client.EncodeRequestHeader(expectedRequest, buffer))
buffer2 := buf.New()
buffer2.Write(buffer.Bytes())
sessionHistory := NewSessionHistory()
defer common.Close(sessionHistory)
userValidator := vmess.NewTimedUserValidator(protocol.DefaultIDHash)
userValidator.Add(user)
defer common.Close(userValidator)
server := NewServerSession(userValidator, sessionHistory)
actualRequest, err := server.DecodeRequestHeader(buffer)
common.Must(err)
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
_, err = server.DecodeRequestHeader(buffer2)
// anti replay attack
if err == nil {
t.Error("nil error")
}
}
func TestInvalidRequest(t *testing.T) {
user := &protocol.MemoryUser{
Level: 0,
Email: "test@v2fly.org",
}
id := uuid.New()
account := &vmess.Account{
Id: id.String(),
AlterId: 0,
}
user.Account = toAccount(account)
expectedRequest := &protocol.RequestHeader{
Version: 1,
User: user,
Command: protocol.RequestCommand(100),
Address: net.DomainAddress("www.v2fly.org"),
Port: net.Port(443),
Security: protocol.SecurityType_AES128_GCM,
}
buffer := buf.New()
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash, 0)
common.Must(client.EncodeRequestHeader(expectedRequest, buffer))
buffer2 := buf.New()
buffer2.Write(buffer.Bytes())
sessionHistory := NewSessionHistory()
defer common.Close(sessionHistory)
userValidator := vmess.NewTimedUserValidator(protocol.DefaultIDHash)
userValidator.Add(user)
defer common.Close(userValidator)
server := NewServerSession(userValidator, sessionHistory)
_, err := server.DecodeRequestHeader(buffer)
if err == nil {
t.Error("nil error")
}
}
func TestMuxRequest(t *testing.T) {
user := &protocol.MemoryUser{
Level: 0,
Email: "test@v2fly.org",
}
id := uuid.New()
account := &vmess.Account{
Id: id.String(),
AlterId: 0,
}
user.Account = toAccount(account)
expectedRequest := &protocol.RequestHeader{
Version: 1,
User: user,
Command: protocol.RequestCommandMux,
Security: protocol.SecurityType_AES128_GCM,
Address: net.DomainAddress("v1.mux.cool"),
}
buffer := buf.New()
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash, 0)
common.Must(client.EncodeRequestHeader(expectedRequest, buffer))
buffer2 := buf.New()
buffer2.Write(buffer.Bytes())
sessionHistory := NewSessionHistory()
defer common.Close(sessionHistory)
userValidator := vmess.NewTimedUserValidator(protocol.DefaultIDHash)
userValidator.Add(user)
defer common.Close(userValidator)
server := NewServerSession(userValidator, sessionHistory)
actualRequest, err := server.DecodeRequestHeader(buffer)
common.Must(err)
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/encoding/auth.go | proxy/vmess/encoding/auth.go | package encoding
import (
"crypto/md5"
"encoding/binary"
"hash/fnv"
"golang.org/x/crypto/sha3"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/crypto"
)
// Authenticate authenticates a byte array using Fnv hash.
func Authenticate(b []byte) uint32 {
fnv1hash := fnv.New32a()
common.Must2(fnv1hash.Write(b))
return fnv1hash.Sum32()
}
type NoOpAuthenticator struct{}
func (NoOpAuthenticator) NonceSize() int {
return 0
}
func (NoOpAuthenticator) Overhead() int {
return 0
}
// Seal implements AEAD.Seal().
func (NoOpAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
return append(dst[:0], plaintext...)
}
// Open implements AEAD.Open().
func (NoOpAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
return append(dst[:0], ciphertext...), nil
}
// FnvAuthenticator is an AEAD based on Fnv hash.
type FnvAuthenticator struct{}
// NonceSize implements AEAD.NonceSize().
func (*FnvAuthenticator) NonceSize() int {
return 0
}
// Overhead impelements AEAD.Overhead().
func (*FnvAuthenticator) Overhead() int {
return 4
}
// Seal implements AEAD.Seal().
func (*FnvAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
dst = append(dst, 0, 0, 0, 0)
binary.BigEndian.PutUint32(dst, Authenticate(plaintext))
return append(dst, plaintext...)
}
// Open implements AEAD.Open().
func (*FnvAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
if binary.BigEndian.Uint32(ciphertext[:4]) != Authenticate(ciphertext[4:]) {
return dst, newError("invalid authentication")
}
return append(dst, ciphertext[4:]...), nil
}
// GenerateChacha20Poly1305Key generates a 32-byte key from a given 16-byte array.
func GenerateChacha20Poly1305Key(b []byte) []byte {
key := make([]byte, 32)
t := md5.Sum(b)
copy(key, t[:])
t = md5.Sum(key[:16])
copy(key[16:], t[:])
return key
}
type ShakeSizeParser struct {
shake sha3.ShakeHash
buffer [2]byte
}
func NewShakeSizeParser(nonce []byte) *ShakeSizeParser {
shake := sha3.NewShake128()
common.Must2(shake.Write(nonce))
return &ShakeSizeParser{
shake: shake,
}
}
func (*ShakeSizeParser) SizeBytes() int32 {
return 2
}
func (s *ShakeSizeParser) next() uint16 {
common.Must2(s.shake.Read(s.buffer[:]))
return binary.BigEndian.Uint16(s.buffer[:])
}
func (s *ShakeSizeParser) Decode(b []byte) (uint16, error) {
mask := s.next()
size := binary.BigEndian.Uint16(b)
return mask ^ size, nil
}
func (s *ShakeSizeParser) Encode(size uint16, b []byte) []byte {
mask := s.next()
binary.BigEndian.PutUint16(b, mask^size)
return b[:2]
}
func (s *ShakeSizeParser) NextPaddingLen() uint16 {
return s.next() % 64
}
func (s *ShakeSizeParser) MaxPaddingLen() uint16 {
return 64
}
type AEADSizeParser struct {
crypto.AEADChunkSizeParser
}
func NewAEADSizeParser(auth *crypto.AEADAuthenticator) *AEADSizeParser {
return &AEADSizeParser{crypto.AEADChunkSizeParser{Auth: auth}}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proxy/vmess/encoding/encoding.go | proxy/vmess/encoding/encoding.go | package encoding
import (
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
const (
Version = byte(1)
)
var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv4), net.AddressFamilyIPv4),
protocol.AddressFamilyByte(byte(protocol.AddressTypeDomain), net.AddressFamilyDomain),
protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv6), net.AddressFamilyIPv6),
protocol.PortThenAddress(),
)
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.