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/common/protocol/udp/udp.go | common/protocol/udp/udp.go | package udp
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/dns/errors.generated.go | common/protocol/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/common/protocol/dns/io.go | common/protocol/dns/io.go | package dns
import (
"encoding/binary"
"sync"
"golang.org/x/net/dns/dnsmessage"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/serial"
)
func PackMessage(msg *dnsmessage.Message) (*buf.Buffer, error) {
buffer := buf.New()
rawBytes := buffer.Extend(buf.Size)
packed, err := msg.AppendPack(rawBytes[:0])
if err != nil {
buffer.Release()
return nil, err
}
buffer.Resize(0, int32(len(packed)))
return buffer, nil
}
type MessageReader interface {
ReadMessage() (*buf.Buffer, error)
}
type UDPReader struct {
buf.Reader
access sync.Mutex
cache buf.MultiBuffer
}
func (r *UDPReader) readCache() *buf.Buffer {
r.access.Lock()
defer r.access.Unlock()
mb, b := buf.SplitFirst(r.cache)
r.cache = mb
return b
}
func (r *UDPReader) refill() error {
mb, err := r.Reader.ReadMultiBuffer()
if err != nil {
return err
}
r.access.Lock()
r.cache = mb
r.access.Unlock()
return nil
}
// ReadMessage implements MessageReader.
func (r *UDPReader) ReadMessage() (*buf.Buffer, error) {
for {
b := r.readCache()
if b != nil {
return b, nil
}
if err := r.refill(); err != nil {
return nil, err
}
}
}
// Close implements common.Closable.
func (r *UDPReader) Close() error {
defer func() {
r.access.Lock()
buf.ReleaseMulti(r.cache)
r.cache = nil
r.access.Unlock()
}()
return common.Close(r.Reader)
}
type TCPReader struct {
reader *buf.BufferedReader
}
func NewTCPReader(reader buf.Reader) *TCPReader {
return &TCPReader{
reader: &buf.BufferedReader{
Reader: reader,
},
}
}
func (r *TCPReader) ReadMessage() (*buf.Buffer, error) {
size, err := serial.ReadUint16(r.reader)
if err != nil {
return nil, err
}
if size > buf.Size {
return nil, newError("message size too large: ", size)
}
b := buf.New()
if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil {
return nil, err
}
return b, nil
}
func (r *TCPReader) Interrupt() {
common.Interrupt(r.reader)
}
func (r *TCPReader) Close() error {
return common.Close(r.reader)
}
type MessageWriter interface {
WriteMessage(msg *buf.Buffer) error
}
type UDPWriter struct {
buf.Writer
}
func (w *UDPWriter) WriteMessage(b *buf.Buffer) error {
return w.WriteMultiBuffer(buf.MultiBuffer{b})
}
type TCPWriter struct {
buf.Writer
}
func (w *TCPWriter) WriteMessage(b *buf.Buffer) error {
if b.IsEmpty() {
return nil
}
mb := make(buf.MultiBuffer, 0, 2)
size := buf.New()
binary.BigEndian.PutUint16(size.Extend(2), uint16(b.Len()))
mb = append(mb, size, b)
return w.WriteMultiBuffer(mb)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/bittorrent/bittorrent.go | common/protocol/bittorrent/bittorrent.go | package bittorrent
import (
"encoding/binary"
"errors"
"math"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
)
type SniffHeader struct{}
func (h *SniffHeader) Protocol() string {
return "bittorrent"
}
func (h *SniffHeader) Domain() string {
return ""
}
var errNotBittorrent = errors.New("not bittorrent header")
func SniffBittorrent(b []byte) (*SniffHeader, error) {
if len(b) < 20 {
return nil, common.ErrNoClue
}
if b[0] == 19 && string(b[1:20]) == "BitTorrent protocol" {
return &SniffHeader{}, nil
}
return nil, errNotBittorrent
}
func SniffUTP(b []byte) (*SniffHeader, error) {
if len(b) < 20 {
return nil, common.ErrNoClue
}
buffer := buf.FromBytes(b)
var typeAndVersion uint8
if binary.Read(buffer, binary.BigEndian, &typeAndVersion) != nil {
return nil, common.ErrNoClue
} else if b[0]>>4&0xF > 4 || b[0]&0xF != 1 {
return nil, errNotBittorrent
}
var extension uint8
if binary.Read(buffer, binary.BigEndian, &extension) != nil {
return nil, common.ErrNoClue
} else if extension != 0 && extension != 1 {
return nil, errNotBittorrent
}
for extension != 0 {
if extension != 1 {
return nil, errNotBittorrent
}
if binary.Read(buffer, binary.BigEndian, &extension) != nil {
return nil, common.ErrNoClue
}
var length uint8
if err := binary.Read(buffer, binary.BigEndian, &length); err != nil {
return nil, common.ErrNoClue
}
if common.Error2(buffer.ReadBytes(int32(length))) != nil {
return nil, common.ErrNoClue
}
}
if common.Error2(buffer.ReadBytes(2)) != nil {
return nil, common.ErrNoClue
}
var timestamp uint32
if err := binary.Read(buffer, binary.BigEndian, ×tamp); err != nil {
return nil, common.ErrNoClue
}
if math.Abs(float64(time.Now().UnixMicro()-int64(timestamp))) > float64(24*time.Hour) {
return nil, errNotBittorrent
}
return &SniffHeader{}, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/http/sniff.go | common/protocol/http/sniff.go | package http
import (
"bytes"
"errors"
"strings"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
)
type version byte
type SniffHeader struct {
host string
}
func (h *SniffHeader) Protocol() string {
return "http1"
}
func (h *SniffHeader) Domain() string {
return h.host
}
var (
// refer to https://pkg.go.dev/net/http@master#pkg-constants
methods = [...]string{"get", "post", "head", "put", "delete", "options", "connect", "patch", "trace"}
errNotHTTPMethod = errors.New("not an HTTP method")
)
func beginWithHTTPMethod(b []byte) error {
for _, m := range &methods {
if len(b) >= len(m) && strings.EqualFold(string(b[:len(m)]), m) {
return nil
}
if len(b) < len(m) {
return common.ErrNoClue
}
}
return errNotHTTPMethod
}
func SniffHTTP(b []byte) (*SniffHeader, error) {
if err := beginWithHTTPMethod(b); err != nil {
return nil, err
}
sh := &SniffHeader{}
headers := bytes.Split(b, []byte{'\n'})
for i := 1; i < len(headers); i++ {
header := headers[i]
if len(header) == 0 {
break
}
parts := bytes.SplitN(header, []byte{':'}, 2)
if len(parts) != 2 {
continue
}
key := strings.ToLower(string(parts[0]))
if key == "host" {
rawHost := strings.ToLower(string(bytes.TrimSpace(parts[1])))
dest, err := ParseHost(rawHost, net.Port(80))
if err != nil {
return nil, err
}
sh.host = dest.Address.String()
}
}
if len(sh.host) > 0 {
return sh, nil
}
return nil, common.ErrNoClue
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/http/headers_test.go | common/protocol/http/headers_test.go | package http_test
import (
"bufio"
"net/http"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
. "github.com/v2fly/v2ray-core/v5/common/protocol/http"
)
func TestParseXForwardedFor(t *testing.T) {
header := http.Header{}
header.Add("X-Forwarded-For", "129.78.138.66, 129.78.64.103")
addrs := ParseXForwardedFor(header)
if r := cmp.Diff(addrs, []net.Address{net.ParseAddress("129.78.138.66"), net.ParseAddress("129.78.64.103")}); r != "" {
t.Error(r)
}
}
func TestHopByHopHeadersRemoving(t *testing.T) {
rawRequest := `GET /pkg/net/http/ HTTP/1.1
Host: golang.org
Connection: keep-alive,Foo, Bar
Foo: foo
Bar: bar
Proxy-Connection: keep-alive
Proxy-Authenticate: abc
Accept-Encoding: gzip
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7
Cache-Control: no-cache
Accept-Language: de,en;q=0.7,en-us;q=0.3
`
b := bufio.NewReader(strings.NewReader(rawRequest))
req, err := http.ReadRequest(b)
common.Must(err)
headers := []struct {
Key string
Value string
}{
{
Key: "Foo",
Value: "foo",
},
{
Key: "Bar",
Value: "bar",
},
{
Key: "Connection",
Value: "keep-alive,Foo, Bar",
},
{
Key: "Proxy-Connection",
Value: "keep-alive",
},
{
Key: "Proxy-Authenticate",
Value: "abc",
},
}
for _, header := range headers {
if v := req.Header.Get(header.Key); v != header.Value {
t.Error("header ", header.Key, " = ", v, " want ", header.Value)
}
}
RemoveHopByHopHeaders(req.Header)
for _, header := range []string{"Connection", "Foo", "Bar", "Proxy-Connection", "Proxy-Authenticate"} {
if v := req.Header.Get(header); v != "" {
t.Error("header ", header, " = ", v)
}
}
}
func TestParseHost(t *testing.T) {
testCases := []struct {
RawHost string
DefaultPort net.Port
Destination net.Destination
Error bool
}{
{
RawHost: "v2fly.org:80",
DefaultPort: 443,
Destination: net.TCPDestination(net.DomainAddress("v2fly.org"), 80),
},
{
RawHost: "tls.v2fly.org",
DefaultPort: 443,
Destination: net.TCPDestination(net.DomainAddress("tls.v2fly.org"), 443),
},
{
RawHost: "[2401:1bc0:51f0:ec08::1]:80",
DefaultPort: 443,
Destination: net.TCPDestination(net.ParseAddress("[2401:1bc0:51f0:ec08::1]"), 80),
},
}
for _, testCase := range testCases {
dest, err := ParseHost(testCase.RawHost, testCase.DefaultPort)
if testCase.Error {
if err == nil {
t.Error("for test case: ", testCase.RawHost, " expected error, but actually nil")
}
} else {
if dest != testCase.Destination {
t.Error("for test case: ", testCase.RawHost, " expected host: ", testCase.Destination.String(), " but got ", dest.String())
}
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/http/sniff_test.go | common/protocol/http/sniff_test.go | package http_test
import (
"testing"
. "github.com/v2fly/v2ray-core/v5/common/protocol/http"
)
func TestHTTPHeaders(t *testing.T) {
cases := []struct {
input string
domain string
err bool
}{
{
input: `GET /tutorials/other/top-20-mysql-best-practices/ HTTP/1.1
Host: net.tutsplus.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120
Pragma: no-cache
Cache-Control: no-cache`,
domain: "net.tutsplus.com",
},
{
input: `POST /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
first_name=John&last_name=Doe&action=Submit`,
domain: "localhost",
},
{
input: `X /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
first_name=John&last_name=Doe&action=Submit`,
domain: "",
err: true,
},
{
input: `GET /foo.php HTTP/1.1
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
Host: localhost
first_name=John&last_name=Doe&action=Submit`,
domain: "",
err: true,
},
{
input: `GET /tutorials/other/top-20-mysql-best-practices/ HTTP/1.1`,
domain: "",
err: true,
},
}
for _, test := range cases {
header, err := SniffHTTP([]byte(test.input))
if test.err {
if err == nil {
t.Errorf("Expect error but nil, in test: %v", test)
}
} else {
if err != nil {
t.Errorf("Expect no error but actually %s in test %v", err.Error(), test)
}
if header.Domain() != test.domain {
t.Error("expected domain ", test.domain, " but got ", header.Domain())
}
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/common/protocol/http/headers.go | common/protocol/http/headers.go | package http
import (
"net/http"
"strconv"
"strings"
"github.com/v2fly/v2ray-core/v5/common/net"
)
// ParseXForwardedFor parses X-Forwarded-For header in http headers, and return the IP list in it.
func ParseXForwardedFor(header http.Header) []net.Address {
xff := header.Get("X-Forwarded-For")
if xff == "" {
return nil
}
list := strings.Split(xff, ",")
addrs := make([]net.Address, 0, len(list))
for _, proxy := range list {
addrs = append(addrs, net.ParseAddress(proxy))
}
return addrs
}
// RemoveHopByHopHeaders remove hop by hop headers in http header list.
func RemoveHopByHopHeaders(header http.Header) {
// Strip hop-by-hop header based on RFC:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
header.Del("Proxy-Connection")
header.Del("Proxy-Authenticate")
header.Del("Proxy-Authorization")
header.Del("TE")
header.Del("Trailers")
header.Del("Transfer-Encoding")
header.Del("Upgrade")
header.Del("Keep-Alive")
connections := header.Get("Connection")
header.Del("Connection")
if connections == "" {
return
}
for _, h := range strings.Split(connections, ",") {
header.Del(strings.TrimSpace(h))
}
}
// ParseHost splits host and port from a raw string. Default port is used when raw string doesn't contain port.
func ParseHost(rawHost string, defaultPort net.Port) (net.Destination, error) {
port := defaultPort
host, rawPort, err := net.SplitHostPort(rawHost)
if err != nil {
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
host = rawHost
} else {
return net.Destination{}, err
}
} else if len(rawPort) > 0 {
intPort, err := strconv.ParseUint(rawPort, 0, 16)
if err != nil {
return net.Destination{}, err
}
port = net.Port(intPort)
}
return net.TCPDestination(net.ParseAddress(host), port), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/errors.generated.go | main/errors.generated.go | package main
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/main/main_test.go | main/main_test.go | //go:build coveragemain
// +build coveragemain
package main
import (
"testing"
)
func TestRunMainForCoverage(t *testing.T) {
main()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/main.go | main/main.go | package main
import (
"github.com/v2fly/v2ray-core/v5/main/commands"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
_ "github.com/v2fly/v2ray-core/v5/main/distro/all"
)
func main() {
base.RootCommand.Long = "A unified platform for anti-censorship."
base.RegisterCommand(commands.CmdRun)
base.RegisterCommand(commands.CmdVersion)
base.RegisterCommand(commands.CmdTest)
base.SortLessFunc = runIsTheFirst
base.SortCommands()
base.Execute()
}
func runIsTheFirst(i, j *base.Command) bool {
left := i.Name()
right := j.Name()
if left == "run" {
return true
}
if right == "run" {
return false
}
return left < right
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/distro/all/all.go | main/distro/all/all.go | package all
import (
// The following are necessary as they register handlers in their init functions.
// Mandatory features. Can't remove unless there are replacements.
_ "github.com/v2fly/v2ray-core/v5/app/dispatcher"
_ "github.com/v2fly/v2ray-core/v5/app/proxyman/inbound"
_ "github.com/v2fly/v2ray-core/v5/app/proxyman/outbound"
// Default commander and all its services. This is an optional feature.
_ "github.com/v2fly/v2ray-core/v5/app/commander"
_ "github.com/v2fly/v2ray-core/v5/app/log/command"
_ "github.com/v2fly/v2ray-core/v5/app/proxyman/command"
_ "github.com/v2fly/v2ray-core/v5/app/stats/command"
// Developer preview services
_ "github.com/v2fly/v2ray-core/v5/app/instman/command"
_ "github.com/v2fly/v2ray-core/v5/app/observatory/command"
// Other optional features.
_ "github.com/v2fly/v2ray-core/v5/app/dns"
_ "github.com/v2fly/v2ray-core/v5/app/dns/fakedns"
_ "github.com/v2fly/v2ray-core/v5/app/log"
_ "github.com/v2fly/v2ray-core/v5/app/policy"
_ "github.com/v2fly/v2ray-core/v5/app/reverse"
_ "github.com/v2fly/v2ray-core/v5/app/router"
_ "github.com/v2fly/v2ray-core/v5/app/stats"
// Fix dependency cycle caused by core import in internet package
_ "github.com/v2fly/v2ray-core/v5/transport/internet/tagged/taggedimpl"
// Developer preview features
_ "github.com/v2fly/v2ray-core/v5/app/commander/webcommander"
_ "github.com/v2fly/v2ray-core/v5/app/instman"
_ "github.com/v2fly/v2ray-core/v5/app/observatory"
_ "github.com/v2fly/v2ray-core/v5/app/persistentstorage/filesystemstorage"
_ "github.com/v2fly/v2ray-core/v5/app/tun"
// Inbound and outbound proxies.
_ "github.com/v2fly/v2ray-core/v5/proxy/blackhole"
_ "github.com/v2fly/v2ray-core/v5/proxy/dns"
_ "github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
_ "github.com/v2fly/v2ray-core/v5/proxy/freedom"
_ "github.com/v2fly/v2ray-core/v5/proxy/http"
_ "github.com/v2fly/v2ray-core/v5/proxy/shadowsocks"
_ "github.com/v2fly/v2ray-core/v5/proxy/socks"
_ "github.com/v2fly/v2ray-core/v5/proxy/trojan"
_ "github.com/v2fly/v2ray-core/v5/proxy/vless/inbound"
_ "github.com/v2fly/v2ray-core/v5/proxy/vless/outbound"
_ "github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
_ "github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
// Developer preview proxies
_ "github.com/v2fly/v2ray-core/v5/proxy/vlite/inbound"
_ "github.com/v2fly/v2ray-core/v5/proxy/vlite/outbound"
_ "github.com/v2fly/v2ray-core/v5/proxy/hysteria2"
_ "github.com/v2fly/v2ray-core/v5/proxy/shadowsocks2022"
// Transports
_ "github.com/v2fly/v2ray-core/v5/transport/internet/domainsocket"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/grpc"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/http"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/kcp"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/quic"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/tcp"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/tls"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/tls/utls"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/udp"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/websocket"
// Developer preview transports
_ "github.com/v2fly/v2ray-core/v5/transport/internet/request/assembly"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/request/assembler/simple"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/request/roundtripper/httprt"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/request/assembler/packetconn"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/request/stereotype/meek"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/request/stereotype/mekya"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/request/roundtripperreverserserver/clicommand"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/dtls"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/httpupgrade"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/hysteria2"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/tlsmirror/mirrorenrollment/roundtripperenrollmentconfirmation"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/tlsmirror/server"
// Transport headers
_ "github.com/v2fly/v2ray-core/v5/transport/internet/headers/http"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/headers/noop"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/headers/srtp"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/headers/tls"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/headers/utp"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/headers/wechat"
_ "github.com/v2fly/v2ray-core/v5/transport/internet/headers/wireguard"
// Geo loaders
_ "github.com/v2fly/v2ray-core/v5/infra/conf/geodata/memconservative"
_ "github.com/v2fly/v2ray-core/v5/infra/conf/geodata/standard"
// JSON, TOML, YAML config support. (jsonv4) This disable selective compile
_ "github.com/v2fly/v2ray-core/v5/main/formats"
// commands
_ "github.com/v2fly/v2ray-core/v5/main/commands/all"
// engineering commands
_ "github.com/v2fly/v2ray-core/v5/main/commands/all/engineering"
_ "github.com/v2fly/v2ray-core/v5/main/commands/all/engineering/generateRandomData"
// Commands that rely on jsonv4 format This disable selective compile
_ "github.com/v2fly/v2ray-core/v5/main/commands/all/api/jsonv4"
_ "github.com/v2fly/v2ray-core/v5/main/commands/all/jsonv4"
// V5 version of json configure file parser
_ "github.com/v2fly/v2ray-core/v5/infra/conf/v5cfg"
// Simplified config
_ "github.com/v2fly/v2ray-core/v5/proxy/http/simplified"
_ "github.com/v2fly/v2ray-core/v5/proxy/shadowsocks/simplified"
_ "github.com/v2fly/v2ray-core/v5/proxy/socks/simplified"
_ "github.com/v2fly/v2ray-core/v5/proxy/trojan/simplified"
// Subscription Supports
_ "github.com/v2fly/v2ray-core/v5/app/subscription/subscriptionmanager"
_ "github.com/v2fly/v2ray-core/v5/app/subscription/subscriptionmanager/command"
// Subscription Containers: general purpose
_ "github.com/v2fly/v2ray-core/v5/app/subscription/containers/base64urlline"
_ "github.com/v2fly/v2ray-core/v5/app/subscription/containers/dataurlsingle"
_ "github.com/v2fly/v2ray-core/v5/app/subscription/containers/jsonfieldarray"
_ "github.com/v2fly/v2ray-core/v5/app/subscription/containers/jsonfieldarray/jsonified"
_ "github.com/v2fly/v2ray-core/v5/app/subscription/containers/urlline"
// Subscription Fetchers
_ "github.com/v2fly/v2ray-core/v5/app/subscription/documentfetcher/dataurlfetcher"
_ "github.com/v2fly/v2ray-core/v5/app/subscription/documentfetcher/httpfetcher"
// Subscription Entries Converters
_ "github.com/v2fly/v2ray-core/v5/app/subscription/entries/nonnative"
_ "github.com/v2fly/v2ray-core/v5/app/subscription/entries/outbound" // Natively Supported Outbound Format
)
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/distro/debug/debug.go | main/distro/debug/debug.go | package debug
import (
"net/http"
)
func init() {
go func() {
http.ListenAndServe(":6060", nil)
}()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/errors.generated.go | main/commands/errors.generated.go | package commands
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/main/commands/run.go | main/commands/run.go | package commands
import (
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common/cmdarg"
"github.com/v2fly/v2ray-core/v5/common/platform"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
"github.com/v2fly/v2ray-core/v5/main/plugins"
)
// CmdRun runs V2Ray with config
var CmdRun = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} run [-c config.json] [-d dir]",
Short: "run V2Ray with config",
Long: `
Run V2Ray with config.
{{.Exec}} will also use the config directory specified by environment
variable "v2ray.location.confdir". If no config found, it tries
to load config from one of below:
1. The default "config.json" in the current directory
2. The config file from ENV "v2ray.location.config"
3. The stdin if all failed above
Arguments:
-c, -config <file>
Config file for V2Ray. Multiple assign is accepted.
-d, -confdir <dir>
A directory with config files. Multiple assign is accepted.
-r
Load confdir recursively.
-format <format>
Format of config input. (default "auto")
Examples:
{{.Exec}} {{.LongName}} -c config.json
{{.Exec}} {{.LongName}} -d path/to/dir
Use "{{.Exec}} help format-loader" for more information about format.
`,
Run: executeRun,
}
var (
configFiles cmdarg.Arg
configDirs cmdarg.Arg
configFormat *string
configDirRecursively *bool
)
func setConfigFlags(cmd *base.Command) {
configFormat = cmd.Flag.String("format", core.FormatAuto, "")
configDirRecursively = cmd.Flag.Bool("r", false, "")
cmd.Flag.Var(&configFiles, "config", "")
cmd.Flag.Var(&configFiles, "c", "")
cmd.Flag.Var(&configDirs, "confdir", "")
cmd.Flag.Var(&configDirs, "d", "")
}
func executeRun(cmd *base.Command, args []string) {
setConfigFlags(cmd)
var pluginFuncs []func() error
for _, plugin := range plugins.Plugins {
if f := plugin(cmd); f != nil {
pluginFuncs = append(pluginFuncs, f)
}
}
cmd.Flag.Parse(args)
printVersion()
configFiles = getConfigFilePath()
server, err := startV2Ray()
if err != nil {
base.Fatalf("Failed to start: %s", err)
}
for _, f := range pluginFuncs {
go func(f func() error) {
if err := f(); err != nil {
log.Print(err)
}
}(f)
}
if err := server.Start(); err != nil {
base.Fatalf("Failed to start: %s", err)
}
defer server.Close()
// Explicitly triggering GC to remove garbage from config loading.
runtime.GC()
{
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
<-osSignals
}
}
func fileExists(file string) bool {
info, err := os.Stat(file)
return err == nil && !info.IsDir()
}
func dirExists(file string) bool {
if file == "" {
return false
}
info, err := os.Stat(file)
return err == nil && info.IsDir()
}
func readConfDir(dirPath string, extension []string) cmdarg.Arg {
confs, err := os.ReadDir(dirPath)
if err != nil {
base.Fatalf("failed to read dir %s: %s", dirPath, err)
}
files := make(cmdarg.Arg, 0)
for _, f := range confs {
ext := filepath.Ext(f.Name())
for _, e := range extension {
if strings.EqualFold(e, ext) {
files.Set(filepath.Join(dirPath, f.Name()))
break
}
}
}
return files
}
// getFolderFiles get files in the folder and it's children
func readConfDirRecursively(dirPath string, extension []string) cmdarg.Arg {
files := make(cmdarg.Arg, 0)
err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
ext := filepath.Ext(path)
for _, e := range extension {
if strings.EqualFold(e, ext) {
files.Set(path)
break
}
}
return nil
})
if err != nil {
base.Fatalf("failed to read dir %s: %s", dirPath, err)
}
return files
}
func getConfigFilePath() cmdarg.Arg {
extension, err := core.GetLoaderExtensions(*configFormat)
if err != nil {
base.Fatalf("%v", err.Error())
}
dirReader := readConfDir
if *configDirRecursively {
dirReader = readConfDirRecursively
}
if len(configDirs) > 0 {
for _, d := range configDirs {
log.Println("Using confdir from arg:", d)
configFiles = append(configFiles, dirReader(d, extension)...)
}
} else if envConfDir := platform.GetConfDirPath(); dirExists(envConfDir) {
log.Println("Using confdir from env:", envConfDir)
configFiles = append(configFiles, dirReader(envConfDir, extension)...)
}
if len(configFiles) > 0 {
return configFiles
}
if len(configFiles) == 0 && len(configDirs) > 0 {
base.Fatalf("no config file found with extension: %s", extension)
}
if workingDir, err := os.Getwd(); err == nil {
configFile := filepath.Join(workingDir, "config.json")
if fileExists(configFile) {
log.Println("Using default config: ", configFile)
return cmdarg.Arg{configFile}
}
}
if configFile := platform.GetConfigurationPath(); fileExists(configFile) {
log.Println("Using config from env: ", configFile)
return cmdarg.Arg{configFile}
}
return nil
}
func startV2Ray() (core.Server, error) {
config, err := core.LoadConfig(*configFormat, configFiles)
if err != nil {
if len(configFiles) == 0 {
err = newError("failed to load config").Base(err)
} else {
err = newError(fmt.Sprintf("failed to load config: %s", configFiles)).Base(err)
}
return nil, err
}
server, err := core.New(config)
if err != nil {
return nil, newError("failed to create server").Base(err)
}
return server, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/test.go | main/commands/test.go | package commands
import (
"fmt"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
// CmdTest tests config files
var CmdTest = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} test [-format=json] [-c config.json] [-d dir]",
Short: "test config files",
Long: `
Test config files, without launching V2Ray server.
{{.Exec}} will also use the config directory specified by environment
variable "v2ray.location.confdir". If no config found, it tries
to load config from one of below:
1. The default "config.json" in the current directory
2. The config file from ENV "v2ray.location.config"
3. The stdin if all failed above
Arguments:
-c, -config <file>
Config file for V2Ray. Multiple assign is accepted.
-d, -confdir <dir>
A directory with config files. Multiple assign is accepted.
-r
Load confdir recursively.
-format <format>
Format of config input. (default "auto")
Examples:
{{.Exec}} {{.LongName}} -c config.json
{{.Exec}} {{.LongName}} -d path/to/dir
Use "{{.Exec}} help format-loader" for more information about format.
`,
Run: executeTest,
}
func executeTest(cmd *base.Command, args []string) {
setConfigFlags(cmd)
cmd.Flag.Parse(args)
printVersion()
configFiles = getConfigFilePath()
_, err := startV2Ray()
if err != nil {
base.Fatalf("Test failed: %s", err)
}
fmt.Println("Configuration OK.")
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/version.go | main/commands/version.go | package commands
import (
"fmt"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
// CmdVersion prints V2Ray Versions
var CmdVersion = &base.Command{
UsageLine: "{{.Exec}} version",
Short: "print V2Ray version",
Long: `Prints the build information for V2Ray.
`,
Run: executeVersion,
}
func executeVersion(cmd *base.Command, args []string) {
printVersion()
}
func printVersion() {
version := core.VersionStatement()
for _, s := range version {
fmt.Println(s)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/base/root.go | main/commands/base/root.go | package base
// RootCommand is the root command of all commands
var RootCommand *Command
func init() {
RootCommand = &Command{
UsageLine: CommandEnv.Exec,
Long: "The root command",
}
}
// RegisterCommand register a command to RootCommand
func RegisterCommand(cmd *Command) {
RootCommand.Commands = append(RootCommand.Commands, cmd)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/base/execute.go | main/commands/base/execute.go | package base
import (
"flag"
"fmt"
"os"
"sort"
"strings"
)
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// copied from "github.com/golang/go/main.go"
// Execute excute the commands
func Execute() {
flag.Usage = func() {
PrintUsage(os.Stderr, RootCommand)
}
flag.Parse()
args := flag.Args()
if len(args) < 1 {
PrintUsage(os.Stderr, RootCommand)
return
}
cmdName := args[0] // for error messages
if args[0] == "help" {
Help(os.Stdout, args[1:])
return
}
BigCmdLoop:
for bigCmd := RootCommand; ; {
for _, cmd := range bigCmd.Commands {
if cmd.Name() != args[0] {
continue
}
if len(cmd.Commands) > 0 {
// test sub commands
bigCmd = cmd
args = args[1:]
if len(args) == 0 {
PrintUsage(os.Stderr, bigCmd)
SetExitStatus(2)
Exit()
}
if args[0] == "help" {
// Accept 'go mod help' and 'go mod help foo' for 'go help mod' and 'go help mod foo'.
Help(os.Stdout, append(strings.Split(cmdName, " "), args[1:]...))
return
}
cmdName += " " + args[0]
continue BigCmdLoop
}
if !cmd.Runnable() {
continue
}
cmd.Flag.Usage = func() { cmd.Usage() }
if cmd.CustomFlags {
args = args[1:]
} else {
cmd.Flag.Parse(args[1:])
args = cmd.Flag.Args()
}
buildCommandText(cmd)
cmd.Run(cmd, args)
Exit()
return
}
helpArg := ""
if i := strings.LastIndex(cmdName, " "); i >= 0 {
helpArg = " " + cmdName[:i]
}
fmt.Fprintf(os.Stderr, "%s %s: unknown command\nRun '%s help%s' for usage.\n", CommandEnv.Exec, cmdName, CommandEnv.Exec, helpArg)
SetExitStatus(2)
Exit()
}
}
// SortCommands sorts the first level sub commands
func SortCommands() {
sort.Slice(RootCommand.Commands, func(i, j int) bool {
return SortLessFunc(RootCommand.Commands[i], RootCommand.Commands[j])
})
}
// SortLessFunc used for sort commands list, can be override from outside
var SortLessFunc = func(i, j *Command) bool {
return i.Name() < j.Name()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/base/env.go | main/commands/base/env.go | package base
import (
"os"
"path"
)
// CommandEnvHolder is a struct holds the environment info of commands
type CommandEnvHolder struct {
// Excutable name of current binary
Exec string
// commands column width of current command
CommandsWidth int
}
// CommandEnv holds the environment info of commands
var CommandEnv CommandEnvHolder
func init() {
exec, err := os.Executable()
if err != nil {
return
}
CommandEnv.Exec = path.Base(exec)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/base/command.go | main/commands/base/command.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package base defines shared basic pieces of the commands,
// in particular logging and the Command structure.
package base
import (
"flag"
"fmt"
"os"
"strings"
"sync"
)
// A Command is an implementation of a v2ray command
// like v2ray run or v2ray version.
type Command struct {
// Run runs the command.
// The args are the arguments after the command name.
Run func(cmd *Command, args []string)
// UsageLine is the one-line usage message.
// The words between the first word (the "executable name") and the first flag or argument in the line are taken to be the command name.
//
// UsageLine supports go template syntax. It's recommended to use "{{.Exec}}" instead of hardcoding name
UsageLine string
// Short is the short description shown in the 'go help' output.
//
// Note: Short does not support go template syntax.
Short string
// Long is the long message shown in the 'go help <this-command>' output.
//
// Long supports go template syntax. It's recommended to use "{{.Exec}}", "{{.LongName}}" instead of hardcoding strings
Long string
// Flag is a set of flags specific to this command.
Flag flag.FlagSet
// CustomFlags indicates that the command will do its own
// flag parsing.
CustomFlags bool
// Commands lists the available commands and help topics.
// The order here is the order in which they are printed by 'go help'.
// Note that subcommands are in general best avoided.
Commands []*Command
}
// LongName returns the command's long name: all the words in the usage line between first word (e.g. "v2ray") and a flag or argument,
func (c *Command) LongName() string {
name := c.UsageLine
if i := strings.Index(name, " ["); i >= 0 {
name = strings.TrimSpace(name[:i])
}
if i := strings.Index(name, " "); i >= 0 {
name = name[i+1:]
} else {
name = ""
}
return strings.TrimSpace(name)
}
// Name returns the command's short name: the last word in the usage line before a flag or argument.
func (c *Command) Name() string {
name := c.LongName()
if i := strings.LastIndex(name, " "); i >= 0 {
name = name[i+1:]
}
return strings.TrimSpace(name)
}
// Usage prints usage of the Command
func (c *Command) Usage() {
buildCommandText(c)
fmt.Fprintf(os.Stderr, "usage: %s\n", c.UsageLine)
fmt.Fprintf(os.Stderr, "Run '%s help %s' for details.\n", CommandEnv.Exec, c.LongName())
SetExitStatus(2)
Exit()
}
// Runnable reports whether the command can be run; otherwise
// it is a documentation pseudo-command such as importpath.
func (c *Command) Runnable() bool {
return c.Run != nil
}
// Exit exits with code set with SetExitStatus()
func Exit() {
os.Exit(exitStatus)
}
// Fatalf logs error and exit with code 1
func Fatalf(format string, args ...interface{}) {
Errorf(format, args...)
Exit()
}
// Errorf logs error and set exit status to 1, but not exit
func Errorf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
fmt.Fprintln(os.Stderr)
SetExitStatus(1)
}
// ExitIfErrors exits if current status is not zero
func ExitIfErrors() {
if exitStatus != 0 {
Exit()
}
}
var (
exitStatus = 0
exitMu sync.Mutex
)
// SetExitStatus set exit status code
func SetExitStatus(n int) {
exitMu.Lock()
if exitStatus < n {
exitStatus = n
}
exitMu.Unlock()
}
// GetExitStatus get exit status code
func GetExitStatus() int {
return exitStatus
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/base/help.go | main/commands/base/help.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strings"
"text/template"
"unicode"
"unicode/utf8"
)
// Help implements the 'help' command.
func Help(w io.Writer, args []string) {
cmd := RootCommand
Args:
for i, arg := range args {
for _, sub := range cmd.Commands {
if sub.Name() == arg {
cmd = sub
continue Args
}
}
// helpSuccess is the help command using as many args as possible that would succeed.
helpSuccess := CommandEnv.Exec + " help"
if i > 0 {
helpSuccess += " " + strings.Join(args[:i], " ")
}
fmt.Fprintf(os.Stderr, "%s help %s: unknown help topic. Run '%s'.\n", CommandEnv.Exec, strings.Join(args, " "), helpSuccess)
SetExitStatus(2) // failed at 'v2ray help cmd'
Exit()
}
if len(cmd.Commands) > 0 {
PrintUsage(os.Stdout, cmd)
} else {
buildCommandText(cmd)
tmpl(os.Stdout, helpTemplate, makeTmplData(cmd))
}
}
var usageTemplate = `{{.Long | trim}}
Usage:
{{.UsageLine}} <command> [arguments]
The commands are:
{{range .Commands}}{{if and (ne .Short "") (or (.Runnable) .Commands)}}
{{.Name | width $.CommandsWidth}} {{.Short}}{{end}}{{end}}
Use "{{.Exec}} help{{with .LongName}} {{.}}{{end}} <command>" for more information about a command.
{{if eq (.UsageLine) (.Exec)}}
Additional help topics:
{{range .Commands}}{{if and (not .Runnable) (not .Commands)}}
{{.Name | width $.CommandsWidth}} {{.Short}}{{end}}{{end}}
Use "{{.Exec}} help{{with .LongName}} {{.}}{{end}} <topic>" for more information about that topic.
{{end}}
`
var helpTemplate = `{{if .Runnable}}usage: {{.UsageLine}}
{{end}}{{.Long | trim}}
`
// An errWriter wraps a writer, recording whether a write error occurred.
type errWriter struct {
w io.Writer
err error
}
func (w *errWriter) Write(b []byte) (int, error) {
n, err := w.w.Write(b)
if err != nil {
w.err = err
}
return n, err
}
// tmpl executes the given template text on data, writing the result to w.
func tmpl(w io.Writer, text string, data interface{}) {
t := template.New("top")
t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize, "width": width})
template.Must(t.Parse(text))
ew := &errWriter{w: w}
err := t.Execute(ew, data)
if ew.err != nil {
// I/O error writing. Ignore write on closed pipe.
if strings.Contains(ew.err.Error(), "pipe") {
SetExitStatus(1)
Exit()
}
Fatalf("writing output: %v", ew.err)
}
if err != nil {
panic(err)
}
}
func capitalize(s string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToTitle(r)) + s[n:]
}
func width(width int, value string) string {
format := fmt.Sprintf("%%-%ds", width)
return fmt.Sprintf(format, value)
}
// PrintUsage prints usage of cmd to w
func PrintUsage(w io.Writer, cmd *Command) {
buildCommandText(cmd)
bw := bufio.NewWriter(w)
tmpl(bw, usageTemplate, makeTmplData(cmd))
bw.Flush()
}
// buildCommandText build command text as template
func buildCommandText(cmd *Command) {
data := makeTmplData(cmd)
cmd.UsageLine = buildText(cmd.UsageLine, data)
// DO NOT SUPPORT ".Short":
// - It's not necessary
// - Or, we have to build text for all sub commands of current command, like "v2ray help api"
// cmd.Short = buildText(cmd.Short, data)
cmd.Long = buildText(cmd.Long, data)
}
func buildText(text string, data interface{}) string {
buf := bytes.NewBuffer([]byte{})
text = strings.ReplaceAll(text, "\t", " ")
tmpl(buf, text, data)
return buf.String()
}
type tmplData struct {
*Command
*CommandEnvHolder
}
func makeTmplData(cmd *Command) tmplData {
// Minimum width of the command column
width := 12
for _, c := range cmd.Commands {
l := len(c.Name())
if width < l {
width = l
}
}
CommandEnv.CommandsWidth = width
return tmplData{
Command: cmd,
CommandEnvHolder: &CommandEnv,
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/helpers/config_load.go | main/commands/helpers/config_load.go | package helpers
import (
"bytes"
"os"
"github.com/v2fly/v2ray-core/v5/infra/conf/merge"
"github.com/v2fly/v2ray-core/v5/infra/conf/mergers"
"github.com/v2fly/v2ray-core/v5/infra/conf/serial"
v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4"
)
// LoadConfig load config files to *conf.Config, it will:
// - resolve folder to files
// - try to read stdin if no file specified
func LoadConfig(files []string, format string, recursively bool) (*v4.Config, error) {
m, err := LoadConfigToMap(files, format, recursively)
if err != nil {
return nil, err
}
bs, err := merge.FromMap(m)
if err != nil {
return nil, err
}
r := bytes.NewReader(bs)
return serial.DecodeJSONConfig(r)
}
// LoadConfigToMap load config files to map, it will:
// - resolve folder to files
// - try to read stdin if no file specified
func LoadConfigToMap(files []string, format string, recursively bool) (map[string]interface{}, error) {
var err error
if len(files) > 0 {
var extensions []string
extensions, err := mergers.GetExtensions(format)
if err != nil {
return nil, err
}
files, err = ResolveFolderToFiles(files, extensions, recursively)
if err != nil {
return nil, err
}
}
m := make(map[string]interface{})
if len(files) == 0 {
err = mergers.MergeAs(format, os.Stdin, m)
} else {
err = mergers.MergeAs(format, files, m)
}
if err != nil {
return nil, err
}
return m, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/helpers/fs.go | main/commands/helpers/fs.go | package helpers
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// ReadDir finds files according to extensions in the dir
func ReadDir(dir string, extensions []string) ([]string, error) {
confs, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
files := make([]string, 0)
for _, f := range confs {
ext := filepath.Ext(f.Name())
for _, e := range extensions {
if strings.EqualFold(ext, e) {
files = append(files, filepath.Join(dir, f.Name()))
break
}
}
}
return files, nil
}
// ReadDirRecursively finds files according to extensions in the dir recursively
func ReadDirRecursively(dir string, extensions []string) ([]string, error) {
files := make([]string, 0)
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
ext := filepath.Ext(path)
for _, e := range extensions {
if strings.EqualFold(ext, e) {
files = append(files, path)
break
}
}
return nil
})
if err != nil {
return nil, err
}
return files, nil
}
// ResolveFolderToFiles expands folder path (if any and it exists) to file paths.
// Any other paths, like file, even URL, it returns them as is.
func ResolveFolderToFiles(paths []string, extensions []string, recursively bool) ([]string, error) {
dirReader := ReadDir
if recursively {
dirReader = ReadDirRecursively
}
files := make([]string, 0)
for _, p := range paths {
i, err := os.Stat(p)
if err == nil && i.IsDir() {
fs, err := dirReader(p, extensions)
if err != nil {
return nil, fmt.Errorf("failed to read dir %s: %s", p, err)
}
files = append(files, fs...)
continue
}
files = append(files, p)
}
return files, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/uuid.go | main/commands/all/uuid.go | package all
import (
"fmt"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdUUID = &base.Command{
UsageLine: "{{.Exec}} uuid",
Short: "generate new UUID",
Long: `Generate new UUID.
`,
Run: executeUUID,
}
func executeUUID(cmd *base.Command, args []string) {
u := uuid.New()
fmt.Println(u.String())
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/merge_doc.go | main/commands/all/merge_doc.go | package all
import (
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var docMerge = &base.Command{
UsageLine: "{{.Exec}} config-merge",
Short: "config merge logic",
Long: `
Merging of config files is applied in following commands:
{{.Exec}} run -c c1.json -c c2.json ...
{{.Exec}} test -c c1.yaml -c c2.yaml ...
{{.Exec}} convert c1.json dir1 ...
{{.Exec}} api ado c1.json dir1 ...
{{.Exec}} api rmi c1.json dir1 ...
... and more ...
Support of toml and yaml is implemented by converting them to json,
both merge and load. So we take json as example here.
Suppose we have 2 JSON files,
The 1st one:
{
"log": {"access": "some_value", "loglevel": "debug"},
"inbounds": [{"tag": "in-1"}],
"outbounds": [{"_priority": 100, "tag": "out-1"}],
"routing": {"rules": [
{"_tag":"default_route","inboundTag":["in-1"],"outboundTag":"out-1"}
]}
}
The 2nd one:
{
"log": {"loglevel": "error"},
"inbounds": [{"tag": "in-2"}],
"outbounds": [{"_priority": -100, "tag": "out-2"}],
"routing": {"rules": [
{"inboundTag":["in-2"],"outboundTag":"out-2"},
{"_tag":"default_route","inboundTag":["in-1.1"],"outboundTag":"out-1.1"}
]}
}
Output:
{
// loglevel is overwritten
"log": {"access": "some_value", "loglevel": "error"},
"inbounds": [{"tag": "in-1"}, {"tag": "in-2"}],
"outbounds": [
{"tag": "out-2"}, // note the order is affected by priority
{"tag": "out-1"}
],
"routing": {"rules": [
// note 3 rules are merged into 2, and outboundTag is overwritten,
// because 2 of them has same tag
{"inboundTag":["in-1","in-1.1"],"outboundTag":"out-1.1"}
{"inboundTag":["in-2"],"outboundTag":"out-2"}
]}
}
Explained:
- Simple values (string, number, boolean) are overwritten, others are merged
- Elements with same "tag" (or "_tag") in an array will be merged
- Add "_priority" property to array elements will help sort the array
`,
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/commands.go | main/commands/all/commands.go | package all
import (
"github.com/v2fly/v2ray-core/v5/main/commands/all/api"
"github.com/v2fly/v2ray-core/v5/main/commands/all/tls"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
//go:generate go run v2ray.com/core/common/errors/errorgen
func init() {
base.RootCommand.Commands = append(
base.RootCommand.Commands,
api.CmdAPI,
cmdLove,
tls.CmdTLS,
cmdUUID,
cmdVerify,
// documents
docFormat,
docMerge,
)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/verify.go | main/commands/all/verify.go | package all
import (
"os"
"github.com/v2fly/VSign/signerVerify"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdVerify = &base.Command{
UsageLine: "{{.Exec}} verify [--sig=sig-file] file",
Short: "verify if a binary is officially signed",
Long: `
Verify if a binary is officially signed.
Arguments:
-sig <signature_file>
The path to the signature file
`,
}
func init() {
cmdVerify.Run = executeVerify // break init loop
}
var verifySigFile = cmdVerify.Flag.String("sig", "", "Path to the signature file")
func executeVerify(cmd *base.Command, args []string) {
target := cmdVerify.Flag.Arg(0)
if target == "" {
base.Fatalf("empty file path.")
}
if *verifySigFile == "" {
base.Fatalf("empty signature path.")
}
sigReader, err := os.Open(os.ExpandEnv(*verifySigFile))
if err != nil {
base.Fatalf("failed to open file %s: %s ", *verifySigFile, err)
}
files := cmdVerify.Flag.Args()
err = signerVerify.OutputAndJudge(signerVerify.CheckSignaturesV2Fly(sigReader, files))
if err != nil {
base.Fatalf("file is not officially signed by V2Ray: %s", err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/errors.generated.go | main/commands/all/errors.generated.go | package all
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/main/commands/all/format_doc.go | main/commands/all/format_doc.go | package all
import (
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var docFormat = &base.Command{
UsageLine: "{{.Exec}} format-loader",
Short: "config formats and loading",
Long: `
{{.Exec}} is equipped with multiple loaders to support different
config formats:
* auto
The default loader, supports all formats listed below, with
format detecting, and mixed fomats support.
* json (.json, .jsonc)
The json loader, multiple files support, mergeable.
* toml (.toml)
The toml loader, multiple files support, mergeable.
* yaml (.yml, .yaml)
The yaml loader, multiple files support, mergeable.
* protobuf / pb (.pb)
Single file support, unmergeable.
The following explains how format loaders behaves.
Examples:
{{.Exec}} run -d dir (1)
{{.Exec}} run -c c1.json -c c2.yaml (2)
{{.Exec}} run -format=json -d dir (3)
{{.Exec}} test -c c1.yml -c c2.pb (4)
{{.Exec}} test -format=pb -d dir (5)
{{.Exec}} test -format=protobuf -c c1.json (6)
(1) Load all supported files in the "dir".
(2) JSON and YAML are merged and loaded.
(3) Load all JSON files in the "dir".
(4) Goes error since .pb is not mergeable to others
(5) Works only when single .pb file found, if not, failed due to
unmergeable.
(6) Force load "c1.json" as protobuf, no matter its extension.
`,
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/love.go | main/commands/all/love.go | package all
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/base64"
"fmt"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/platform"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdLove = &base.Command{
UsageLine: "{{.Exec}} lovevictoria",
Short: "", // set Short to "" hides the command
Long: "",
Run: executeLove,
}
func executeLove(cmd *base.Command, args []string) {
const content = "H4sIAAAAAAAC/4SVMaskNwzH+/kUW6izcSthMGrcqLhVk0rdQS5cSMg7Xu4S0vizB8meZd57M3ta2GHX/ukvyZZmY2ZKDMzCzJyY5yOlxKII1omsf+qkBiiC6WhbYsbkjDAfySQsJqD3jtrD0EBM3sBHzG3kUsrglIQREXonpd47kYIi4AHmgI9Wcq2jlJITC6JZJ+v3ECYzBMAHyYm392yuY4zWsjACmHZSh6l3A0JETzGlWZqDsnArpTg62mhJONhOdO90p97V1BAnteoaOcuummtrrtuERQwUiJwP8a4KGKcyxdOCw1spOY+WHueFqmakAIgUSSuhwKNgobxKXSLbtg6r5cFmBiAeF6yCkYycmv+BiCIiW8ScHa3DgxAuZQbRhFNrLTFo96RBmx9jKWWG5nBsjyJzuIkftUblonppZU5t5LzwIks5L1a4lijagQxLokbIYwxfytNDC+XQqrWW9fzAunhqh5/Tg8PuaMw0d/Tcw3iDO81bHfWM/AnutMh2xqSUntMzd3wHDy9iHMQz8bmUZYvqedTJ5GgOnrNt7FIbSlwXE3wDI19n/KA38MsLaP4l89b5F8AV3ESOMIEhIBgezHBc0H6xV9KbaXwMvPcNvIHcC0C7UPZQx4JVTb35/AneSQq+bAYXsBmY7TCRupF2NTdVm/+ch22xa0pvRERKqt1oxj9DUbXzU84Gvj5hc5a81SlAUwMwgEs4T9+7sg9lb9h+908MWiKV8xtWciVTmnB3tivRjNerfXdxpfEBbq2NUvLMM5R9NLuyQg8nXT0PIh1xPd/wrcV49oJ6zbZaPlj2V87IY9T3F2XCOcW2MbZyZd49H+9m81E1N9SxlU+ff/1y+/f3719vf7788+Ugv/ffbMIH7ZNj0dsT4WMHHwLPu/Rp2O75uh99AK+N2xn7ZHq1OK6gczkN+9ngdOl1Qvki5xwSR8vFX6D+9vXA97B/+fr5rz9u/738uP328urP19vfP759e3n9Xs6jamvqlfJ/AAAA//+YAMZjDgkAAA=="
c, err := base64.StdEncoding.DecodeString(content)
common.Must(err)
reader, err := gzip.NewReader(bytes.NewBuffer(c))
common.Must(err)
b := make([]byte, 4096)
nBytes, _ := reader.Read(b)
bb := bytes.NewBuffer(b[:nBytes])
scanner := bufio.NewScanner(bb)
for scanner.Scan() {
s := scanner.Text()
fmt.Print(s + platform.LineSeparator())
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/tls/chainhash.go | main/commands/all/tls/chainhash.go | package tls
import (
"fmt"
"os"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
v2tls "github.com/v2fly/v2ray-core/v5/transport/internet/tls"
)
var cmdChainHash = &base.Command{
UsageLine: "{{.Exec}} tls certChainHash [--cert <cert.pem>]",
Short: "Generate certificate chain hash for given certificate bundle",
}
func init() {
cmdChainHash.Run = executeChainHash // break init loop
}
var certFile = cmdChainHash.Flag.String("cert", "cert.pem", "")
func executeChainHash(cmd *base.Command, args []string) {
if len(*certFile) == 0 {
base.Fatalf("cert file not specified")
}
certContent, err := os.ReadFile(*certFile)
if err != nil {
base.Fatalf("Failed to read cert file: %s", err)
return
}
certChainHashB64 := v2tls.CalculatePEMCertChainSHA256Hash(certContent)
fmt.Println(certChainHashB64)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/tls/ping.go | main/commands/all/tls/ping.go | package tls
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"net"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
v2tls "github.com/v2fly/v2ray-core/v5/transport/internet/tls"
)
// cmdPing is the tls ping command
var cmdPing = &base.Command{
UsageLine: "{{.Exec}} tls ping [-ip <ip>] <domain>",
Short: "ping the domain with TLS handshake",
Long: `
Ping the domain with TLS handshake.
Arguments:
-ip <ip>
The IP address of the domain.
`,
}
func init() {
cmdPing.Run = executePing // break init loop
}
var pingIPStr = cmdPing.Flag.String("ip", "", "")
func executePing(cmd *base.Command, args []string) {
if cmdPing.Flag.NArg() < 1 {
base.Fatalf("domain not specified")
}
domain := cmdPing.Flag.Arg(0)
fmt.Println("Tls ping: ", domain)
var ip net.IP
if len(*pingIPStr) > 0 {
v := net.ParseIP(*pingIPStr)
if v == nil {
base.Fatalf("invalid IP: %s", *pingIPStr)
}
ip = v
} else {
v, err := net.ResolveIPAddr("ip", domain)
if err != nil {
base.Fatalf("Failed to resolve IP: %s", err)
}
ip = v.IP
}
fmt.Println("Using IP: ", ip.String())
fmt.Println("-------------------")
fmt.Println("Pinging without SNI")
{
tcpConn, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: ip, Port: 443})
if err != nil {
base.Fatalf("Failed to dial tcp: %s", err)
}
tlsConn := tls.Client(tcpConn, &tls.Config{
InsecureSkipVerify: true,
NextProtos: []string{"http/1.1"},
MaxVersion: tls.VersionTLS12,
MinVersion: tls.VersionTLS12,
// Do not release tool before v5's refactor
// VerifyPeerCertificate: showCert(),
})
err = tlsConn.Handshake()
if err != nil {
fmt.Println("Handshake failure: ", err)
} else {
fmt.Println("Handshake succeeded")
printCertificates(tlsConn.ConnectionState().PeerCertificates)
}
tlsConn.Close()
}
fmt.Println("-------------------")
fmt.Println("Pinging with SNI")
{
tcpConn, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: ip, Port: 443})
if err != nil {
base.Fatalf("Failed to dial tcp: %s", err)
}
tlsConn := tls.Client(tcpConn, &tls.Config{
ServerName: domain,
NextProtos: []string{"http/1.1"},
MaxVersion: tls.VersionTLS12,
MinVersion: tls.VersionTLS12,
// Do not release tool before v5's refactor
// VerifyPeerCertificate: showCert(),
})
err = tlsConn.Handshake()
if err != nil {
fmt.Println("handshake failure: ", err)
} else {
fmt.Println("handshake succeeded")
printCertificates(tlsConn.ConnectionState().PeerCertificates)
}
tlsConn.Close()
}
fmt.Println("Tls ping finished")
}
func printCertificates(certs []*x509.Certificate) {
for _, cert := range certs {
if len(cert.DNSNames) == 0 {
continue
}
fmt.Println("Allowed domains: ", cert.DNSNames)
}
}
func showCert() func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
hash := v2tls.GenerateCertChainHash(rawCerts)
fmt.Println("Certificate Chain Hash: ", base64.StdEncoding.EncodeToString(hash))
return nil
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/tls/cert.go | main/commands/all/tls/cert.go | package tls
import (
"context"
"crypto/x509"
"encoding/json"
"os"
"strings"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/protocol/tls/cert"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
// cmdCert is the tls cert command
var cmdCert = &base.Command{
UsageLine: "{{.Exec}} tls cert [--ca] [--domain=v2fly.org] [--expire=240h]",
Short: "Generate TLS certificates",
Long: `
Generate TLS certificates.
Arguments:
-domain <domain_name>
The domain name for the certificate.
-name <common name>
The common name of this certificate
-org <organization>
The organization name for the certificate.
-ca
The certificate is a CA
-json
To output certificate to JSON
-file <path>
The certificate path to save.
-expire <days>
Expire days of the certificate. Default 90 days.
`,
}
func init() {
cmdCert.Run = executeCert // break init loop
}
var (
certDomainNames stringList
_ = func() bool {
cmdCert.Flag.Var(&certDomainNames, "domain", "Domain name for the certificate")
return true
}()
certCommonName = cmdCert.Flag.String("name", "V2Ray Inc", "")
certOrganization = cmdCert.Flag.String("org", "V2Ray Inc", "")
certIsCA = cmdCert.Flag.Bool("ca", false, "")
certJSONOutput = cmdCert.Flag.Bool("json", true, "")
certFileOutput = cmdCert.Flag.String("file", "", "")
certExpire = cmdCert.Flag.Uint("expire", 90, "")
)
func executeCert(cmd *base.Command, args []string) {
var opts []cert.Option
if *certIsCA {
opts = append(opts, cert.Authority(*certIsCA))
opts = append(opts, cert.KeyUsage(x509.KeyUsageCertSign|x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature))
}
opts = append(opts, cert.NotAfter(time.Now().Add(time.Duration(*certExpire)*time.Hour*24)))
opts = append(opts, cert.CommonName(*certCommonName))
if len(certDomainNames) > 0 {
opts = append(opts, cert.DNSNames(certDomainNames...))
}
opts = append(opts, cert.Organization(*certOrganization))
cert, err := cert.Generate(nil, opts...)
if err != nil {
base.Fatalf("failed to generate TLS certificate: %s", err)
}
if *certJSONOutput {
printJSON(cert)
}
if len(*certFileOutput) > 0 {
if err := printFile(cert, *certFileOutput); err != nil {
base.Fatalf("failed to save file: %s", err)
}
}
}
func printJSON(certificate *cert.Certificate) {
certPEM, keyPEM := certificate.ToPEM()
jCert := &jsonCert{
Certificate: strings.Split(strings.TrimSpace(string(certPEM)), "\n"),
Key: strings.Split(strings.TrimSpace(string(keyPEM)), "\n"),
}
content, err := json.MarshalIndent(jCert, "", " ")
common.Must(err)
os.Stdout.Write(content)
os.Stdout.WriteString("\n")
}
func writeFile(content []byte, name string) error {
f, err := os.Create(name)
if err != nil {
return err
}
defer f.Close()
return common.Error2(f.Write(content))
}
func printFile(certificate *cert.Certificate, name string) error {
certPEM, keyPEM := certificate.ToPEM()
return task.Run(context.Background(), func() error {
return writeFile(certPEM, name+"_cert.pem")
}, func() error {
return writeFile(keyPEM, name+"_key.pem")
})
}
type stringList []string
func (l *stringList) String() string {
return "String list"
}
func (l *stringList) Set(v string) error {
if v == "" {
base.Fatalf("empty value")
}
*l = append(*l, v)
return nil
}
type jsonCert struct {
Certificate []string `json:"certificate"`
Key []string `json:"key"`
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/tls/tls.go | main/commands/all/tls/tls.go | package tls
import (
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
// CmdTLS holds all tls sub commands
var CmdTLS = &base.Command{
UsageLine: "{{.Exec}} tls",
Short: "TLS tools",
Long: `{{.Exec}} {{.LongName}} provides tools for TLS.
`,
Commands: []*base.Command{
cmdCert,
cmdPing,
cmdChainHash,
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/balancer_info.go | main/commands/all/api/balancer_info.go | package api
import (
"fmt"
"os"
"strings"
routerService "github.com/v2fly/v2ray-core/v5/app/router/command"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
// TODO: support "-json" flag for json output
var cmdBalancerInfo = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} api bi [--server=127.0.0.1:8080] [balancer]...",
Short: "balancer information",
Long: `
Get information of specified balancers, including health, strategy
and selecting. If no balancer tag specified, get information of
all balancers.
> Make sure you have "RoutingService" set in "config.api.services"
of server config.
Arguments:
-json
Use json output.
-s, -server <server:port>
The API server address. Default 127.0.0.1:8080
-t, -timeout <seconds>
Timeout seconds to call API. Default 3
Example:
{{.Exec}} {{.LongName}} --server=127.0.0.1:8080 balancer1 balancer2
`,
Run: executeBalancerInfo,
}
func executeBalancerInfo(cmd *base.Command, args []string) {
setSharedFlags(cmd)
cmd.Flag.Parse(args)
conn, ctx, close := dialAPIServer()
defer close()
client := routerService.NewRoutingServiceClient(conn)
r := &routerService.GetBalancerInfoRequest{Tag: cmd.Flag.Arg(0)}
resp, err := client.GetBalancerInfo(ctx, r)
if err != nil {
base.Fatalf("failed to get health information: %s", err)
}
if apiJSON {
showJSONResponse(resp)
return
}
showBalancerInfo(resp.Balancer)
}
func showBalancerInfo(b *routerService.BalancerMsg) {
const tableIndent = 4
sb := new(strings.Builder)
// Override
if b.Override != nil {
sb.WriteString(" - Selecting Override:\n")
for i, s := range []string{b.Override.Target} {
writeRow(sb, tableIndent, i+1, []string{s}, nil)
}
}
// Selects
sb.WriteString(" - Selects:\n")
for i, o := range b.PrincipleTarget.Tag {
writeRow(sb, tableIndent, i+1, []string{o}, nil)
}
os.Stdout.WriteString(sb.String())
}
func getColumnFormats(titles []string) []string {
w := make([]string, len(titles))
for i, t := range titles {
w[i] = fmt.Sprintf("%%-%ds ", len(t))
}
return w
}
func writeRow(sb *strings.Builder, indent, index int, values, formats []string) {
if index == 0 {
// title line
sb.WriteString(strings.Repeat(" ", indent+4))
} else {
sb.WriteString(fmt.Sprintf("%s%-4d", strings.Repeat(" ", indent), index))
}
for i, v := range values {
format := "%-14s"
if i < len(formats) {
format = formats[i]
}
sb.WriteString(fmt.Sprintf(format, v))
}
sb.WriteByte('\n')
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/stats.go | main/commands/all/api/stats.go | package api
import (
"fmt"
"os"
"sort"
"strings"
"time"
statsService "github.com/v2fly/v2ray-core/v5/app/stats/command"
"github.com/v2fly/v2ray-core/v5/common/units"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdStats = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} api stats [--server=127.0.0.1:8080] [pattern]...",
Short: "query statistics",
Long: `
Query statistics from V2Ray.
> Make sure you have "StatsService" set in "config.api.services"
of server config.
Arguments:
-regexp
The patterns are using regexp.
-reset
Reset counters to 0 after fetching their values.
-runtime
Get runtime statistics.
-json
Use json output.
-s, -server <server:port>
The API server address. Default 127.0.0.1:8080
-t, -timeout <seconds>
Timeout seconds to call API. Default 3
Example:
{{.Exec}} {{.LongName}} -runtime
{{.Exec}} {{.LongName}} node1
{{.Exec}} {{.LongName}} -json node1 node2
{{.Exec}} {{.LongName}} -regexp 'node1.+downlink'
`,
Run: executeStats,
}
func executeStats(cmd *base.Command, args []string) {
setSharedFlags(cmd)
var (
runtime bool
regexp bool
reset bool
)
cmd.Flag.BoolVar(&runtime, "runtime", false, "")
cmd.Flag.BoolVar(®exp, "regexp", false, "")
cmd.Flag.BoolVar(&reset, "reset", false, "")
cmd.Flag.Parse(args)
unnamed := cmd.Flag.Args()
if runtime {
getRuntimeStats(apiJSON)
return
}
getStats(unnamed, regexp, reset, apiJSON)
}
func getRuntimeStats(jsonOutput bool) {
conn, ctx, close := dialAPIServer()
defer close()
client := statsService.NewStatsServiceClient(conn)
r := &statsService.SysStatsRequest{}
resp, err := client.GetSysStats(ctx, r)
if err != nil {
base.Fatalf("failed to get sys stats: %s", err)
}
if jsonOutput {
showJSONResponse(resp)
return
}
showRuntimeStats(resp)
}
func showRuntimeStats(s *statsService.SysStatsResponse) {
formats := []string{"%-22s", "%-10s"}
rows := [][]string{
{"Up time", (time.Duration(s.Uptime) * time.Second).String()},
{"Memory obtained", units.ByteSize(s.Sys).String()},
{"Number of goroutines", fmt.Sprintf("%d", s.NumGoroutine)},
{"Heap allocated", units.ByteSize(s.Alloc).String()},
{"Live objects", fmt.Sprintf("%d", s.LiveObjects)},
{"Heap allocated total", units.ByteSize(s.TotalAlloc).String()},
{"Heap allocate count", fmt.Sprintf("%d", s.Mallocs)},
{"Heap free count", fmt.Sprintf("%d", s.Frees)},
{"Number of GC", fmt.Sprintf("%d", s.NumGC)},
{"Time of GC pause", (time.Duration(s.PauseTotalNs) * time.Nanosecond).String()},
}
sb := new(strings.Builder)
writeRow(sb, 0, 0,
[]string{"Item", "Value"},
formats,
)
for i, r := range rows {
writeRow(sb, 0, i+1, r, formats)
}
os.Stdout.WriteString(sb.String())
}
func getStats(patterns []string, regexp, reset, jsonOutput bool) {
conn, ctx, close := dialAPIServer()
defer close()
client := statsService.NewStatsServiceClient(conn)
r := &statsService.QueryStatsRequest{
Patterns: patterns,
Regexp: regexp,
Reset_: reset,
}
resp, err := client.QueryStats(ctx, r)
if err != nil {
base.Fatalf("failed to query stats: %s", err)
}
if jsonOutput {
showJSONResponse(resp)
return
}
sort.Slice(resp.Stat, func(i, j int) bool {
return resp.Stat[i].Name < resp.Stat[j].Name
})
showStats(resp.Stat)
}
func showStats(stats []*statsService.Stat) {
if len(stats) == 0 {
return
}
formats := []string{"%-12s", "%s"}
sum := int64(0)
sb := new(strings.Builder)
idx := 0
writeRow(sb, 0, 0,
[]string{"Value", "Name"},
formats,
)
for _, stat := range stats {
// if stat.Value == 0 {
// continue
// }
idx++
sum += stat.Value
writeRow(
sb, 0, idx,
[]string{units.ByteSize(stat.Value).String(), stat.Name},
formats,
)
}
sb.WriteString(
fmt.Sprintf("\nTotal: %s\n", units.ByteSize(sum)),
)
os.Stdout.WriteString(sb.String())
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/api.go | main/commands/all/api/api.go | package api
import (
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
// CmdAPI calls an API in an V2Ray process
var CmdAPI = &base.Command{
UsageLine: "{{.Exec}} api",
Short: "call V2Ray API",
Long: `{{.Exec}} {{.LongName}} provides tools to manipulate V2Ray via its API.
`,
Commands: []*base.Command{
cmdLog,
cmdStats,
cmdBalancerInfo,
cmdBalancerOverride,
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/log.go | main/commands/all/api/log.go | package api
import (
"io"
"log"
"os"
logService "github.com/v2fly/v2ray-core/v5/app/log/command"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdLog = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} api log [--server=127.0.0.1:8080]",
Short: "log operations",
Long: `
Follow and print logs from v2ray.
> Make sure you have "LoggerService" set in "config.api.services"
of server config.
> It ignores -timeout flag while following logs
Arguments:
-restart
Restart the logger
-s, -server <server:port>
The API server address. Default 127.0.0.1:8080
-t, -timeout <seconds>
Timeout seconds to call API. Default 3
Example:
{{.Exec}} {{.LongName}}
{{.Exec}} {{.LongName}} --restart
`,
Run: executeLog,
}
func executeLog(cmd *base.Command, args []string) {
var restart bool
cmd.Flag.BoolVar(&restart, "restart", false, "")
setSharedFlags(cmd)
cmd.Flag.Parse(args)
if restart {
restartLogger()
return
}
followLogger()
}
func restartLogger() {
conn, ctx, close := dialAPIServer()
defer close()
client := logService.NewLoggerServiceClient(conn)
r := &logService.RestartLoggerRequest{}
_, err := client.RestartLogger(ctx, r)
if err != nil {
base.Fatalf("failed to restart logger: %s", err)
}
}
func followLogger() {
conn, ctx, close := dialAPIServerWithoutTimeout()
defer close()
client := logService.NewLoggerServiceClient(conn)
r := &logService.FollowLogRequest{}
stream, err := client.FollowLog(ctx, r)
if err != nil {
base.Fatalf("failed to follow logger: %s", err)
}
// work with `v2ray api log | grep expr`
log.SetOutput(os.Stdout)
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
base.Fatalf("failed to fetch log: %s", err)
}
log.Println(resp.Message)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/shared.go | main/commands/all/api/shared.go | package api
import (
"context"
"fmt"
"os"
"strings"
"time"
"google.golang.org/grpc"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var (
apiServerAddrPtr string
apiTimeout int
apiJSON bool
// APIConfigFormat is an internal variable
APIConfigFormat string
// APIConfigRecursively is an internal variable
APIConfigRecursively bool
)
// SetSharedFlags is an internal API
func SetSharedFlags(cmd *base.Command) {
setSharedFlags(cmd)
}
func setSharedFlags(cmd *base.Command) {
cmd.Flag.StringVar(&apiServerAddrPtr, "s", "127.0.0.1:8080", "")
cmd.Flag.StringVar(&apiServerAddrPtr, "server", "127.0.0.1:8080", "")
cmd.Flag.IntVar(&apiTimeout, "t", 3, "")
cmd.Flag.IntVar(&apiTimeout, "timeout", 3, "")
cmd.Flag.BoolVar(&apiJSON, "json", false, "")
}
// SetSharedConfigFlags is an internal API
func SetSharedConfigFlags(cmd *base.Command) {
setSharedConfigFlags(cmd)
}
func setSharedConfigFlags(cmd *base.Command) {
cmd.Flag.StringVar(&APIConfigFormat, "format", core.FormatAuto, "")
cmd.Flag.BoolVar(&APIConfigRecursively, "r", false, "")
}
// SetSharedFlags is an internal API
func DialAPIServer() (conn *grpc.ClientConn, ctx context.Context, close func()) {
return dialAPIServer()
}
func dialAPIServer() (conn *grpc.ClientConn, ctx context.Context, close func()) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(apiTimeout)*time.Second)
conn = dialAPIServerWithContext(ctx)
close = func() {
cancel()
conn.Close()
}
return
}
func dialAPIServerWithoutTimeout() (conn *grpc.ClientConn, ctx context.Context, close func()) {
ctx = context.Background()
conn = dialAPIServerWithContext(ctx)
close = func() {
conn.Close()
}
return
}
func dialAPIServerWithContext(ctx context.Context) (conn *grpc.ClientConn) {
conn, err := grpc.DialContext(ctx, apiServerAddrPtr, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
base.Fatalf("failed to dial %s", apiServerAddrPtr)
}
return
}
func protoToJSONString(m proto.Message, prefix, indent string) (string, error) { // nolint: unparam
return strings.TrimSpace(protojson.MarshalOptions{Indent: indent}.Format(m)), nil
}
func showJSONResponse(m proto.Message) {
output, err := protoToJSONString(m, "", "")
if err != nil {
fmt.Fprintf(os.Stdout, "%v\n", m)
base.Fatalf("error encode json: %s", err)
}
fmt.Println(output)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/balancer_override.go | main/commands/all/api/balancer_override.go | package api
import (
routerService "github.com/v2fly/v2ray-core/v5/app/router/command"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdBalancerOverride = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} api bo [--server=127.0.0.1:8080] <-b balancer> outboundTag",
Short: "balancer override",
Long: `
Override a balancer's selection.
> Make sure you have "RoutingService" set in "config.api.services"
of server config.
Once a balancer's selection is overridden:
- The balancer's selection result will always be outboundTag
Arguments:
-b, -balancer <tag>
Tag of the target balancer. Required.
-r, -remove
Remove the override
-s, -server <server:port>
The API server address. Default 127.0.0.1:8080
-t, -timeout <seconds>
Timeout seconds to call API. Default 3
Example:
{{.Exec}} {{.LongName}} --server=127.0.0.1:8080 -b balancer tag
{{.Exec}} {{.LongName}} --server=127.0.0.1:8080 -b balancer -r
`,
Run: executeBalancerOverride,
}
func executeBalancerOverride(cmd *base.Command, args []string) {
var (
balancer string
remove bool
)
cmd.Flag.StringVar(&balancer, "b", "", "")
cmd.Flag.StringVar(&balancer, "balancer", "", "")
cmd.Flag.BoolVar(&remove, "r", false, "")
cmd.Flag.BoolVar(&remove, "remove", false, "")
setSharedFlags(cmd)
cmd.Flag.Parse(args)
if balancer == "" {
base.Fatalf("balancer tag not specified")
}
conn, ctx, close := dialAPIServer()
defer close()
client := routerService.NewRoutingServiceClient(conn)
target := ""
if !remove {
target = cmd.Flag.Args()[0]
}
r := &routerService.OverrideBalancerTargetRequest{
BalancerTag: balancer,
Target: target,
}
_, err := client.OverrideBalancerTarget(ctx, r)
if err != nil {
base.Fatalf("failed to override balancer: %s", err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/jsonv4/outbounds_add.go | main/commands/all/api/jsonv4/outbounds_add.go | package jsonv4
import (
"fmt"
handlerService "github.com/v2fly/v2ray-core/v5/app/proxyman/command"
"github.com/v2fly/v2ray-core/v5/main/commands/all/api"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
"github.com/v2fly/v2ray-core/v5/main/commands/helpers"
)
var cmdAddOutbounds = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} api ado [--server=127.0.0.1:8080] [c1.json] [dir1]...",
Short: "add outbounds",
Long: `
Add outbounds to V2Ray.
> Make sure you have "HandlerService" set in "config.api.services"
of server config.
Arguments:
-format <format>
The input format.
Available values: "auto", "json", "toml", "yaml"
Default: "auto"
-r
Load folders recursively.
-s, -server <server:port>
The API server address. Default 127.0.0.1:8080
-t, -timeout <seconds>
Timeout seconds to call API. Default 3
Example:
{{.Exec}} {{.LongName}} dir
{{.Exec}} {{.LongName}} c1.json c2.yaml
`,
Run: executeAddOutbounds,
}
func executeAddOutbounds(cmd *base.Command, args []string) {
api.SetSharedFlags(cmd)
api.SetSharedConfigFlags(cmd)
cmd.Flag.Parse(args)
c, err := helpers.LoadConfig(cmd.Flag.Args(), api.APIConfigFormat, api.APIConfigRecursively)
if err != nil {
base.Fatalf("failed to load: %s", err)
}
if len(c.OutboundConfigs) == 0 {
base.Fatalf("no valid outbound found")
}
conn, ctx, close := api.DialAPIServer()
defer close()
client := handlerService.NewHandlerServiceClient(conn)
for _, out := range c.OutboundConfigs {
fmt.Println("adding:", out.Tag)
o, err := out.Build()
if err != nil {
base.Fatalf("failed to build conf: %s", err)
}
r := &handlerService.AddOutboundRequest{
Outbound: o,
}
_, err = client.AddOutbound(ctx, r)
if err != nil {
base.Fatalf("failed to add outbound: %s", err)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/jsonv4/init.go | main/commands/all/api/jsonv4/init.go | package jsonv4
import "github.com/v2fly/v2ray-core/v5/main/commands/all/api"
func init() {
api.CmdAPI.Commands = append(api.CmdAPI.Commands,
cmdAddInbounds,
cmdAddOutbounds,
cmdRemoveInbounds,
cmdRemoveOutbounds)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/jsonv4/inbounds_add.go | main/commands/all/api/jsonv4/inbounds_add.go | package jsonv4
import (
"fmt"
handlerService "github.com/v2fly/v2ray-core/v5/app/proxyman/command"
"github.com/v2fly/v2ray-core/v5/main/commands/all/api"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
"github.com/v2fly/v2ray-core/v5/main/commands/helpers"
)
var cmdAddInbounds = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} api adi [--server=127.0.0.1:8080] [c1.json] [dir1]...",
Short: "add inbounds",
Long: `
Add inbounds to V2Ray.
> Make sure you have "HandlerService" set in "config.api.services"
of server config.
Arguments:
-format <format>
The input format.
Available values: "auto", "json", "toml", "yaml"
Default: "auto"
-r
Load folders recursively.
-s, -server <server:port>
The API server address. Default 127.0.0.1:8080
-t, -timeout <seconds>
Timeout seconds to call API. Default 3
Example:
{{.Exec}} {{.LongName}} dir
{{.Exec}} {{.LongName}} c1.json c2.yaml
`,
Run: executeAddInbounds,
}
func executeAddInbounds(cmd *base.Command, args []string) {
api.SetSharedFlags(cmd)
api.SetSharedConfigFlags(cmd)
cmd.Flag.Parse(args)
c, err := helpers.LoadConfig(cmd.Flag.Args(), api.APIConfigFormat, api.APIConfigRecursively)
if err != nil {
base.Fatalf("failed to load: %s", err)
}
if len(c.InboundConfigs) == 0 {
base.Fatalf("no valid inbound found")
}
conn, ctx, close := api.DialAPIServer()
defer close()
client := handlerService.NewHandlerServiceClient(conn)
for _, in := range c.InboundConfigs {
fmt.Println("adding:", in.Tag)
i, err := in.Build()
if err != nil {
base.Fatalf("failed to build conf: %s", err)
}
r := &handlerService.AddInboundRequest{
Inbound: i,
}
_, err = client.AddInbound(ctx, r)
if err != nil {
base.Fatalf("failed to add inbound: %s", err)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/jsonv4/outbounds_remove.go | main/commands/all/api/jsonv4/outbounds_remove.go | package jsonv4
import (
"fmt"
handlerService "github.com/v2fly/v2ray-core/v5/app/proxyman/command"
"github.com/v2fly/v2ray-core/v5/main/commands/all/api"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
"github.com/v2fly/v2ray-core/v5/main/commands/helpers"
)
var cmdRemoveOutbounds = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} api rmo [--server=127.0.0.1:8080] [c1.json] [dir1]...",
Short: "remove outbounds",
Long: `
Remove outbounds from V2Ray.
> Make sure you have "HandlerService" set in "config.api.services"
of server config.
Arguments:
-format <format>
The input format.
Available values: "auto", "json", "toml", "yaml"
Default: "auto"
-r
Load folders recursively.
-tags
The input are tags instead of config files
-s, -server <server:port>
The API server address. Default 127.0.0.1:8080
-t, -timeout <seconds>
Timeout seconds to call API. Default 3
Example:
{{.Exec}} {{.LongName}} dir
{{.Exec}} {{.LongName}} c1.json c2.yaml
{{.Exec}} {{.LongName}} -tags tag1 tag2
`,
Run: executeRemoveOutbounds,
}
func executeRemoveOutbounds(cmd *base.Command, args []string) {
api.SetSharedFlags(cmd)
api.SetSharedConfigFlags(cmd)
isTags := cmd.Flag.Bool("tags", false, "")
cmd.Flag.Parse(args)
var tags []string
if *isTags {
tags = cmd.Flag.Args()
} else {
c, err := helpers.LoadConfig(cmd.Flag.Args(), api.APIConfigFormat, api.APIConfigRecursively)
if err != nil {
base.Fatalf("failed to load: %s", err)
}
tags = make([]string, 0)
for _, c := range c.OutboundConfigs {
tags = append(tags, c.Tag)
}
}
if len(tags) == 0 {
base.Fatalf("no outbound to remove")
}
conn, ctx, close := api.DialAPIServer()
defer close()
client := handlerService.NewHandlerServiceClient(conn)
for _, tag := range tags {
fmt.Println("removing:", tag)
r := &handlerService.RemoveOutboundRequest{
Tag: tag,
}
_, err := client.RemoveOutbound(ctx, r)
if err != nil {
base.Fatalf("failed to remove outbound: %s", err)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/api/jsonv4/inbounds_remove.go | main/commands/all/api/jsonv4/inbounds_remove.go | package jsonv4
import (
"fmt"
handlerService "github.com/v2fly/v2ray-core/v5/app/proxyman/command"
"github.com/v2fly/v2ray-core/v5/main/commands/all/api"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
"github.com/v2fly/v2ray-core/v5/main/commands/helpers"
)
var cmdRemoveInbounds = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} api rmi [--server=127.0.0.1:8080] [c1.json] [dir1]...",
Short: "remove inbounds",
Long: `
Remove inbounds from V2Ray.
> Make sure you have "HandlerService" set in "config.api.services"
of server config.
Arguments:
-format <format>
The input format.
Available values: "auto", "json", "toml", "yaml"
Default: "auto"
-r
Load folders recursively.
-tags
The input are tags instead of config files
-s, -server <server:port>
The API server address. Default 127.0.0.1:8080
-t, -timeout <seconds>
Timeout seconds to call API. Default 3
Example:
{{.Exec}} {{.LongName}} dir
{{.Exec}} {{.LongName}} c1.json c2.yaml
{{.Exec}} {{.LongName}} -tags tag1 tag2
`,
Run: executeRemoveInbounds,
}
func executeRemoveInbounds(cmd *base.Command, args []string) {
api.SetSharedFlags(cmd)
api.SetSharedConfigFlags(cmd)
isTags := cmd.Flag.Bool("tags", false, "")
cmd.Flag.Parse(args)
var tags []string
if *isTags {
tags = cmd.Flag.Args()
} else {
c, err := helpers.LoadConfig(cmd.Flag.Args(), api.APIConfigFormat, api.APIConfigRecursively)
if err != nil {
base.Fatalf("failed to load: %s", err)
}
tags = make([]string, 0)
for _, c := range c.InboundConfigs {
tags = append(tags, c.Tag)
}
}
if len(tags) == 0 {
base.Fatalf("no inbound to remove")
}
conn, ctx, close := api.DialAPIServer()
defer close()
client := handlerService.NewHandlerServiceClient(conn)
for _, tag := range tags {
fmt.Println("removing:", tag)
r := &handlerService.RemoveInboundRequest{
Tag: tag,
}
_, err := client.RemoveInbound(ctx, r)
if err != nil {
base.Fatalf("failed to remove inbound: %s", err)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/jsonv4/init.go | main/commands/all/jsonv4/init.go | package jsonv4
import "github.com/v2fly/v2ray-core/v5/main/commands/base"
func init() {
base.RegisterCommand(cmdConvert)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/jsonv4/convert.go | main/commands/all/jsonv4/convert.go | package jsonv4
import (
"bytes"
"encoding/json"
"os"
"strings"
"github.com/pelletier/go-toml"
"google.golang.org/protobuf/proto"
"gopkg.in/yaml.v3"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/infra/conf/jsonpb"
"github.com/v2fly/v2ray-core/v5/infra/conf/merge"
"github.com/v2fly/v2ray-core/v5/infra/conf/v2jsonpb"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
"github.com/v2fly/v2ray-core/v5/main/commands/helpers"
)
var cmdConvert = &base.Command{
CustomFlags: true,
UsageLine: "{{.Exec}} convert [c1.json] [<url>.json] [dir1] ...",
Short: "convert config files",
Long: `
Convert config files between different formats. Files are merged
before convert.
Arguments:
-i, -input <format>
The input format.
Available values: "auto", "json", "toml", "yaml"
Default: "auto"
-o, -output <format>
The output format
Available values: "json", "toml", "yaml", "protobuf" / "pb"
Default: "json"
-r
Load folders recursively.
Examples:
{{.Exec}} {{.LongName}} -output=protobuf "path/to/dir" (1)
{{.Exec}} {{.LongName}} -o=yaml config.toml (2)
{{.Exec}} {{.LongName}} c1.json c2.json (3)
{{.Exec}} {{.LongName}} -output=yaml c1.yaml <url>.yaml (4)
(1) Merge all supported files in dir and convert to protobuf
(2) Convert toml to yaml
(3) Merge json files
(4) Merge yaml files
Use "{{.Exec}} help config-merge" for more information about merge.
`,
}
func init() {
cmdConvert.Run = executeConvert // break init loop
}
var (
inputFormat string
outputFormat string
confDirRecursively bool
)
func setConfArgs(cmd *base.Command) {
cmd.Flag.StringVar(&inputFormat, "input", core.FormatAuto, "")
cmd.Flag.StringVar(&inputFormat, "i", core.FormatAuto, "")
cmd.Flag.StringVar(&outputFormat, "output", "json", "")
cmd.Flag.StringVar(&outputFormat, "o", "json", "")
cmd.Flag.BoolVar(&confDirRecursively, "r", false, "")
}
func executeConvert(cmd *base.Command, args []string) {
setConfArgs(cmd)
cmd.Flag.Parse(args)
inputFormat = strings.ToLower(inputFormat)
outputFormat = strings.ToLower(outputFormat)
inputFormatMerge := inputFormat
if inputFormat == "jsonv5" {
inputFormatMerge = "json"
}
m, err := helpers.LoadConfigToMap(cmd.Flag.Args(), inputFormatMerge, confDirRecursively)
if err != nil {
base.Fatalf("failed to merge: %s", err)
}
err = merge.ApplyRules(m)
if err != nil {
base.Fatalf("failed to apply merge rules: %s", err)
}
var out []byte
switch outputFormat {
case core.FormatJSON:
out, err = json.Marshal(m)
if err != nil {
base.Fatalf("failed to convert to json: %s", err)
}
case core.FormatTOML:
out, err = toml.Marshal(m)
if err != nil {
base.Fatalf("failed to convert to toml: %s", err)
}
case core.FormatYAML:
out, err = yaml.Marshal(m)
if err != nil {
base.Fatalf("failed to convert to yaml: %s", err)
}
case core.FormatProtobuf, core.FormatProtobufShort:
data, err := json.Marshal(m)
if err != nil {
base.Fatalf("failed to marshal json: %s", err)
}
r := bytes.NewReader(data)
pbConfig, err := core.LoadConfig(inputFormat, r)
if err != nil {
base.Fatalf("%v", err.Error())
}
out, err = proto.Marshal(pbConfig)
if err != nil {
base.Fatalf("failed to convert to protobuf: %s", err)
}
case jsonpb.FormatProtobufJSONPB:
data, err := json.Marshal(m)
if err != nil {
base.Fatalf("failed to marshal json: %s", err)
}
r := bytes.NewReader(data)
pbConfig, err := core.LoadConfig(inputFormat, r)
if err != nil {
base.Fatalf("%v", err.Error())
}
w := bytes.NewBuffer(nil)
err = jsonpb.DumpJSONPb(pbConfig, w)
if err != nil {
base.Fatalf("%v", err.Error())
}
out = w.Bytes()
case v2jsonpb.FormatProtobufV2JSONPB:
data, err := json.Marshal(m)
if err != nil {
base.Fatalf("failed to marshal json: %s", err)
}
r := bytes.NewReader(data)
pbConfig, err := core.LoadConfig(inputFormat, r)
if err != nil {
base.Fatalf("%v", err.Error())
}
out, err = v2jsonpb.DumpV2JsonPb(pbConfig)
if err != nil {
base.Fatalf("%v", err.Error())
}
default:
base.Errorf("invalid output format: %s", outputFormat)
base.Errorf("Run '%s help %s' for details.", base.CommandEnv.Exec, cmd.LongName())
base.Exit()
}
if _, err := os.Stdout.Write(out); err != nil {
base.Fatalf("failed to write stdout: %s", err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/engineering/nonnativelinkexec.go | main/commands/all/engineering/nonnativelinkexec.go | package engineering
import (
"bytes"
"flag"
"io"
"os"
"github.com/v2fly/v2ray-core/v5/app/subscription/entries/nonnative"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdNonNativeLinkExecInputName *string
var cmdNonNativeLinkExecTemplatePath *string
var cmdNonNativeLinkExec = &base.Command{
UsageLine: "{{.Exec}} engineering nonnativelinkexec",
Flag: func() flag.FlagSet {
fs := flag.NewFlagSet("", flag.ExitOnError)
cmdNonNativeLinkExecInputName = fs.String("name", "", "")
cmdNonNativeLinkExecTemplatePath = fs.String("templatePath", "", "path for template directory (WARNING: This will not stop templates from reading file outside this directory)")
return *fs
}(),
Run: func(cmd *base.Command, args []string) {
cmd.Flag.Parse(args)
content, err := io.ReadAll(os.Stdin)
if err != nil {
base.Fatalf("%s", err)
}
flattenedLink := nonnative.ExtractAllValuesFromBytes(content)
matcher := nonnative.NewDefMatcher()
if *cmdNonNativeLinkExecTemplatePath != "" {
osFs := os.DirFS(*cmdNonNativeLinkExecTemplatePath)
err = matcher.LoadDefinitions(osFs)
if err != nil {
base.Fatalf("%s", err)
}
} else {
err = matcher.LoadEmbeddedDefinitions()
if err != nil {
base.Fatalf("%s", err)
}
}
spec, err := matcher.ExecuteNamed(flattenedLink, *cmdNonNativeLinkExecInputName)
if err != nil {
base.Fatalf("%s", err)
}
io.Copy(os.Stdout, bytes.NewReader(spec))
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/engineering/engineering.go | main/commands/all/engineering/engineering.go | package engineering
import "github.com/v2fly/v2ray-core/v5/main/commands/base"
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
var cmdEngineering = &base.Command{
UsageLine: "{{.Exec}} engineering",
Commands: []*base.Command{
cmdConvertPb,
cmdReversePb,
cmdNonNativeLinkExtract,
cmdNonNativeLinkExec,
cmdSubscriptionEntriesExtract,
cmdEncodeDataURL,
},
}
func init() {
base.RegisterCommand(cmdEngineering)
}
func AddCommand(cmd *base.Command) {
cmdEngineering.Commands = append(cmdEngineering.Commands, cmd)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/engineering/errors.generated.go | main/commands/all/engineering/errors.generated.go | package engineering
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/main/commands/all/engineering/convertpb.go | main/commands/all/engineering/convertpb.go | package engineering
import (
"bytes"
"fmt"
"io"
"os"
"google.golang.org/protobuf/proto"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common/cmdarg"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var (
configFiles cmdarg.Arg
configDirs cmdarg.Arg
configFormat *string
configDirRecursively *bool
)
func setConfigFlags(cmd *base.Command) {
configFormat = cmd.Flag.String("format", core.FormatAuto, "")
configDirRecursively = cmd.Flag.Bool("r", false, "")
cmd.Flag.Var(&configFiles, "config", "")
cmd.Flag.Var(&configFiles, "c", "")
cmd.Flag.Var(&configDirs, "confdir", "")
cmd.Flag.Var(&configDirs, "d", "")
}
var cmdConvertPb = &base.Command{
UsageLine: "{{.Exec}} engineering convertpb [-c config.json] [-d dir]",
CustomFlags: true,
Run: func(cmd *base.Command, args []string) {
setConfigFlags(cmd)
cmd.Flag.Parse(args)
config, err := core.LoadConfig(*configFormat, configFiles)
if err != nil {
if len(configFiles) == 0 {
base.Fatalf("%s", newError("failed to load config").Base(err))
return
}
base.Fatalf("%s", newError(fmt.Sprintf("failed to load config: %s", configFiles)).Base(err))
return
}
bytew, err := proto.Marshal(config)
if err != nil {
base.Fatalf("%s", newError("failed to marshal config").Base(err))
return
}
io.Copy(os.Stdout, bytes.NewReader(bytew))
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/engineering/reversepb.go | main/commands/all/engineering/reversepb.go | package engineering
import (
"bytes"
"flag"
"io"
"os"
"github.com/golang/protobuf/proto"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/infra/conf/jsonpb"
"github.com/v2fly/v2ray-core/v5/infra/conf/v2jsonpb"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdReversePb = &base.Command{
UsageLine: "{{.Exec}} engineering reversepb [-f format]",
Flag: func() flag.FlagSet {
fs := flag.NewFlagSet("", flag.ExitOnError)
configFormat = fs.String("f", "v2jsonpb", "")
return *fs
}(),
Run: func(cmd *base.Command, args []string) {
cmd.Flag.Parse(args)
configIn := bytes.NewBuffer(nil)
io.Copy(configIn, os.Stdin)
var conf core.Config
if err := proto.Unmarshal(configIn.Bytes(), &conf); err != nil {
base.Fatalf("%s", err)
}
switch *configFormat {
case "jsonpb":
if err := jsonpb.DumpJSONPb(&conf, os.Stdout); err != nil {
base.Fatalf("%s", err)
}
case "v2jsonpb":
if value, err := v2jsonpb.DumpV2JsonPb(&conf); err != nil {
base.Fatalf("%s", err)
} else {
io.Copy(os.Stdout, bytes.NewReader(value))
}
}
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/engineering/encodedataurl.go | main/commands/all/engineering/encodedataurl.go | package engineering
import (
"flag"
"io"
"os"
"github.com/vincent-petithory/dataurl"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdEncodeDataURLContentType *string
var cmdEncodeDataURL = &base.Command{
UsageLine: "{{.Exec}} engineering encodeDataURL",
Flag: func() flag.FlagSet {
fs := flag.NewFlagSet("", flag.ExitOnError)
cmdEncodeDataURLContentType = fs.String("type", "application/vnd.v2ray.subscription-singular", "")
return *fs
}(),
Run: func(cmd *base.Command, args []string) {
cmd.Flag.Parse(args)
content, err := io.ReadAll(os.Stdin)
if err != nil {
base.Fatalf("%s", err)
}
dataURL := dataurl.New(content, *cmdEncodeDataURLContentType)
dataURL.WriteTo(os.Stdout)
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/engineering/nonnativelinkextract.go | main/commands/all/engineering/nonnativelinkextract.go | package engineering
import (
"flag"
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/v2fly/v2ray-core/v5/app/subscription/entries/nonnative"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
type valueContainer struct {
key, value string
}
type orderedValueContainer []valueContainer
func (o *orderedValueContainer) Len() int {
return len(*o)
}
func (o *orderedValueContainer) Less(i, j int) bool {
return strings.Compare((*o)[i].key, (*o)[j].key) < 0
}
func (o *orderedValueContainer) Swap(i, j int) {
(*o)[i], (*o)[j] = (*o)[j], (*o)[i]
}
var cmdNonNativeLinkExtract = &base.Command{
UsageLine: "{{.Exec}} engineering nonnativelinkextract",
Flag: func() flag.FlagSet {
fs := flag.NewFlagSet("", flag.ExitOnError)
return *fs
}(),
Run: func(cmd *base.Command, args []string) {
content, err := io.ReadAll(os.Stdin)
if err != nil {
base.Fatalf("%s", err)
}
flattenedLink := nonnative.ExtractAllValuesFromBytes(content)
var valueContainerOrdered orderedValueContainer
for key, value := range flattenedLink.Values {
valueContainerOrdered = append(valueContainerOrdered, valueContainer{key, value})
}
sort.Sort(&valueContainerOrdered)
for _, valueContainer := range valueContainerOrdered {
io.WriteString(os.Stdout, fmt.Sprintf("%s=%s\n", valueContainer.key, valueContainer.value))
}
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/engineering/subscriptionEntriesExtract.go | main/commands/all/engineering/subscriptionEntriesExtract.go | package engineering
import (
"archive/zip"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"golang.org/x/crypto/sha3"
"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
var cmdSubscriptionEntriesExtractInputName *string
var cmdSubscriptionEntriesExtract = &base.Command{
UsageLine: "{{.Exec}} engineering subscriptionEntriesExtract",
Flag: func() flag.FlagSet {
fs := flag.NewFlagSet("", flag.ExitOnError)
cmdSubscriptionEntriesExtractInputName = fs.String("input", "", "")
return *fs
}(),
Run: func(cmd *base.Command, args []string) {
cmd.Flag.Parse(args)
inputReader := os.Stdin
if *cmdSubscriptionEntriesExtractInputName != "" {
file, err := os.Open(*cmdSubscriptionEntriesExtractInputName)
if err != nil {
base.Fatalf("%s", err)
}
inputReader = file
defer file.Close()
}
content, err := io.ReadAll(inputReader)
if err != nil {
base.Fatalf("%s", err)
}
parsed, err := containers.TryAllParsers(content, "")
if err != nil {
base.Fatalf("%s", err)
}
zipWriter := zip.NewWriter(os.Stdout)
{
writer, err := zipWriter.Create("meta.json")
if err != nil {
base.Fatalf("%s", err)
}
err = json.NewEncoder(writer).Encode(parsed.Metadata)
if err != nil {
base.Fatalf("%s", err)
}
}
for k, entry := range parsed.ServerSpecs {
hash := sha3.Sum256(entry.Content)
fileName := fmt.Sprintf("entry_%v_%x", k, hash[:8])
writer, err := zipWriter.Create(fileName)
if err != nil {
base.Fatalf("%s", err)
}
_, err = writer.Write(entry.Content)
if err != nil {
base.Fatalf("%s", err)
}
}
zipWriter.Close()
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/commands/all/engineering/generateRandomData/errors.generated.go | main/commands/all/engineering/generateRandomData/errors.generated.go | package generateRandomData
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/main/commands/all/engineering/generateRandomData/generateRandomData.go | main/commands/all/engineering/generateRandomData/generateRandomData.go | package generateRandomData
import (
"crypto/rand"
"encoding/base64"
"flag"
"fmt"
"github.com/v2fly/v2ray-core/v5/main/commands/all/engineering"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
var length *int
var cmdGenerateRandomData = &base.Command{
UsageLine: "{{.Exec}} engineering generate-random-data",
Short: "generate random data and output as base64",
Long: `
Generate random data of specified length and output as base64 encoded string.
Usage:
{{.Exec}} engineering generate-random-data -length <bytes>
Options:
-length <bytes>
The number of random bytes to generate (required)
Example:
{{.Exec}} engineering generate-random-data -length 32
`,
Flag: func() flag.FlagSet {
fs := flag.NewFlagSet("", flag.ExitOnError)
length = fs.Int("length", 0, "number of random bytes to generate")
return *fs
}(),
Run: func(cmd *base.Command, args []string) {
err := cmd.Flag.Parse(args)
if err != nil {
base.Fatalf("failed to parse flags: %v", err)
}
if *length <= 0 {
base.Fatalf("length must be a positive integer, got: %d", *length)
}
// Generate random data
randomData := make([]byte, *length)
_, err = rand.Read(randomData)
if err != nil {
base.Fatalf("failed to generate random data: %v", err)
}
// Encode to base64
encoded := base64.StdEncoding.EncodeToString(randomData)
// Output the result
fmt.Println(encoded)
},
}
func init() {
engineering.AddCommand(cmdGenerateRandomData)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/v2binding/v2binding.go | main/v2binding/v2binding.go | package v2binding
import (
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/commander"
"github.com/v2fly/v2ray-core/v5/app/dispatcher"
"github.com/v2fly/v2ray-core/v5/app/instman"
"github.com/v2fly/v2ray-core/v5/app/instman/command"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/app/router"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/serial"
_ "github.com/v2fly/v2ray-core/v5/main/distro/all"
"github.com/v2fly/v2ray-core/v5/proxy/blackhole"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
)
type bindingInstance struct {
started bool
instance *core.Instance
}
var binding bindingInstance
func (b *bindingInstance) startAPIInstance() {
bindConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&instman.Config{}),
serial.ToTypedMessage(&commander.Config{
Tag: "api",
Service: []*anypb.Any{
serial.ToTypedMessage(&command.Config{}),
},
}),
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
InboundTag: []string{"api"},
TargetTag: &router.RoutingRule_Tag{
Tag: "api",
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
Tag: "api",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(10999),
Listen: net.NewIPOrDomain(net.AnyIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(10999),
Networks: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
},
}
bindConfig = withDefaultApps(bindConfig)
instance, err := core.New(bindConfig)
if err != nil {
panic(err)
}
err = instance.Start()
if err != nil {
panic(err)
}
b.instance = instance
}
func withDefaultApps(config *core.Config) *core.Config {
config.App = append(config.App, serial.ToTypedMessage(&dispatcher.Config{}))
config.App = append(config.App, serial.ToTypedMessage(&proxyman.InboundConfig{}))
config.App = append(config.App, serial.ToTypedMessage(&proxyman.OutboundConfig{}))
return config
}
func StartAPIInstance(basedir string) {
if binding.started {
return
}
binding.started = true
binding.startAPIInstance()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/v2binding/v2api/api.go | main/v2binding/v2api/api.go | package main
import (
"time"
"github.com/v2fly/v2ray-core/v5/main/v2binding"
)
func main() {
v2binding.StartAPIInstance(".")
for {
time.Sleep(time.Minute)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/plugins/plugin.go | main/plugins/plugin.go | package plugins
import "github.com/v2fly/v2ray-core/v5/main/commands/base"
var Plugins []Plugin
type Plugin func(*base.Command) func() error
func RegisterPlugin(plugin Plugin) {
Plugins = append(Plugins, plugin)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/plugins/plugin_pprof/plugin_pprof.go | main/plugins/plugin_pprof/plugin_pprof.go | package plugin_pprof //nolint: stylecheck
import (
"net/http"
"net/http/pprof"
"github.com/v2fly/v2ray-core/v5/main/commands/base"
"github.com/v2fly/v2ray-core/v5/main/plugins"
)
var pprofPlugin plugins.Plugin = func(cmd *base.Command) func() error {
addr := cmd.Flag.String("pprof", "", "")
return func() error {
if *addr != "" {
h := http.NewServeMux()
h.HandleFunc("/debug/pprof/", pprof.Index)
h.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
h.HandleFunc("/debug/pprof/profile", pprof.Profile)
h.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
h.HandleFunc("/debug/pprof/trace", pprof.Trace)
return (&http.Server{Addr: *addr, Handler: h}).ListenAndServe()
}
return nil
}
}
func init() {
plugins.RegisterPlugin(pprofPlugin)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/main/formats/errors.generated.go | main/formats/errors.generated.go | package formats
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/main/formats/formats.go | main/formats/formats.go | package formats
import (
"bytes"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/infra/conf/merge"
"github.com/v2fly/v2ray-core/v5/infra/conf/mergers"
"github.com/v2fly/v2ray-core/v5/infra/conf/serial"
)
func init() {
for _, formatName := range mergers.GetAllNames() {
loader, err := makeMergeLoader(formatName)
if err != nil {
panic(err)
}
if formatName == core.FormatAuto {
loader.Extension = nil
}
common.Must(core.RegisterConfigLoader(loader))
}
}
func makeMergeLoader(formatName string) (*core.ConfigFormat, error) {
extensions, err := mergers.GetExtensions(formatName)
if err != nil {
return nil, err
}
return &core.ConfigFormat{
Name: []string{formatName},
Extension: extensions,
Loader: makeLoaderFunc(formatName),
}, nil
}
func makeLoaderFunc(formatName string) core.ConfigLoader {
return func(input interface{}) (*core.Config, error) {
m := make(map[string]interface{})
err := mergers.MergeAs(formatName, input, m)
if err != nil {
return nil, err
}
data, err := merge.FromMap(m)
if err != nil {
return nil, err
}
r := bytes.NewReader(data)
cf, err := serial.DecodeJSONConfig(r)
if err != nil {
return nil, err
}
return cf.Build()
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/mocks/proxy.go | testing/mocks/proxy.go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/v2fly/v2ray-core/v5/proxy (interfaces: Inbound,Outbound)
// Package mocks is a generated GoMock package.
package mocks
import (
context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
net "github.com/v2fly/v2ray-core/v5/common/net"
routing "github.com/v2fly/v2ray-core/v5/features/routing"
transport "github.com/v2fly/v2ray-core/v5/transport"
internet "github.com/v2fly/v2ray-core/v5/transport/internet"
)
// ProxyInbound is a mock of Inbound interface.
type ProxyInbound struct {
ctrl *gomock.Controller
recorder *ProxyInboundMockRecorder
}
// ProxyInboundMockRecorder is the mock recorder for ProxyInbound.
type ProxyInboundMockRecorder struct {
mock *ProxyInbound
}
// NewProxyInbound creates a new mock instance.
func NewProxyInbound(ctrl *gomock.Controller) *ProxyInbound {
mock := &ProxyInbound{ctrl: ctrl}
mock.recorder = &ProxyInboundMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *ProxyInbound) EXPECT() *ProxyInboundMockRecorder {
return m.recorder
}
// Network mocks base method.
func (m *ProxyInbound) Network() []net.Network {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Network")
ret0, _ := ret[0].([]net.Network)
return ret0
}
// Network indicates an expected call of Network.
func (mr *ProxyInboundMockRecorder) Network() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Network", reflect.TypeOf((*ProxyInbound)(nil).Network))
}
// Process mocks base method.
func (m *ProxyInbound) Process(arg0 context.Context, arg1 net.Network, arg2 internet.Connection, arg3 routing.Dispatcher) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Process", arg0, arg1, arg2, arg3)
ret0, _ := ret[0].(error)
return ret0
}
// Process indicates an expected call of Process.
func (mr *ProxyInboundMockRecorder) Process(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Process", reflect.TypeOf((*ProxyInbound)(nil).Process), arg0, arg1, arg2, arg3)
}
// ProxyOutbound is a mock of Outbound interface.
type ProxyOutbound struct {
ctrl *gomock.Controller
recorder *ProxyOutboundMockRecorder
}
// ProxyOutboundMockRecorder is the mock recorder for ProxyOutbound.
type ProxyOutboundMockRecorder struct {
mock *ProxyOutbound
}
// NewProxyOutbound creates a new mock instance.
func NewProxyOutbound(ctrl *gomock.Controller) *ProxyOutbound {
mock := &ProxyOutbound{ctrl: ctrl}
mock.recorder = &ProxyOutboundMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *ProxyOutbound) EXPECT() *ProxyOutboundMockRecorder {
return m.recorder
}
// Process mocks base method.
func (m *ProxyOutbound) Process(arg0 context.Context, arg1 *transport.Link, arg2 internet.Dialer) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Process", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
// Process indicates an expected call of Process.
func (mr *ProxyOutboundMockRecorder) Process(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Process", reflect.TypeOf((*ProxyOutbound)(nil).Process), arg0, arg1, arg2)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/mocks/dns.go | testing/mocks/dns.go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/v2fly/v2ray-core/v5/features/dns (interfaces: Client)
// Package mocks is a generated GoMock package.
package mocks
import (
net "net"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// DNSClient is a mock of Client interface.
type DNSClient struct {
ctrl *gomock.Controller
recorder *DNSClientMockRecorder
}
// DNSClientMockRecorder is the mock recorder for DNSClient.
type DNSClientMockRecorder struct {
mock *DNSClient
}
// NewDNSClient creates a new mock instance.
func NewDNSClient(ctrl *gomock.Controller) *DNSClient {
mock := &DNSClient{ctrl: ctrl}
mock.recorder = &DNSClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *DNSClient) EXPECT() *DNSClientMockRecorder {
return m.recorder
}
// Close mocks base method.
func (m *DNSClient) Close() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Close")
ret0, _ := ret[0].(error)
return ret0
}
// Close indicates an expected call of Close.
func (mr *DNSClientMockRecorder) Close() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*DNSClient)(nil).Close))
}
// LookupIP mocks base method.
func (m *DNSClient) LookupIP(arg0 string) ([]net.IP, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LookupIP", arg0)
ret0, _ := ret[0].([]net.IP)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LookupIP indicates an expected call of LookupIP.
func (mr *DNSClientMockRecorder) LookupIP(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LookupIP", reflect.TypeOf((*DNSClient)(nil).LookupIP), arg0)
}
// Start mocks base method.
func (m *DNSClient) Start() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Start")
ret0, _ := ret[0].(error)
return ret0
}
// Start indicates an expected call of Start.
func (mr *DNSClientMockRecorder) Start() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*DNSClient)(nil).Start))
}
// Type mocks base method.
func (m *DNSClient) Type() interface{} {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Type")
ret0, _ := ret[0].(interface{})
return ret0
}
// Type indicates an expected call of Type.
func (mr *DNSClientMockRecorder) Type() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Type", reflect.TypeOf((*DNSClient)(nil).Type))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/mocks/io.go | testing/mocks/io.go | // Code generated by MockGen. DO NOT EDIT.
// Source: io (interfaces: Reader,Writer)
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// Reader is a mock of Reader interface.
type Reader struct {
ctrl *gomock.Controller
recorder *ReaderMockRecorder
}
// ReaderMockRecorder is the mock recorder for Reader.
type ReaderMockRecorder struct {
mock *Reader
}
// NewReader creates a new mock instance.
func NewReader(ctrl *gomock.Controller) *Reader {
mock := &Reader{ctrl: ctrl}
mock.recorder = &ReaderMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Reader) EXPECT() *ReaderMockRecorder {
return m.recorder
}
// Read mocks base method.
func (m *Reader) Read(arg0 []byte) (int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Read", arg0)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Read indicates an expected call of Read.
func (mr *ReaderMockRecorder) Read(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*Reader)(nil).Read), arg0)
}
// Writer is a mock of Writer interface.
type Writer struct {
ctrl *gomock.Controller
recorder *WriterMockRecorder
}
// WriterMockRecorder is the mock recorder for Writer.
type WriterMockRecorder struct {
mock *Writer
}
// NewWriter creates a new mock instance.
func NewWriter(ctrl *gomock.Controller) *Writer {
mock := &Writer{ctrl: ctrl}
mock.recorder = &WriterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Writer) EXPECT() *WriterMockRecorder {
return m.recorder
}
// Write mocks base method.
func (m *Writer) Write(arg0 []byte) (int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Write", arg0)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Write indicates an expected call of Write.
func (mr *WriterMockRecorder) Write(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*Writer)(nil).Write), arg0)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/mocks/log.go | testing/mocks/log.go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/v2fly/v2ray-core/v5/common/log (interfaces: Handler)
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
log "github.com/v2fly/v2ray-core/v5/common/log"
)
// LogHandler is a mock of Handler interface.
type LogHandler struct {
ctrl *gomock.Controller
recorder *LogHandlerMockRecorder
}
// LogHandlerMockRecorder is the mock recorder for LogHandler.
type LogHandlerMockRecorder struct {
mock *LogHandler
}
// NewLogHandler creates a new mock instance.
func NewLogHandler(ctrl *gomock.Controller) *LogHandler {
mock := &LogHandler{ctrl: ctrl}
mock.recorder = &LogHandlerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *LogHandler) EXPECT() *LogHandlerMockRecorder {
return m.recorder
}
// Handle mocks base method.
func (m *LogHandler) Handle(arg0 log.Message) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Handle", arg0)
}
// Handle indicates an expected call of Handle.
func (mr *LogHandlerMockRecorder) Handle(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Handle", reflect.TypeOf((*LogHandler)(nil).Handle), arg0)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/mocks/outbound.go | testing/mocks/outbound.go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/v2fly/v2ray-core/v5/features/outbound (interfaces: Manager,HandlerSelector)
// Package mocks is a generated GoMock package.
package mocks
import (
context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
outbound "github.com/v2fly/v2ray-core/v5/features/outbound"
)
// OutboundManager is a mock of Manager interface.
type OutboundManager struct {
ctrl *gomock.Controller
recorder *OutboundManagerMockRecorder
}
// OutboundManagerMockRecorder is the mock recorder for OutboundManager.
type OutboundManagerMockRecorder struct {
mock *OutboundManager
}
// NewOutboundManager creates a new mock instance.
func NewOutboundManager(ctrl *gomock.Controller) *OutboundManager {
mock := &OutboundManager{ctrl: ctrl}
mock.recorder = &OutboundManagerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *OutboundManager) EXPECT() *OutboundManagerMockRecorder {
return m.recorder
}
// AddHandler mocks base method.
func (m *OutboundManager) AddHandler(arg0 context.Context, arg1 outbound.Handler) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AddHandler", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// AddHandler indicates an expected call of AddHandler.
func (mr *OutboundManagerMockRecorder) AddHandler(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHandler", reflect.TypeOf((*OutboundManager)(nil).AddHandler), arg0, arg1)
}
// Close mocks base method.
func (m *OutboundManager) Close() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Close")
ret0, _ := ret[0].(error)
return ret0
}
// Close indicates an expected call of Close.
func (mr *OutboundManagerMockRecorder) Close() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*OutboundManager)(nil).Close))
}
// GetDefaultHandler mocks base method.
func (m *OutboundManager) GetDefaultHandler() outbound.Handler {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetDefaultHandler")
ret0, _ := ret[0].(outbound.Handler)
return ret0
}
// GetDefaultHandler indicates an expected call of GetDefaultHandler.
func (mr *OutboundManagerMockRecorder) GetDefaultHandler() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDefaultHandler", reflect.TypeOf((*OutboundManager)(nil).GetDefaultHandler))
}
// GetHandler mocks base method.
func (m *OutboundManager) GetHandler(arg0 string) outbound.Handler {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetHandler", arg0)
ret0, _ := ret[0].(outbound.Handler)
return ret0
}
// GetHandler indicates an expected call of GetHandler.
func (mr *OutboundManagerMockRecorder) GetHandler(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHandler", reflect.TypeOf((*OutboundManager)(nil).GetHandler), arg0)
}
// RemoveHandler mocks base method.
func (m *OutboundManager) RemoveHandler(arg0 context.Context, arg1 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RemoveHandler", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// RemoveHandler indicates an expected call of RemoveHandler.
func (mr *OutboundManagerMockRecorder) RemoveHandler(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveHandler", reflect.TypeOf((*OutboundManager)(nil).RemoveHandler), arg0, arg1)
}
// Start mocks base method.
func (m *OutboundManager) Start() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Start")
ret0, _ := ret[0].(error)
return ret0
}
// Start indicates an expected call of Start.
func (mr *OutboundManagerMockRecorder) Start() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*OutboundManager)(nil).Start))
}
// Type mocks base method.
func (m *OutboundManager) Type() interface{} {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Type")
ret0, _ := ret[0].(interface{})
return ret0
}
// Type indicates an expected call of Type.
func (mr *OutboundManagerMockRecorder) Type() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Type", reflect.TypeOf((*OutboundManager)(nil).Type))
}
// OutboundHandlerSelector is a mock of HandlerSelector interface.
type OutboundHandlerSelector struct {
ctrl *gomock.Controller
recorder *OutboundHandlerSelectorMockRecorder
}
// OutboundHandlerSelectorMockRecorder is the mock recorder for OutboundHandlerSelector.
type OutboundHandlerSelectorMockRecorder struct {
mock *OutboundHandlerSelector
}
// NewOutboundHandlerSelector creates a new mock instance.
func NewOutboundHandlerSelector(ctrl *gomock.Controller) *OutboundHandlerSelector {
mock := &OutboundHandlerSelector{ctrl: ctrl}
mock.recorder = &OutboundHandlerSelectorMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *OutboundHandlerSelector) EXPECT() *OutboundHandlerSelectorMockRecorder {
return m.recorder
}
// Select mocks base method.
func (m *OutboundHandlerSelector) Select(arg0 []string) []string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Select", arg0)
ret0, _ := ret[0].([]string)
return ret0
}
// Select indicates an expected call of Select.
func (mr *OutboundHandlerSelectorMockRecorder) Select(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Select", reflect.TypeOf((*OutboundHandlerSelector)(nil).Select), arg0)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/mocks/mux.go | testing/mocks/mux.go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/v2fly/v2ray-core/v5/common/mux (interfaces: ClientWorkerFactory)
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
mux "github.com/v2fly/v2ray-core/v5/common/mux"
)
// MuxClientWorkerFactory is a mock of ClientWorkerFactory interface.
type MuxClientWorkerFactory struct {
ctrl *gomock.Controller
recorder *MuxClientWorkerFactoryMockRecorder
}
// MuxClientWorkerFactoryMockRecorder is the mock recorder for MuxClientWorkerFactory.
type MuxClientWorkerFactoryMockRecorder struct {
mock *MuxClientWorkerFactory
}
// NewMuxClientWorkerFactory creates a new mock instance.
func NewMuxClientWorkerFactory(ctrl *gomock.Controller) *MuxClientWorkerFactory {
mock := &MuxClientWorkerFactory{ctrl: ctrl}
mock.recorder = &MuxClientWorkerFactoryMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MuxClientWorkerFactory) EXPECT() *MuxClientWorkerFactoryMockRecorder {
return m.recorder
}
// Create mocks base method.
func (m *MuxClientWorkerFactory) Create() (*mux.ClientWorker, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Create")
ret0, _ := ret[0].(*mux.ClientWorker)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Create indicates an expected call of Create.
func (mr *MuxClientWorkerFactoryMockRecorder) Create() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MuxClientWorkerFactory)(nil).Create))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/command_test.go | testing/scenarios/command_test.go | package scenarios
import (
"context"
"fmt"
"io"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/commander"
"github.com/v2fly/v2ray-core/v5/app/policy"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/app/proxyman/command"
"github.com/v2fly/v2ray-core/v5/app/router"
"github.com/v2fly/v2ray-core/v5/app/stats"
statscmd "github.com/v2fly/v2ray-core/v5/app/stats/command"
"github.com/v2fly/v2ray-core/v5/common"
"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"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
)
func TestCommanderRemoveHandler(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
clientPort := tcp.PickPort()
cmdPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&commander.Config{
Tag: "api",
Service: []*anypb.Any{
serial.ToTypedMessage(&command.Config{}),
},
}),
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
InboundTag: []string{"api"},
TargetTag: &router.RoutingRule_Tag{
Tag: "api",
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
Tag: "d",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
Networks: []net.Network{net.Network_TCP},
}),
},
{
Tag: "api",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(cmdPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
Networks: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "default-outbound",
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*5)(); err != nil {
t.Fatal(err)
}
cmdConn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", cmdPort), grpc.WithInsecure(), grpc.WithBlock())
common.Must(err)
defer cmdConn.Close()
hsClient := command.NewHandlerServiceClient(cmdConn)
resp, err := hsClient.RemoveInbound(context.Background(), &command.RemoveInboundRequest{
Tag: "d",
})
common.Must(err)
if resp == nil {
t.Error("unexpected nil response")
}
{
_, err := net.DialTCP("tcp", nil, &net.TCPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(clientPort),
})
if err == nil {
t.Error("unexpected nil error")
}
}
}
func TestCommanderAddRemoveUser(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
u1 := protocol.NewID(uuid.New())
u2 := protocol.NewID(uuid.New())
cmdPort := tcp.PickPort()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&commander.Config{
Tag: "api",
Service: []*anypb.Any{
serial.ToTypedMessage(&command.Config{}),
},
}),
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
InboundTag: []string{"api"},
TargetTag: &router.RoutingRule_Tag{
Tag: "api",
},
},
},
}),
serial.ToTypedMessage(&policy.Config{
Level: map[uint32]*policy.Policy{
0: {
Timeout: &policy.Policy_Timeout{
UplinkOnly: &policy.Second{Value: 0},
DownlinkOnly: &policy.Second{Value: 0},
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
Tag: "v",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: u1.String(),
AlterId: 0,
}),
},
},
}),
},
{
Tag: "api",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(cmdPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
Networks: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&policy.Config{
Level: map[uint32]*policy.Policy{
0: {
Timeout: &policy.Policy_Timeout{
UplinkOnly: &policy.Second{Value: 0},
DownlinkOnly: &policy.Second{Value: 0},
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
Tag: "d",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: u2.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*5)(); err != io.EOF &&
/*We might wish to drain the connection*/
(err != nil && !strings.HasSuffix(err.Error(), "i/o timeout")) {
t.Fatal("expected error: ", err)
}
cmdConn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", cmdPort), grpc.WithInsecure(), grpc.WithBlock())
common.Must(err)
defer cmdConn.Close()
hsClient := command.NewHandlerServiceClient(cmdConn)
resp, err := hsClient.AlterInbound(context.Background(), &command.AlterInboundRequest{
Tag: "v",
Operation: serial.ToTypedMessage(
&command.AddUserOperation{
User: &protocol.User{
Email: "test@v2fly.org",
Account: serial.ToTypedMessage(&vmess.Account{
Id: u2.String(),
AlterId: 0,
}),
},
}),
})
common.Must(err)
if resp == nil {
t.Fatal("nil response")
}
if err := testTCPConn(clientPort, 1024, time.Second*5)(); err != nil {
t.Fatal(err)
}
resp, err = hsClient.AlterInbound(context.Background(), &command.AlterInboundRequest{
Tag: "v",
Operation: serial.ToTypedMessage(&command.RemoveUserOperation{Email: "test@v2fly.org"}),
})
common.Must(err)
if resp == nil {
t.Fatal("nil response")
}
}
func TestCommanderStats(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
cmdPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&stats.Config{}),
serial.ToTypedMessage(&commander.Config{
Tag: "api",
Service: []*anypb.Any{
serial.ToTypedMessage(&statscmd.Config{}),
},
}),
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
InboundTag: []string{"api"},
TargetTag: &router.RoutingRule_Tag{
Tag: "api",
},
},
},
}),
serial.ToTypedMessage(&policy.Config{
Level: map[uint32]*policy.Policy{
0: {
Timeout: &policy.Policy_Timeout{
UplinkOnly: &policy.Second{Value: 0},
DownlinkOnly: &policy.Second{Value: 0},
},
},
1: {
Stats: &policy.Policy_Stats{
UserUplink: true,
UserDownlink: true,
},
},
},
System: &policy.SystemPolicy{
Stats: &policy.SystemPolicy_Stats{
InboundUplink: true,
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
Tag: "vmess",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Level: 1,
Email: "test",
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
{
Tag: "api",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(cmdPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
if err != nil {
t.Fatal("Failed to create all servers", err)
}
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 10240*1024, time.Second*20)(); err != nil {
t.Fatal(err)
}
cmdConn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", cmdPort), grpc.WithInsecure(), grpc.WithBlock())
common.Must(err)
defer cmdConn.Close()
const name = "user>>>test>>>traffic>>>uplink"
sClient := statscmd.NewStatsServiceClient(cmdConn)
sresp, err := sClient.GetStats(context.Background(), &statscmd.GetStatsRequest{
Name: name,
Reset_: true,
})
common.Must(err)
if r := cmp.Diff(sresp.Stat, &statscmd.Stat{
Name: name,
Value: 10240 * 1024,
}, cmpopts.IgnoreUnexported(statscmd.Stat{})); r != "" {
t.Error(r)
}
sresp, err = sClient.GetStats(context.Background(), &statscmd.GetStatsRequest{
Name: name,
})
common.Must(err)
if r := cmp.Diff(sresp.Stat, &statscmd.Stat{
Name: name,
Value: 0,
}, cmpopts.IgnoreUnexported(statscmd.Stat{})); r != "" {
t.Error(r)
}
sresp, err = sClient.GetStats(context.Background(), &statscmd.GetStatsRequest{
Name: "inbound>>>vmess>>>traffic>>>uplink",
Reset_: true,
})
common.Must(err)
if sresp.Stat.Value <= 10240*1024 {
t.Error("value < 10240*1024: ", sresp.Stat.Value)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/tls_test.go | testing/scenarios/tls_test.go | package scenarios
import (
"crypto/x509"
"runtime"
"testing"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/protocol/tls/cert"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/http"
"github.com/v2fly/v2ray-core/v5/transport/internet/tls"
"github.com/v2fly/v2ray-core/v5/transport/internet/websocket"
)
func TestSimpleTLSConnection(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil))},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
AllowInsecure: true,
}),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*20)(); err != nil {
t.Fatal(err)
}
}
func TestAutoIssuingCertificate(t *testing.T) {
if runtime.GOOS == "windows" {
// Not supported on Windows yet.
return
}
if runtime.GOARCH == "arm64" {
return
}
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
caCert, err := cert.Generate(nil, cert.Authority(true), cert.KeyUsage(x509.KeyUsageDigitalSignature|x509.KeyUsageKeyEncipherment|x509.KeyUsageCertSign))
common.Must(err)
certPEM, keyPEM := caCert.ToPEM()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
Certificate: []*tls.Certificate{{
Certificate: certPEM,
Key: keyPEM,
Usage: tls.Certificate_AUTHORITY_ISSUE,
}},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
ServerName: "v2fly.org",
Certificate: []*tls.Certificate{{
Certificate: certPEM,
Usage: tls.Certificate_AUTHORITY_VERIFY,
}},
}),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
for i := 0; i < 10; i++ {
if err := testTCPConn(clientPort, 1024, time.Second*20)(); err != nil {
t.Error(err)
}
}
}
func TestIPAddressesCertificate(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
caCert, err := cert.Generate(nil, cert.IPAddresses(net.LocalHostIP.IP()), cert.Authority(true), cert.KeyUsage(x509.KeyUsageDigitalSignature|x509.KeyUsageKeyEncipherment|x509.KeyUsageCertSign))
common.Must(err)
certPEM, keyPEM := caCert.ToPEM()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
Certificate: []*tls.Certificate{{
Certificate: certPEM,
Key: keyPEM,
}},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
DisableSystemRoot: true,
Certificate: []*tls.Certificate{{
Certificate: certPEM,
Usage: tls.Certificate_AUTHORITY_VERIFY,
}},
}),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
for i := 0; i < 10; i++ {
if err := testTCPConn(clientPort, 1024, time.Second*20)(); err != nil {
t.Error(err)
}
}
}
func TestDNSNamesCertificate(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
caCert, err := cert.Generate(nil, cert.DNSNames("v2fly.org"), cert.Authority(true), cert.KeyUsage(x509.KeyUsageDigitalSignature|x509.KeyUsageKeyEncipherment|x509.KeyUsageCertSign))
common.Must(err)
certPEM, keyPEM := caCert.ToPEM()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
Certificate: []*tls.Certificate{{
Certificate: certPEM,
Key: keyPEM,
}},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
DisableSystemRoot: true,
ServerName: "v2fly.org",
Certificate: []*tls.Certificate{{
Certificate: certPEM,
Usage: tls.Certificate_AUTHORITY_VERIFY,
}},
}),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
for i := 0; i < 10; i++ {
if err := testTCPConn(clientPort, 1024, time.Second*20)(); err != nil {
t.Error(err)
}
}
}
func TestTLSOverKCP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := udp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil))},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
AllowInsecure: true,
}),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*20)(); err != nil {
t.Error(err)
}
}
func TestTLSOverWebSocket(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_WebSocket,
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil))},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_WebSocket,
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_WebSocket,
Settings: serial.ToTypedMessage(&websocket.Config{}),
},
},
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
AllowInsecure: true,
}),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*20))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestHTTP2(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_HTTP,
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_HTTP,
Settings: serial.ToTypedMessage(&http.Config{
Host: []string{"v2fly.org"},
Path: "/testpath",
}),
},
},
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil))},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_HTTP,
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_HTTP,
Settings: serial.ToTypedMessage(&http.Config{
Host: []string{"v2fly.org"},
Path: "/testpath",
}),
},
},
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
AllowInsecure: true,
}),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 7168*1024, time.Second*40))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestSimpleTLSConnectionPinned(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
certificateDer := cert.MustGenerate(nil)
certificate := tls.ParseCertificate(certificateDer)
certHash := tls.GenerateCertChainHash([][]byte{certificateDer.Certificate})
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
Certificate: []*tls.Certificate{certificate},
}),
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(&tls.Config{
AllowInsecure: true,
PinnedPeerCertificateChainSha256: [][]byte{certHash},
}),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*20)(); err != nil {
t.Fatal(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/dns_test.go | testing/scenarios/dns_test.go | package scenarios
import (
"fmt"
"testing"
"time"
xproxy "golang.org/x/net/proxy"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/dns"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/app/router"
"github.com/v2fly/v2ray-core/v5/app/router/routercommon"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/proxy/blackhole"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/socks"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
)
func TestResolveIP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dns.Config{
Hosts: map[string]*net.IPOrDomain{
"google.com": net.NewIPOrDomain(dest.Address),
},
}),
serial.ToTypedMessage(&router.Config{
DomainStrategy: router.DomainStrategy_IpIfNonMatch,
Rule: []*router.RoutingRule{
{
Cidr: []*routercommon.CIDR{
{
Ip: []byte{127, 0, 0, 0},
Prefix: 8,
},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "direct",
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{
AuthType: socks.AuthType_NO_AUTH,
Accounts: map[string]string{
"Test Account": "Test Password",
},
Address: net.NewIPOrDomain(net.LocalHostIP),
UdpEnabled: false,
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
{
Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{
DomainStrategy: freedom.Config_USE_IP,
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
noAuthDialer, err := xproxy.SOCKS5("tcp", net.TCPDestination(net.LocalHostIP, serverPort).NetAddr(), nil, xproxy.Direct)
common.Must(err)
conn, err := noAuthDialer.Dial("tcp", fmt.Sprintf("google.com:%d", dest.Port))
common.Must(err)
defer conn.Close()
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/hy2_test.go | testing/scenarios/hy2_test.go | package scenarios
import (
"testing"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/log"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
clog "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/protocol/tls/cert"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/hysteria2"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/headers/http"
hyTransport "github.com/v2fly/v2ray-core/v5/transport/internet/hysteria2"
tcpTransport "github.com/v2fly/v2ray-core/v5/transport/internet/tcp"
"github.com/v2fly/v2ray-core/v5/transport/internet/tls"
)
func TestVMessHysteria2Congestion(t *testing.T) {
for _, v := range []string{"bbr", "brutal"} {
testVMessHysteria2(t, v)
}
}
func testVMessHysteria2(t *testing.T, congestionType string) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := udp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
ProtocolName: "hysteria2",
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(
&tls.Config{
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil))},
},
),
},
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "hysteria2",
Settings: serial.ToTypedMessage(&hyTransport.Config{
Congestion: &hyTransport.Congestion{Type: congestionType, UpMbps: 100, DownMbps: 100},
Password: "password",
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
ProtocolName: "hysteria2",
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(
&tls.Config{
ServerName: "www.v2fly.org",
AllowInsecure: true,
},
),
},
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "hysteria2",
Settings: serial.ToTypedMessage(&hyTransport.Config{
Congestion: &hyTransport.Congestion{Type: congestionType, UpMbps: 100, DownMbps: 100},
Password: "password",
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_NONE,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
if err != nil {
t.Fatal("Failed to initialize all servers: ", err.Error())
}
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*40))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestHysteria2Offical(t *testing.T) {
for _, v := range []bool{true, false} {
testHysteria2Offical(t, v)
}
}
func testHysteria2Offical(t *testing.T, isUDP bool) {
var dest net.Destination
var err error
if isUDP {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err = udpServer.Start()
common.Must(err)
defer udpServer.Close()
} else {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err = tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
}
serverPort := udp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
ProtocolName: "hysteria2",
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(
&tls.Config{
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil))},
},
),
},
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "hysteria2",
Settings: serial.ToTypedMessage(&hyTransport.Config{
Congestion: &hyTransport.Congestion{Type: "brutal", UpMbps: 100, DownMbps: 100},
UseUdpExtension: true,
Password: "password",
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&hysteria2.ServerConfig{}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP, net.Network_UDP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
ProtocolName: "hysteria2",
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(
&tls.Config{
ServerName: "www.v2fly.org",
AllowInsecure: true,
},
),
},
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "hysteria2",
Settings: serial.ToTypedMessage(&hyTransport.Config{
Congestion: &hyTransport.Congestion{Type: "brutal", UpMbps: 100, DownMbps: 100},
UseUdpExtension: true,
Password: "password",
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&hysteria2.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&hysteria2.Account{}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
if err != nil {
t.Fatal("Failed to initialize all servers: ", err.Error())
}
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
if isUDP {
errg.Go(testUDPConn(clientPort, 1500, time.Second*4))
} else {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*40))
}
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestHysteria2OnTCP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
serverPort := udp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(
&tls.Config{
Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil))},
},
),
},
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_TCP,
Settings: serial.ToTypedMessage(&tcpTransport.Config{
HeaderSettings: serial.ToTypedMessage(&http.Config{}),
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&hysteria2.ServerConfig{}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
SecurityType: serial.GetMessageType(&tls.Config{}),
SecuritySettings: []*anypb.Any{
serial.ToTypedMessage(
&tls.Config{
ServerName: "www.v2fly.org",
AllowInsecure: true,
},
),
},
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_TCP,
Settings: serial.ToTypedMessage(&tcpTransport.Config{
HeaderSettings: serial.ToTypedMessage(&http.Config{}),
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&hysteria2.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&hysteria2.Account{}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
if err != nil {
t.Fatal("Failed to initialize all servers: ", err.Error())
}
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 1; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*40))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/feature_test.go | testing/scenarios/feature_test.go | package scenarios
import (
"context"
"io"
"net/http"
"net/url"
"testing"
"time"
xproxy "golang.org/x/net/proxy"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/dispatcher"
"github.com/v2fly/v2ray-core/v5/app/log"
"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/app/router"
"github.com/v2fly/v2ray-core/v5/common"
clog "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/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/blackhole"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
v2http "github.com/v2fly/v2ray-core/v5/proxy/http"
"github.com/v2fly/v2ray-core/v5/proxy/socks"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
func TestPassiveConnection(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
SendFirst: []byte("send first"),
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(serverPort),
})
common.Must(err)
{
response := make([]byte, 1024)
nBytes, err := conn.Read(response)
common.Must(err)
if string(response[:nBytes]) != "send first" {
t.Error("unexpected first response: ", string(response[:nBytes]))
}
}
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
func TestProxy(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
serverUserID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: serverUserID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
proxyUserID := protocol.NewID(uuid.New())
proxyPort := tcp.PickPort()
proxyConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(proxyPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: proxyUserID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: serverUserID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
ProxySettings: &internet.ProxyConfig{
Tag: "proxy",
},
}),
},
{
Tag: "proxy",
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(proxyPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: proxyUserID.String(),
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, proxyConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
func TestProxyOverKCP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
serverUserID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: serverUserID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
proxyUserID := protocol.NewID(uuid.New())
proxyPort := tcp.PickPort()
proxyConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(proxyPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: proxyUserID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
},
}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: serverUserID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
ProxySettings: &internet.ProxyConfig{
Tag: "proxy",
},
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
},
}),
},
{
Tag: "proxy",
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(proxyPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: proxyUserID.String(),
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, proxyConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
func TestBlackhole(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
tcpServer2 := tcp.Server{
MsgProcessor: xor,
}
dest2, err := tcpServer2.Start()
common.Must(err)
defer tcpServer2.Close()
serverPort := tcp.PickPort()
serverPort2 := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort2),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest2.Address),
Port: uint32(dest2.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
{
Tag: "blocked",
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
},
App: []*anypb.Any{
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
TargetTag: &router.RoutingRule_Tag{
Tag: "blocked",
},
PortRange: net.SinglePortRange(dest2.Port),
},
},
}),
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(serverPort2, 1024, time.Second*5)(); err == nil {
t.Error("nil error")
}
}
func TestForward(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{
AuthType: socks.AuthType_NO_AUTH,
Accounts: map[string]string{
"Test Account": "Test Password",
},
Address: net.NewIPOrDomain(net.LocalHostIP),
UdpEnabled: false,
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{
DestinationOverride: &freedom.DestinationOverride{
Server: &protocol.ServerEndpoint{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(dest.Port),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
noAuthDialer, err := xproxy.SOCKS5("tcp", net.TCPDestination(net.LocalHostIP, serverPort).NetAddr(), nil, xproxy.Direct)
common.Must(err)
conn, err := noAuthDialer.Dial("tcp", "google.com:80")
common.Must(err)
defer conn.Close()
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
}
func TestUDPConnection(t *testing.T) {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
clientPort := udp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_UDP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testUDPConn(clientPort, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
time.Sleep(20 * time.Second)
if err := testUDPConn(clientPort, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
func TestDomainSniffing(t *testing.T) {
sniffingPort := tcp.PickPort()
httpPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
Tag: "snif",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(sniffingPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
DomainOverride: []proxyman.KnownProtocols{
proxyman.KnownProtocols_TLS,
},
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: 443,
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
{
Tag: "http",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(httpPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&v2http.ServerConfig{}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "redir",
ProxySettings: serial.ToTypedMessage(&freedom.Config{
DestinationOverride: &freedom.DestinationOverride{
Server: &protocol.ServerEndpoint{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(sniffingPort),
},
},
}),
},
{
Tag: "direct",
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
App: []*anypb.Any{
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
TargetTag: &router.RoutingRule_Tag{
Tag: "direct",
},
InboundTag: []string{"snif"},
}, {
TargetTag: &router.RoutingRule_Tag{
Tag: "redir",
},
InboundTag: []string{"http"},
},
},
}),
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:" + httpPort.String())
},
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Get("https://www.github.com/")
common.Must(err)
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Error("unexpected status code: ", resp.StatusCode)
}
common.Must(resp.Write(io.Discard))
}
}
func TestDialV2Ray(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
},
Inbound: []*core.InboundHandlerConfig{},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
client, err := core.New(clientConfig)
common.Must(err)
conn, err := core.Dial(context.Background(), client, dest)
common.Must(err)
defer conn.Close()
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/policy_test.go | testing/scenarios/policy_test.go | package scenarios
import (
"io"
"testing"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/log"
"github.com/v2fly/v2ray-core/v5/app/policy"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
clog "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/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
)
func startQuickClosingTCPServer() (net.Listener, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
break
}
b := make([]byte, 1024)
conn.Read(b)
conn.Close()
}
}()
return listener, nil
}
func TestVMessClosing(t *testing.T) {
tcpServer, err := startQuickClosingTCPServer()
common.Must(err)
defer tcpServer.Close()
dest := net.DestinationFromAddr(tcpServer.Addr())
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&policy.Config{
Level: map[uint32]*policy.Policy{
0: {
Timeout: &policy.Policy_Timeout{
UplinkOnly: &policy.Second{Value: 0},
DownlinkOnly: &policy.Second{Value: 0},
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&policy.Config{
Level: map[uint32]*policy.Policy{
0: {
Timeout: &policy.Policy_Timeout{
UplinkOnly: &policy.Second{Value: 0},
DownlinkOnly: &policy.Second{Value: 0},
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*2)(); err != io.EOF {
t.Error(err)
}
}
func TestZeroBuffer(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&policy.Config{
Level: map[uint32]*policy.Policy{
0: {
Timeout: &policy.Policy_Timeout{
UplinkOnly: &policy.Second{Value: 0},
DownlinkOnly: &policy.Second{Value: 0},
},
Buffer: &policy.Policy_Buffer{
Connection: 0,
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*20))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/meek_test.go | testing/scenarios/meek_test.go | package scenarios
import (
"context"
"os"
"testing"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
_ "github.com/v2fly/v2ray-core/v5/main/distro/all"
)
func TestMeek(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
coreInst, InstMgrIfce := NewInstanceManagerCoreInstance()
defer coreInst.Close()
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"meek_client",
common.Must2(os.ReadFile("config/meek_client.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"meek_server",
common.Must2(os.ReadFile("config/meek_server.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "meek_server"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "meek_client"))
defer func() {
common.Must(InstMgrIfce.StopInstance(context.TODO(), "meek_server"))
common.Must(InstMgrIfce.StopInstance(context.TODO(), "meek_client"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "meek_server"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "meek_client"))
coreInst.Close()
}()
if err := testTCPConnViaSocks(17774, dest.Port, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/transport_test.go | testing/scenarios/transport_test.go | package scenarios
import (
"os"
"runtime"
"testing"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/log"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
clog "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/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/domainsocket"
"github.com/v2fly/v2ray-core/v5/transport/internet/headers/http"
"github.com/v2fly/v2ray-core/v5/transport/internet/headers/wechat"
"github.com/v2fly/v2ray-core/v5/transport/internet/quic"
tcptransport "github.com/v2fly/v2ray-core/v5/transport/internet/tcp"
)
func TestHTTPConnectionHeader(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_TCP,
Settings: serial.ToTypedMessage(&tcptransport.Config{
HeaderSettings: serial.ToTypedMessage(&http.Config{}),
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_TCP,
Settings: serial.ToTypedMessage(&tcptransport.Config{
HeaderSettings: serial.ToTypedMessage(&http.Config{}),
}),
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
func TestDomainSocket(t *testing.T) {
if runtime.GOOS == "windows" || runtime.GOOS == "android" {
t.Skip("Not supported on windows and android")
return
}
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
const dsPath = "/tmp/ds_scenario"
os.Remove(dsPath)
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_DomainSocket,
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_DomainSocket,
Settings: serial.ToTypedMessage(&domainsocket.Config{
Path: dsPath,
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_DomainSocket,
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_DomainSocket,
Settings: serial.ToTypedMessage(&domainsocket.Config{
Path: dsPath,
}),
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
func TestVMessQuic(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := udp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
ProtocolName: "quic",
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "quic",
Settings: serial.ToTypedMessage(&quic.Config{
Header: serial.ToTypedMessage(&wechat.VideoConfig{}),
Security: &protocol.SecurityConfig{
Type: protocol.SecurityType_NONE,
},
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
ProtocolName: "quic",
TransportSettings: []*internet.TransportConfig{
{
ProtocolName: "quic",
Settings: serial.ToTypedMessage(&quic.Config{
Header: serial.ToTypedMessage(&wechat.VideoConfig{}),
Security: &protocol.SecurityConfig{
Type: protocol.SecurityType_NONE,
},
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
if err != nil {
t.Fatal("Failed to initialize all servers: ", err.Error())
}
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*40))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/common_coverage.go | testing/scenarios/common_coverage.go | //go:build coverage
// +build coverage
package scenarios
import (
"bytes"
"os"
"os/exec"
"github.com/v2fly/v2ray-core/v5/common/uuid"
)
func BuildV2Ray() error {
genTestBinaryPath()
if _, err := os.Stat(testBinaryPath); err == nil {
return nil
}
cmd := exec.Command("go", "test", "-tags", "coverage coveragemain", "-coverpkg", "github.com/v2fly/v2ray-core/v5/...", "-c", "-o", testBinaryPath, GetSourcePath())
return cmd.Run()
}
func RunV2RayProtobuf(config []byte) *exec.Cmd {
genTestBinaryPath()
covDir := os.Getenv("V2RAY_COV")
os.MkdirAll(covDir, os.ModeDir)
randomID := uuid.New()
profile := randomID.String() + ".out"
proc := exec.Command(testBinaryPath, "run", "-format=pb", "-test.run", "TestRunMainForCoverage", "-test.coverprofile", profile, "-test.outputdir", covDir)
proc.Stdin = bytes.NewBuffer(config)
proc.Stderr = os.Stderr
proc.Stdout = os.Stdout
return proc
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/common_instanceMgr_test.go | testing/scenarios/common_instanceMgr_test.go | package scenarios
import "testing"
func TestInstanceMgrInit(t *testing.T) {
NewInstanceManagerCoreInstance()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/grpc_test.go | testing/scenarios/grpc_test.go | package scenarios
import (
"context"
"os"
"testing"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
_ "github.com/v2fly/v2ray-core/v5/main/distro/all"
)
func TestGRPCDefault(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
coreInst, InstMgrIfce := NewInstanceManagerCoreInstance()
defer coreInst.Close()
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"grpc_client",
common.Must2(os.ReadFile("config/grpc_client.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"grpc_server",
common.Must2(os.ReadFile("config/grpc_server.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "grpc_server"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "grpc_client"))
defer func() {
common.Must(InstMgrIfce.StopInstance(context.TODO(), "grpc_server"))
common.Must(InstMgrIfce.StopInstance(context.TODO(), "grpc_client"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "grpc_server"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "grpc_client"))
coreInst.Close()
}()
if err := testTCPConnViaSocks(17784, dest.Port, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
func TestGRPCWithServiceName(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
coreInst, InstMgrIfce := NewInstanceManagerCoreInstance()
defer coreInst.Close()
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"grpc_client",
common.Must2(os.ReadFile("config/grpc_servicename_client.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"grpc_server",
common.Must2(os.ReadFile("config/grpc_servicename_server.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "grpc_server"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "grpc_client"))
defer func() {
common.Must(InstMgrIfce.StopInstance(context.TODO(), "grpc_server"))
common.Must(InstMgrIfce.StopInstance(context.TODO(), "grpc_client"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "grpc_server"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "grpc_client"))
coreInst.Close()
}()
if err := testTCPConnViaSocks(17794, dest.Port, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/common_regular.go | testing/scenarios/common_regular.go | //go:build !coverage
// +build !coverage
package scenarios
import (
"bytes"
"fmt"
"os"
"os/exec"
)
func BuildV2Ray() error {
genTestBinaryPath()
if _, err := os.Stat(testBinaryPath); err == nil {
return nil
}
fmt.Printf("Building V2Ray into path (%s)\n", testBinaryPath)
cmd := exec.Command("go", "build", "-o="+testBinaryPath, GetSourcePath())
return cmd.Run()
}
func RunV2RayProtobuf(config []byte) *exec.Cmd {
genTestBinaryPath()
proc := exec.Command(testBinaryPath, "run", "-format=pb")
proc.Stdin = bytes.NewBuffer(config)
proc.Stderr = os.Stderr
proc.Stdout = os.Stdout
return proc
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/common_instanceMgr.go | testing/scenarios/common_instanceMgr.go | package scenarios
import (
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/instman"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/features/extension"
)
func NewInstanceManagerInstanceConfig() *core.Config {
config := &core.Config{}
config.App = append(config.App, serial.ToTypedMessage(&instman.Config{}))
return config
}
func NewInstanceManagerCoreInstance() (*core.Instance, extension.InstanceManagement) {
coreConfig := NewInstanceManagerInstanceConfig()
instance, err := core.New(coreConfig)
if err != nil {
panic(err)
}
common.Must(instance.Start())
instanceMgr := instance.GetFeature(extension.InstanceManagementType())
InstanceMgrIfce := instanceMgr.(extension.InstanceManagement)
return instance, InstanceMgrIfce
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/vmess_test.go | testing/scenarios/vmess_test.go | package scenarios
import (
"os"
"testing"
"time"
"github.com/golang/protobuf/ptypes/any"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/log"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
clog "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/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/internet/kcp"
)
func TestVMessDynamicPort(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
retry := 1
serverPort := tcp.PickPort()
for {
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
Detour: &inbound.DetourConfig{
To: "detour",
},
}),
},
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort + 100),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: &net.PortRange{
From: uint32(serverPort + 1),
To: uint32(serverPort + 99),
},
Listen: net.NewIPOrDomain(net.LocalHostIP),
AllocationStrategy: &proxyman.AllocationStrategy{
Type: proxyman.AllocationStrategy_Random,
Concurrency: &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
Value: 2,
},
Refresh: &proxyman.AllocationStrategy_AllocationStrategyRefresh{
Value: 5,
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{}),
Tag: "detour",
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
server, _ := InitializeServerConfig(serverConfig)
if server != nil && tcpConnAvailableAtPort(t, serverPort+100) {
defer CloseServer(server)
break
}
retry++
if retry > 5 {
t.Fatal("All attempts failed to start server")
}
serverPort = tcp.PickPort()
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
},
},
}
server, err := InitializeServerConfig(clientConfig)
common.Must(err)
defer CloseServer(server)
if !tcpConnAvailableAtPort(t, clientPort) {
t.Fail()
}
}
func tcpConnAvailableAtPort(t *testing.T, port net.Port) bool {
for i := 1; ; i++ {
if i > 10 {
t.Log("All attempts failed to test tcp conn")
return false
}
time.Sleep(time.Millisecond * 10)
if err := testTCPConn(port, 1024, time.Second*2)(); err != nil {
t.Log("err ", err)
} else {
t.Log("success with", i, "attempts")
break
}
}
return true
}
func TestVMessGCM(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
if err != nil {
t.Fatal("Failed to initialize all servers: ", err.Error())
}
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*40))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestVMessGCMReadv(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
const envName = "V2RAY_BUF_READV"
common.Must(os.Setenv(envName, "enable"))
defer os.Unsetenv(envName)
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
if err != nil {
t.Fatal("Failed to initialize all servers: ", err.Error())
}
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*40))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestVMessGCMUDP(t *testing.T) {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := udp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_UDP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testUDPConn(clientPort, 1024, time.Second*5))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestVMessChacha20(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_CHACHA20_POLY1305,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Second*20))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestVMessNone(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_NONE,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 1024*1024, time.Second*30))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestVMessKCP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := udp.PickPort()
serverConfig := &core.Config{
App: []*any.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 10; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Minute*2))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
func TestVMessKCPLarge(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := udp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_MKCP,
Settings: serial.ToTypedMessage(&kcp.Config{
ReadBuffer: &kcp.ReadBuffer{
Size: 512 * 1024,
},
WriteBuffer: &kcp.WriteBuffer{
Size: 512 * 1024,
},
UplinkCapacity: &kcp.UplinkCapacity{
Value: 20,
},
DownlinkCapacity: &kcp.DownlinkCapacity{
Value: 20,
},
}),
},
},
},
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
StreamSettings: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
TransportSettings: []*internet.TransportConfig{
{
Protocol: internet.TransportProtocol_MKCP,
Settings: serial.ToTypedMessage(&kcp.Config{
ReadBuffer: &kcp.ReadBuffer{
Size: 512 * 1024,
},
WriteBuffer: &kcp.WriteBuffer{
Size: 512 * 1024,
},
UplinkCapacity: &kcp.UplinkCapacity{
Value: 20,
},
DownlinkCapacity: &kcp.DownlinkCapacity{
Value: 20,
},
}),
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
var errg errgroup.Group
for i := 0; i < 2; i++ {
errg.Go(testTCPConn(clientPort, 10240*1024, time.Minute*5))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
defer func() {
<-time.After(5 * time.Second)
CloseAllServers(servers)
}()
}
func TestVMessGCMMux(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
MultiplexSettings: &proxyman.MultiplexingConfig{
Enabled: true,
Concurrency: 4,
},
}),
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
for range "abcd" {
var errg errgroup.Group
for i := 0; i < 16; i++ {
errg.Go(testTCPConn(clientPort, 10240, time.Second*20))
}
if err := errg.Wait(); err != nil {
t.Fatal(err)
}
time.Sleep(time.Second)
}
}
func TestVMessGCMMuxUDP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
udpServer := udp.Server{
MsgProcessor: xor,
}
udpDest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientUDPPort := udp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientUDPPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(udpDest.Address),
Port: uint32(udpDest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_UDP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
MultiplexSettings: &proxyman.MultiplexingConfig{
Enabled: true,
Concurrency: 4,
},
}),
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
for range "abcd" {
var errg errgroup.Group
for i := 0; i < 16; i++ {
errg.Go(testTCPConn(clientPort, 10240, time.Second*20))
errg.Go(testUDPConn(clientUDPPort, 1024, time.Second*10))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
time.Sleep(time.Second)
}
defer func() {
<-time.After(5 * time.Second)
CloseAllServers(servers)
}()
}
func TestVMessZero(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | true |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/dokodemo_test.go | testing/scenarios/dokodemo_test.go | package scenarios
import (
"testing"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/log"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
clog "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/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
)
func TestDokodemoTCP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := uint32(tcp.PickPort())
clientPortRange := uint32(5)
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: &net.PortRange{From: clientPort, To: clientPort + clientPortRange},
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
for port := clientPort; port <= clientPort+clientPortRange; port++ {
if err := testTCPConn(net.Port(port), 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
}
func TestDokodemoUDP(t *testing.T) {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
userID := protocol.NewID(uuid.New())
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := uint32(udp.PickPort())
clientPortRange := uint32(5)
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: &net.PortRange{From: clientPort, To: clientPort + clientPortRange},
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_UDP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for port := clientPort; port <= clientPort+clientPortRange; port++ {
errg.Go(testUDPConn(net.Port(port), 1024, time.Second*5))
}
if err := errg.Wait(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/socks_test.go | testing/scenarios/socks_test.go | package scenarios
import (
"testing"
"time"
xproxy "golang.org/x/net/proxy"
"google.golang.org/protobuf/types/known/anypb"
socks4 "h12.io/socks"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/app/router"
"github.com/v2fly/v2ray-core/v5/common"
"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/proxy/blackhole"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/socks"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
)
func TestSocksBridgeTCP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{
AuthType: socks.AuthType_PASSWORD,
Accounts: map[string]string{
"Test Account": "Test Password",
},
Address: net.NewIPOrDomain(net.LocalHostIP),
UdpEnabled: false,
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&socks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&socks.Account{
Username: "Test Account",
Password: "Test Password",
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testTCPConn(clientPort, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
func TestSocksBridageUDP(t *testing.T) {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{
AuthType: socks.AuthType_PASSWORD,
Accounts: map[string]string{
"Test Account": "Test Password",
},
Address: net.NewIPOrDomain(net.LocalHostIP),
UdpEnabled: true,
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP, net.Network_UDP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&socks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&socks.Account{
Username: "Test Account",
Password: "Test Password",
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testUDPConn(clientPort, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
func TestSocksBridageUDPWithRouting(t *testing.T) {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
TargetTag: &router.RoutingRule_Tag{
Tag: "out",
},
InboundTag: []string{"socks"},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
Tag: "socks",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{
AuthType: socks.AuthType_NO_AUTH,
Address: net.NewIPOrDomain(net.LocalHostIP),
UdpEnabled: true,
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
{
Tag: "out",
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP, net.Network_UDP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&socks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
if err := testUDPConn(clientPort, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
func TestSocksConformanceMod(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
authPort := tcp.PickPort()
noAuthPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(authPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{
AuthType: socks.AuthType_PASSWORD,
Accounts: map[string]string{
"Test Account": "Test Password",
},
Address: net.NewIPOrDomain(net.LocalHostIP),
UdpEnabled: false,
}),
},
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(noAuthPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{
AuthType: socks.AuthType_NO_AUTH,
Accounts: map[string]string{
"Test Account": "Test Password",
},
Address: net.NewIPOrDomain(net.LocalHostIP),
UdpEnabled: false,
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
noAuthDialer, err := xproxy.SOCKS5("tcp", net.TCPDestination(net.LocalHostIP, noAuthPort).NetAddr(), nil, xproxy.Direct)
common.Must(err)
conn, err := noAuthDialer.Dial("tcp", dest.NetAddr())
common.Must(err)
defer conn.Close()
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
{
authDialer, err := xproxy.SOCKS5("tcp", net.TCPDestination(net.LocalHostIP, authPort).NetAddr(), &xproxy.Auth{User: "Test Account", Password: "Test Password"}, xproxy.Direct)
common.Must(err)
conn, err := authDialer.Dial("tcp", dest.NetAddr())
common.Must(err)
defer conn.Close()
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
{
dialer := socks4.Dial("socks4://" + net.TCPDestination(net.LocalHostIP, noAuthPort).NetAddr())
conn, err := dialer("tcp", dest.NetAddr())
common.Must(err)
defer conn.Close()
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
{
dialer := socks4.Dial("socks4://" + net.TCPDestination(net.LocalHostIP, noAuthPort).NetAddr())
conn, err := dialer("tcp", net.TCPDestination(net.LocalHostIP, tcpServer.Port).NetAddr())
common.Must(err)
defer conn.Close()
if err := testTCPConn2(conn, 1024, time.Second*5)(); err != nil {
t.Error(err)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/http_test.go | testing/scenarios/http_test.go | package scenarios
import (
"bytes"
"context"
"crypto/rand"
"io"
"net/http"
"net/url"
"testing"
"time"
"github.com/google/go-cmp/cmp"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"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/serial"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
v2http "github.com/v2fly/v2ray-core/v5/proxy/http"
v2httptest "github.com/v2fly/v2ray-core/v5/testing/servers/http"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
)
func TestHttpConformance(t *testing.T) {
httpServerPort := tcp.PickPort()
httpServer := &v2httptest.Server{
Port: httpServerPort,
PathHandler: make(map[string]http.HandlerFunc),
}
_, err := httpServer.Start()
common.Must(err)
defer httpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&v2http.ServerConfig{}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:" + serverPort.String())
},
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Get("http://127.0.0.1:" + httpServerPort.String())
common.Must(err)
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatal("status: ", resp.StatusCode)
}
content, err := io.ReadAll(resp.Body)
common.Must(err)
if string(content) != "Home" {
t.Fatal("body: ", string(content))
}
}
}
func TestHttpError(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: func(msg []byte) []byte {
return []byte{}
},
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
time.AfterFunc(time.Second*2, func() {
tcpServer.ShouldClose = true
})
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&v2http.ServerConfig{}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:" + serverPort.String())
},
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Get("http://127.0.0.1:" + dest.Port.String())
common.Must(err)
defer resp.Body.Close()
if resp.StatusCode != 503 {
t.Error("status: ", resp.StatusCode)
}
}
}
func TestHTTPConnectMethod(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&v2http.ServerConfig{}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:" + serverPort.String())
},
}
client := &http.Client{
Transport: transport,
}
payload := make([]byte, 1024*64)
common.Must2(rand.Read(payload))
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, "Connect", "http://"+dest.NetAddr()+"/", bytes.NewReader(payload))
req.Header.Set("X-a", "b")
req.Header.Set("X-b", "d")
common.Must(err)
resp, err := client.Do(req)
common.Must(err)
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatal("status: ", resp.StatusCode)
}
content := make([]byte, len(payload))
common.Must2(io.ReadFull(resp.Body, content))
if r := cmp.Diff(content, xor(payload)); r != "" {
t.Fatal(r)
}
}
}
func TestHttpPost(t *testing.T) {
httpServerPort := tcp.PickPort()
httpServer := &v2httptest.Server{
Port: httpServerPort,
PathHandler: map[string]http.HandlerFunc{
"/testpost": func(w http.ResponseWriter, r *http.Request) {
payload, err := buf.ReadAllToBytes(r.Body)
r.Body.Close()
if err != nil {
w.WriteHeader(500)
w.Write([]byte("Unable to read all payload"))
return
}
payload = xor(payload)
w.Write(payload)
},
},
}
_, err := httpServer.Start()
common.Must(err)
defer httpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&v2http.ServerConfig{}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:" + serverPort.String())
},
}
client := &http.Client{
Transport: transport,
}
payload := make([]byte, 1024*64)
common.Must2(rand.Read(payload))
resp, err := client.Post("http://127.0.0.1:"+httpServerPort.String()+"/testpost", "application/x-www-form-urlencoded", bytes.NewReader(payload))
common.Must(err)
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatal("status: ", resp.StatusCode)
}
content, err := io.ReadAll(resp.Body)
common.Must(err)
if r := cmp.Diff(content, xor(payload)); r != "" {
t.Fatal(r)
}
}
}
func setProxyBasicAuth(req *http.Request, user, pass string) {
req.SetBasicAuth(user, pass)
req.Header.Set("Proxy-Authorization", req.Header.Get("Authorization"))
req.Header.Del("Authorization")
}
func TestHttpBasicAuth(t *testing.T) {
httpServerPort := tcp.PickPort()
httpServer := &v2httptest.Server{
Port: httpServerPort,
PathHandler: make(map[string]http.HandlerFunc),
}
_, err := httpServer.Start()
common.Must(err)
defer httpServer.Close()
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&v2http.ServerConfig{
Accounts: map[string]string{
"a": "b",
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig)
common.Must(err)
defer CloseAllServers(servers)
{
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:" + serverPort.String())
},
}
client := &http.Client{
Transport: transport,
}
{
resp, err := client.Get("http://127.0.0.1:" + httpServerPort.String())
common.Must(err)
defer resp.Body.Close()
if resp.StatusCode != 407 {
t.Fatal("status: ", resp.StatusCode)
}
}
{
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, "GET", "http://127.0.0.1:"+httpServerPort.String(), nil)
common.Must(err)
setProxyBasicAuth(req, "a", "c")
resp, err := client.Do(req)
common.Must(err)
defer resp.Body.Close()
if resp.StatusCode != 407 {
t.Fatal("status: ", resp.StatusCode)
}
}
{
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, "GET", "http://127.0.0.1:"+httpServerPort.String(), nil)
common.Must(err)
setProxyBasicAuth(req, "a", "b")
resp, err := client.Do(req)
common.Must(err)
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatal("status: ", resp.StatusCode)
}
content, err := io.ReadAll(resp.Body)
common.Must(err)
if string(content) != "Home" {
t.Fatal("body: ", string(content))
}
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/httpupgrade_test.go | testing/scenarios/httpupgrade_test.go | package scenarios
import (
"context"
"os"
"testing"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
_ "github.com/v2fly/v2ray-core/v5/main/distro/all"
)
func TestHTTPUpgrade(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
coreInst, InstMgrIfce := NewInstanceManagerCoreInstance()
defer coreInst.Close()
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"httpupgrade_client",
common.Must2(os.ReadFile("config/httpupgrade_client.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"httpupgrade_server",
common.Must2(os.ReadFile("config/httpupgrade_server.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "httpupgrade_client"))
defer func() {
common.Must(InstMgrIfce.StopInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.StopInstance(context.TODO(), "httpupgrade_client"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "httpupgrade_client"))
coreInst.Close()
}()
if err := testTCPConnViaSocks(17794, dest.Port, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
func TestHTTPUpgradeWithEarlyData(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
coreInst, InstMgrIfce := NewInstanceManagerCoreInstance()
defer coreInst.Close()
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"httpupgrade_client",
common.Must2(os.ReadFile("config/httpupgrade_earlydata_client.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"httpupgrade_server",
common.Must2(os.ReadFile("config/httpupgrade_earlydata_server.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "httpupgrade_client"))
defer func() {
common.Must(InstMgrIfce.StopInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.StopInstance(context.TODO(), "httpupgrade_client"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "httpupgrade_client"))
coreInst.Close()
}()
if err := testTCPConnViaSocks(17794, dest.Port, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
func TestHTTPUpgradeWithShortEarlyData(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
coreInst, InstMgrIfce := NewInstanceManagerCoreInstance()
defer coreInst.Close()
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"httpupgrade_client",
common.Must2(os.ReadFile("config/httpupgrade_earlydataShortEarlyData_client.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"httpupgrade_server",
common.Must2(os.ReadFile("config/httpupgrade_earlydataShortEarlyData_server.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "httpupgrade_client"))
defer func() {
common.Must(InstMgrIfce.StopInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.StopInstance(context.TODO(), "httpupgrade_client"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "httpupgrade_server"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "httpupgrade_client"))
coreInst.Close()
}()
if err := testTCPConnViaSocks(17794, dest.Port, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/mekya_test.go | testing/scenarios/mekya_test.go | package scenarios
import (
"context"
"os"
"testing"
"time"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
_ "github.com/v2fly/v2ray-core/v5/main/distro/all"
)
func TestMekya(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
coreInst, InstMgrIfce := NewInstanceManagerCoreInstance()
defer coreInst.Close()
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"mekya_client",
common.Must2(os.ReadFile("config/mekya_client.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.AddInstance(
context.TODO(),
"mekya_server",
common.Must2(os.ReadFile("config/mekya_server.json")).([]byte),
"jsonv5"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "mekya_server"))
common.Must(InstMgrIfce.StartInstance(context.TODO(), "mekya_client"))
defer func() {
common.Must(InstMgrIfce.StopInstance(context.TODO(), "mekya_server"))
common.Must(InstMgrIfce.StopInstance(context.TODO(), "mekya_client"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "mekya_server"))
common.Must(InstMgrIfce.UntrackInstance(context.TODO(), "mekya_client"))
coreInst.Close()
}()
if err := testTCPConnViaSocks(17774, dest.Port, 1024, time.Second*2)(); err != nil {
t.Error(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/shadowsocks_test.go | testing/scenarios/shadowsocks_test.go | package scenarios
import (
"testing"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/log"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
clog "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/serial"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/shadowsocks"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
)
func TestShadowsocksChaCha20Poly1305TCP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
account := serial.ToTypedMessage(&shadowsocks.Account{
Password: "shadowsocks-password",
CipherType: shadowsocks.CipherType_CHACHA20_POLY1305,
})
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&shadowsocks.ServerConfig{
User: &protocol.User{
Account: account,
Level: 1,
},
Network: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
Networks: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&shadowsocks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: account,
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errGroup errgroup.Group
for i := 0; i < 10; i++ {
errGroup.Go(testTCPConn(clientPort, 10240*1024, time.Second*20))
}
if err := errGroup.Wait(); err != nil {
t.Error(err)
}
}
func TestShadowsocksAES256GCMTCP(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
account := serial.ToTypedMessage(&shadowsocks.Account{
Password: "shadowsocks-password",
CipherType: shadowsocks.CipherType_AES_256_GCM,
})
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&shadowsocks.ServerConfig{
User: &protocol.User{
Account: account,
Level: 1,
},
Network: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
Networks: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&shadowsocks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: account,
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errGroup errgroup.Group
for i := 0; i < 10; i++ {
errGroup.Go(testTCPConn(clientPort, 10240*1024, time.Second*20))
}
if err := errGroup.Wait(); err != nil {
t.Error(err)
}
}
func TestShadowsocksAES128GCMUDP(t *testing.T) {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
account := serial.ToTypedMessage(&shadowsocks.Account{
Password: "shadowsocks-password",
CipherType: shadowsocks.CipherType_AES_128_GCM,
})
serverPort := udp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&shadowsocks.ServerConfig{
User: &protocol.User{
Account: account,
Level: 1,
},
Network: []net.Network{net.Network_UDP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := udp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
Networks: []net.Network{net.Network_UDP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&shadowsocks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: account,
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errGroup errgroup.Group
for i := 0; i < 10; i++ {
errGroup.Go(testUDPConn(clientPort, 1024, time.Second*5))
}
if err := errGroup.Wait(); err != nil {
t.Error(err)
}
}
func TestShadowsocksAES128GCMUDPMux(t *testing.T) {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
account := serial.ToTypedMessage(&shadowsocks.Account{
Password: "shadowsocks-password",
CipherType: shadowsocks.CipherType_AES_128_GCM,
})
serverPort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&shadowsocks.ServerConfig{
User: &protocol.User{
Account: account,
Level: 1,
},
Network: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := udp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
Networks: []net.Network{net.Network_UDP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
SenderSettings: serial.ToTypedMessage(&proxyman.SenderConfig{
MultiplexSettings: &proxyman.MultiplexingConfig{
Enabled: true,
Concurrency: 8,
},
}),
ProxySettings: serial.ToTypedMessage(&shadowsocks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: account,
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errGroup errgroup.Group
for i := 0; i < 10; i++ {
errGroup.Go(testUDPConn(clientPort, 1024, time.Second*5))
}
if err := errGroup.Wait(); err != nil {
t.Error(err)
}
}
func TestShadowsocksNone(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
account := serial.ToTypedMessage(&shadowsocks.Account{
Password: "shadowsocks-password",
CipherType: shadowsocks.CipherType_NONE,
})
serverPort := tcp.PickPort()
serverConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(serverPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&shadowsocks.ServerConfig{
User: &protocol.User{
Account: account,
Level: 1,
},
Network: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
Networks: []net.Network{net.Network_TCP},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&shadowsocks.ClientConfig{
Server: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(serverPort),
User: []*protocol.User{
{
Account: account,
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errGroup errgroup.Group
for i := 0; i < 10; i++ {
errGroup.Go(testTCPConn(clientPort, 10240*1024, time.Second*20))
}
if err := errGroup.Wait(); err != nil {
t.Fatal(err)
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/common.go | testing/scenarios/common.go | package scenarios
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"sync"
"syscall"
"time"
"golang.org/x/net/proxy"
"google.golang.org/protobuf/proto"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/dispatcher"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
"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/retry"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/units"
)
func xor(b []byte) []byte {
r := make([]byte, len(b))
for i, v := range b {
r[i] = v ^ 'c'
}
return r
}
func readFrom(conn net.Conn, timeout time.Duration, length int) []byte {
b := make([]byte, length)
deadline := time.Now().Add(timeout)
conn.SetReadDeadline(deadline)
n, err := io.ReadFull(conn, b[:length])
if err != nil {
fmt.Println("Unexpected error from readFrom:", err)
}
return b[:n]
}
func readFrom2(conn net.Conn, timeout time.Duration, length int) ([]byte, error) {
b := make([]byte, length)
deadline := time.Now().Add(timeout)
conn.SetReadDeadline(deadline)
n, err := io.ReadFull(conn, b[:length])
if err != nil {
return nil, err
}
return b[:n], nil
}
func InitializeServerConfigs(configs ...*core.Config) ([]*exec.Cmd, error) {
servers := make([]*exec.Cmd, 0, 10)
for _, config := range configs {
server, err := InitializeServerConfig(config)
if err != nil {
CloseAllServers(servers)
return nil, err
}
servers = append(servers, server)
}
time.Sleep(time.Second * 2)
return servers, nil
}
func InitializeServerConfig(config *core.Config) (*exec.Cmd, error) {
err := BuildV2Ray()
if err != nil {
return nil, err
}
config = withDefaultApps(config)
configBytes, err := proto.Marshal(config)
if err != nil {
return nil, err
}
proc := RunV2RayProtobuf(configBytes)
if err := proc.Start(); err != nil {
return nil, err
}
return proc, nil
}
var (
testBinaryPath string
testBinaryPathGen sync.Once
)
func genTestBinaryPath() {
testBinaryPathGen.Do(func() {
var tempDir string
common.Must(retry.Timed(5, 100).On(func() error {
dir, err := os.MkdirTemp("", "v2ray")
if err != nil {
return err
}
tempDir = dir
return nil
}))
file := filepath.Join(tempDir, "v2ray.test")
if runtime.GOOS == "windows" {
file += ".exe"
}
testBinaryPath = file
fmt.Printf("Generated binary path: %s\n", file)
})
}
func GetSourcePath() string {
return filepath.Join("github.com", "v2fly", "v2ray-core", "v5", "main")
}
func CloseAllServers(servers []*exec.Cmd) {
log.Record(&log.GeneralMessage{
Severity: log.Severity_Info,
Content: "Closing all servers.",
})
for _, server := range servers {
if runtime.GOOS == "windows" {
server.Process.Kill()
} else {
server.Process.Signal(syscall.SIGTERM)
}
}
for _, server := range servers {
server.Process.Wait()
}
log.Record(&log.GeneralMessage{
Severity: log.Severity_Info,
Content: "All server closed.",
})
}
func CloseServer(server *exec.Cmd) {
log.Record(&log.GeneralMessage{
Severity: log.Severity_Info,
Content: "Closing server.",
})
if runtime.GOOS == "windows" {
server.Process.Kill()
} else {
server.Process.Signal(syscall.SIGTERM)
}
server.Process.Wait()
log.Record(&log.GeneralMessage{
Severity: log.Severity_Info,
Content: "Server closed.",
})
}
func withDefaultApps(config *core.Config) *core.Config {
config.App = append(config.App, serial.ToTypedMessage(&dispatcher.Config{}))
config.App = append(config.App, serial.ToTypedMessage(&proxyman.InboundConfig{}))
config.App = append(config.App, serial.ToTypedMessage(&proxyman.OutboundConfig{}))
return config
}
func testTCPConnViaSocks(socksPort, testPort net.Port, payloadSize int, timeout time.Duration) func() error { //nolint: unparam
return func() error {
socksDialer, err := proxy.SOCKS5("tcp", "127.0.0.1:"+socksPort.String(), nil, nil)
if err != nil {
return err
}
destAddr := &net.TCPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(testPort),
}
conn, err := socksDialer.Dial("tcp", destAddr.String())
if err != nil {
return err
}
defer conn.Close()
return testTCPConn2(conn, payloadSize, timeout)()
}
}
func testTCPConn(port net.Port, payloadSize int, timeout time.Duration) func() error {
return func() error {
conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(port),
})
if err != nil {
return err
}
defer conn.Close()
return testTCPConn2(conn, payloadSize, timeout)()
}
}
func testUDPConn(port net.Port, payloadSize int, timeout time.Duration) func() error { // nolint: unparam
return func() error {
conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(port),
})
if err != nil {
return err
}
defer conn.Close()
return testTCPConn2(conn, payloadSize, timeout)()
}
}
func testTCPConn2(conn net.Conn, payloadSize int, timeout time.Duration) func() error {
return func() (err1 error) {
start := time.Now()
defer func() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
// For info on each, see: https://golang.org/pkg/runtime/#MemStats
fmt.Println("testConn finishes:", time.Since(start).Milliseconds(), "ms\t",
err1, "\tAlloc =", units.ByteSize(m.Alloc).String(),
"\tTotalAlloc =", units.ByteSize(m.TotalAlloc).String(),
"\tSys =", units.ByteSize(m.Sys).String(),
"\tNumGC =", m.NumGC)
}()
payload := make([]byte, payloadSize)
common.Must2(rand.Read(payload))
nBytes, err := conn.Write(payload)
if err != nil {
return err
}
if nBytes != len(payload) {
return errors.New("expect ", len(payload), " written, but actually ", nBytes)
}
response, err := readFrom2(conn, timeout, payloadSize)
if err != nil {
return err
}
_ = response
if r := bytes.Compare(response, xor(payload)); r != 0 {
return errors.New(r)
}
return nil
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/scenarios/reverse_test.go | testing/scenarios/reverse_test.go | package scenarios
import (
"testing"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/log"
"github.com/v2fly/v2ray-core/v5/app/policy"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/app/reverse"
"github.com/v2fly/v2ray-core/v5/app/router"
"github.com/v2fly/v2ray-core/v5/app/router/routercommon"
"github.com/v2fly/v2ray-core/v5/common"
clog "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/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/proxy/blackhole"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/inbound"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
)
func TestReverseProxy(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
externalPort := tcp.PickPort()
reversePort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&reverse.Config{
PortalConfig: []*reverse.PortalConfig{
{
Tag: "portal",
Domain: "test.v2fly.org",
},
},
}),
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
Domain: []*routercommon.Domain{
{Type: routercommon.Domain_Full, Value: "test.v2fly.org"},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "portal",
},
},
{
InboundTag: []string{"external"},
TargetTag: &router.RoutingRule_Tag{
Tag: "portal",
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
Tag: "external",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(externalPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(reversePort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&reverse.Config{
BridgeConfig: []*reverse.BridgeConfig{
{
Tag: "bridge",
Domain: "test.v2fly.org",
},
},
}),
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
Domain: []*routercommon.Domain{
{Type: routercommon.Domain_Full, Value: "test.v2fly.org"},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "reverse",
},
},
{
InboundTag: []string{"bridge"},
TargetTag: &router.RoutingRule_Tag{
Tag: "freedom",
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "freedom",
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
{
Tag: "reverse",
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(reversePort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
var errg errgroup.Group
for i := 0; i < 32; i++ {
errg.Go(testTCPConn(externalPort, 10240*1024, time.Second*40))
}
if err := errg.Wait(); err != nil {
t.Fatal(err)
}
}
func TestReverseProxyLongRunning(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
userID := protocol.NewID(uuid.New())
externalPort := tcp.PickPort()
reversePort := tcp.PickPort()
serverConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
serial.ToTypedMessage(&policy.Config{
Level: map[uint32]*policy.Policy{
0: {
Timeout: &policy.Policy_Timeout{
UplinkOnly: &policy.Second{Value: 0},
DownlinkOnly: &policy.Second{Value: 0},
},
},
},
}),
serial.ToTypedMessage(&reverse.Config{
PortalConfig: []*reverse.PortalConfig{
{
Tag: "portal",
Domain: "test.v2fly.org",
},
},
}),
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
Domain: []*routercommon.Domain{
{Type: routercommon.Domain_Full, Value: "test.v2fly.org"},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "portal",
},
},
{
InboundTag: []string{"external"},
TargetTag: &router.RoutingRule_Tag{
Tag: "portal",
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
Tag: "external",
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(externalPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(reversePort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&inbound.Config{
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
}),
},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&blackhole.Config{}),
},
},
}
clientPort := tcp.PickPort()
clientConfig := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&log.Config{
Error: &log.LogSpecification{Level: clog.Severity_Debug, Type: log.LogType_Console},
}),
serial.ToTypedMessage(&policy.Config{
Level: map[uint32]*policy.Policy{
0: {
Timeout: &policy.Policy_Timeout{
UplinkOnly: &policy.Second{Value: 0},
DownlinkOnly: &policy.Second{Value: 0},
},
},
},
}),
serial.ToTypedMessage(&reverse.Config{
BridgeConfig: []*reverse.BridgeConfig{
{
Tag: "bridge",
Domain: "test.v2fly.org",
},
},
}),
serial.ToTypedMessage(&router.Config{
Rule: []*router.RoutingRule{
{
Domain: []*routercommon.Domain{
{Type: routercommon.Domain_Full, Value: "test.v2fly.org"},
},
TargetTag: &router.RoutingRule_Tag{
Tag: "reverse",
},
},
{
InboundTag: []string{"bridge"},
TargetTag: &router.RoutingRule_Tag{
Tag: "freedom",
},
},
},
}),
},
Inbound: []*core.InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(clientPort),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(dest.Address),
Port: uint32(dest.Port),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP},
},
}),
},
},
Outbound: []*core.OutboundHandlerConfig{
{
Tag: "freedom",
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
{
Tag: "reverse",
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(reversePort),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
AlterId: 0,
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AES128_GCM,
},
}),
},
},
},
},
}),
},
},
}
servers, err := InitializeServerConfigs(serverConfig, clientConfig)
common.Must(err)
defer CloseAllServers(servers)
for i := 0; i < 4096; i++ {
if err := testTCPConn(externalPort, 1024, time.Second*20)(); err != nil {
t.Error(err)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/servers/tcp/tcp.go | testing/servers/tcp/tcp.go | package tcp
import (
"context"
"fmt"
"io"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/transport/internet"
"github.com/v2fly/v2ray-core/v5/transport/pipe"
)
type Server struct {
Port net.Port
MsgProcessor func(msg []byte) []byte
ShouldClose bool
SendFirst []byte
Listen net.Address
listener net.Listener
}
func (server *Server) Start() (net.Destination, error) {
return server.StartContext(context.Background(), nil)
}
func (server *Server) StartContext(ctx context.Context, sockopt *internet.SocketConfig) (net.Destination, error) {
listenerAddr := server.Listen
if listenerAddr == nil {
listenerAddr = net.LocalHostIP
}
listener, err := internet.ListenSystem(ctx, &net.TCPAddr{
IP: listenerAddr.IP(),
Port: int(server.Port),
}, sockopt)
if err != nil {
return net.Destination{}, err
}
localAddr := listener.Addr().(*net.TCPAddr)
server.Port = net.Port(localAddr.Port)
server.listener = listener
go server.acceptConnections(listener.(*net.TCPListener))
return net.TCPDestination(net.IPAddress(localAddr.IP), net.Port(localAddr.Port)), nil
}
func (server *Server) acceptConnections(listener *net.TCPListener) {
for {
conn, err := listener.Accept()
if err != nil {
fmt.Printf("Failed accept TCP connection: %v\n", err)
return
}
go server.handleConnection(conn)
}
}
func (server *Server) handleConnection(conn net.Conn) {
if len(server.SendFirst) > 0 {
conn.Write(server.SendFirst)
}
pReader, pWriter := pipe.New(pipe.WithoutSizeLimit())
err := task.Run(context.Background(), func() error {
defer pWriter.Close()
for {
b := buf.New()
if _, err := b.ReadFrom(conn); err != nil {
if err == io.EOF {
return nil
}
return err
}
copy(b.Bytes(), server.MsgProcessor(b.Bytes()))
if err := pWriter.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
return err
}
}
}, func() error {
defer pReader.Interrupt()
w := buf.NewWriter(conn)
for {
mb, err := pReader.ReadMultiBuffer()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
if err := w.WriteMultiBuffer(mb); err != nil {
return err
}
}
})
if err != nil {
fmt.Println("failed to transfer data: ", err.Error())
}
conn.Close()
}
func (server *Server) Close() error {
return server.listener.Close()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/servers/tcp/port.go | testing/servers/tcp/port.go | package tcp
import "github.com/v2fly/v2ray-core/v5/common/net"
// PickPort returns an unused TCP port of the system.
func PickPort() net.Port {
listener := pickPort()
defer listener.Close()
addr := listener.Addr().(*net.TCPAddr)
return net.Port(addr.Port)
}
func pickPort() net.Listener {
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
listener = pickPort()
}
return listener
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/servers/udp/port.go | testing/servers/udp/port.go | package udp
import "github.com/v2fly/v2ray-core/v5/common/net"
// PickPort returns an unused UDP port of the system.
func PickPort() net.Port {
conn := pickPort()
defer conn.Close()
addr := conn.LocalAddr().(*net.UDPAddr)
return net.Port(addr.Port)
}
func pickPort() *net.UDPConn {
conn, err := net.ListenUDP("udp4", &net.UDPAddr{
IP: net.LocalHostIP.IP(),
Port: 0,
})
if err != nil {
conn = pickPort()
}
return conn
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/servers/udp/udp.go | testing/servers/udp/udp.go | package udp
import (
"fmt"
"github.com/v2fly/v2ray-core/v5/common/net"
)
type Server struct {
Port net.Port
MsgProcessor func(msg []byte) []byte
accepting bool
conn *net.UDPConn
}
func (server *Server) Start() (net.Destination, error) {
conn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: []byte{127, 0, 0, 1},
Port: int(server.Port),
Zone: "",
})
if err != nil {
return net.Destination{}, err
}
server.Port = net.Port(conn.LocalAddr().(*net.UDPAddr).Port)
fmt.Println("UDP server started on port ", server.Port)
server.conn = conn
go server.handleConnection(conn)
localAddr := conn.LocalAddr().(*net.UDPAddr)
return net.UDPDestination(net.IPAddress(localAddr.IP), net.Port(localAddr.Port)), nil
}
func (server *Server) handleConnection(conn *net.UDPConn) {
server.accepting = true
for server.accepting {
buffer := make([]byte, 2*1024)
nBytes, addr, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Printf("Failed to read from UDP: %v\n", err)
continue
}
response := server.MsgProcessor(buffer[:nBytes])
if _, err := conn.WriteToUDP(response, addr); err != nil {
fmt.Println("Failed to write to UDP: ", err.Error())
}
}
}
func (server *Server) Close() error {
server.accepting = false
return server.conn.Close()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/testing/servers/http/http.go | testing/servers/http/http.go | package tcp
import (
"net/http"
"github.com/v2fly/v2ray-core/v5/common/net"
)
type Server struct {
Port net.Port
PathHandler map[string]http.HandlerFunc
server *http.Server
}
func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/" {
resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
resp.WriteHeader(http.StatusOK)
resp.Write([]byte("Home"))
return
}
handler, found := s.PathHandler[req.URL.Path]
if found {
handler(resp, req)
}
}
func (s *Server) Start() (net.Destination, error) {
s.server = &http.Server{
Addr: "127.0.0.1:" + s.Port.String(),
Handler: s,
}
go s.server.ListenAndServe()
return net.TCPDestination(net.LocalHostIP, s.Port), nil
}
func (s *Server) Close() error {
return s.server.Close()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/transport/config.go | transport/config.go | package transport
import (
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
// Apply applies this Config.
func (c *Config) Apply() error {
if c == nil {
return nil
}
return internet.ApplyGlobalTransportSettings(c.TransportSettings)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/transport/link.go | transport/link.go | package transport
import "github.com/v2fly/v2ray-core/v5/common/buf"
// Link is a utility for connecting between an inbound and an outbound proxy handler.
type Link struct {
Reader buf.Reader
Writer buf.Writer
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/transport/config.pb.go | transport/config.pb.go | package transport
import (
internet "github.com/v2fly/v2ray-core/v5/transport/internet"
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)
)
// Global transport settings. This affects all type of connections that go
// through V2Ray. Deprecated. Use each settings in StreamConfig.
//
// Deprecated: Marked as deprecated in transport/config.proto.
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
TransportSettings []*internet.TransportConfig `protobuf:"bytes,1,rep,name=transport_settings,json=transportSettings,proto3" json:"transport_settings,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_transport_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_transport_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_transport_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetTransportSettings() []*internet.TransportConfig {
if x != nil {
return x.TransportSettings
}
return nil
}
var File_transport_config_proto protoreflect.FileDescriptor
const file_transport_config_proto_rawDesc = "" +
"\n" +
"\x16transport/config.proto\x12\x14v2ray.core.transport\x1a\x1ftransport/internet/config.proto\"k\n" +
"\x06Config\x12]\n" +
"\x12transport_settings\x18\x01 \x03(\v2..v2ray.core.transport.internet.TransportConfigR\x11transportSettings:\x02\x18\x01B]\n" +
"\x18com.v2ray.core.transportP\x01Z(github.com/v2fly/v2ray-core/v5/transport\xaa\x02\x14V2Ray.Core.Transportb\x06proto3"
var (
file_transport_config_proto_rawDescOnce sync.Once
file_transport_config_proto_rawDescData []byte
)
func file_transport_config_proto_rawDescGZIP() []byte {
file_transport_config_proto_rawDescOnce.Do(func() {
file_transport_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_transport_config_proto_rawDesc), len(file_transport_config_proto_rawDesc)))
})
return file_transport_config_proto_rawDescData
}
var file_transport_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_transport_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.transport.Config
(*internet.TransportConfig)(nil), // 1: v2ray.core.transport.internet.TransportConfig
}
var file_transport_config_proto_depIdxs = []int32{
1, // 0: v2ray.core.transport.Config.transport_settings:type_name -> v2ray.core.transport.internet.TransportConfig
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_transport_config_proto_init() }
func file_transport_config_proto_init() {
if File_transport_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_config_proto_rawDesc), len(file_transport_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_transport_config_proto_goTypes,
DependencyIndexes: file_transport_config_proto_depIdxs,
MessageInfos: file_transport_config_proto_msgTypes,
}.Build()
File_transport_config_proto = out.File
file_transport_config_proto_goTypes = nil
file_transport_config_proto_depIdxs = nil
}
| 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.