V2Ray Core (Project V)
repository·master·Indexed 13 days ago
https://github.com/v2fly/v2ray-coreA powerful network toolset for building secure, private computer networks. V2Ray Core provides a modular framework for network protocols and connection security, featuring gRPC APIs for instance management via InstanceManagementService and log control via LoggerService.
What's inside V2Ray
- Project V (v2ray-core) is a suite of network tools designed to help users build custom computer networks. Its primary purpose is to secure network connections to protect user privacy. It is a highly modular core that can be used as a standalone tool or integrated into larger networking solutions.
Understand the AppEnvironmentCapabilitySet interface hierarchy
masterThe
AppEnvironmentCapabilitySetis a composite interface that defines the full breadth of environmental capabilities available to the application. It acts as a container for several specialized capability sets:BaseEnvironmentCapabilitySet: Core environment features.SystemNetworkCapabilitySet: Network capabilities at the system level.InstanceNetworkCapabilitySet: Network capabilities specific to the instance.FileSystemCapabilitySet: File system access and operations.PersistentStorageCapabilitySet: Access to non-volatile storage.TransientStorageCapabilitySet: Access to volatile/temporary storage.
Developers implementing or consuming environment logic should use this interface to ensure they have access to the required resource abstractions.
Understand HTTP/2 connection multiplexing in the HTTP client
masterThe HTTP client implements connection caching for HTTP/2. When a connection to a destination is established via HTTP/2 (
h2), theh2Conn(containing the raw connection and thehttp2.ClientConn) is stored in a globalcachedH2Connsmap.Subsequent requests to the same destination can reuse the existing
http2.ClientConnto perform newRoundTripoperations, effectively multiplexing multiple proxy tunnels over a single underlying TCP/TLS connection. This is managed viacachedH2Mutexto ensure thread safety.Implement Hysteria2 as a proxy client
masterThe
hysteria2.Clienttype implements theOutboundHandlerinterface, allowing V2Ray to use Hysteria2 as an outbound proxy. It supports multiple servers via a round-robin selection mechanism and handles both TCP and UDP traffic.To use this in a V2Ray configuration, you must provide a
ClientConfigcontaining a list of servers. The client automatically manages connection retries with exponential backoff and applies session policies (like idle timeouts) based on the user level defined in the server specification.// Note: This is a conceptual usage of the Client type within the V2Ray framework. // In practice, this is configured via the V2Ray JSON/Protobuf configuration. // The Client is instantiated by the core using NewClient(ctx, config). // The Client struct is used by the core to process outbound connections: // func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) errorUnderstand V2Ray API stability annotations
masterV2Ray uses
Annotationmetadata within code comments to signal the stability and intended usage of functions and types. These annotations always begin with the prefixv2ray:.If a type or function lacks an API annotation, it is considered internal and should not be used by external libraries or consumers.
Available API stability levels:
v2ray:api:stable: Guaranteed backward compatibility.v2ray:api:beta: Ready for use, but subject to future changes.v2ray:api:deprecated: Should no longer be used.
Note: The
Annotationstruct itself is a documentation-only concept and is not used in the runtime logic of the project.How UDP connection state is managed in Shadowsocks 2022
masterShadowsocks 2022 uses a
ClientUDPConnStateto manage and reuse UDP sessions. This state is stored in theProxyEnvironment's transient storage under the keyUDPConnectionState(constant value:"UDPConnectionState").When a new UDP connection is needed,
GetOrCreateSessionis used to ensure that a session is initialized exactly once using async.Oncemechanism. This allows multiple concurrent UDP requests to share the same underlying transport session where appropriate.Understand the Command structure in v2ray-core
masterThe
Commandstruct is the fundamental building block for implementing CLI commands (e.g.,v2ray run,v2ray version). Each command defines its execution logic, usage documentation, and specific flags.Key components of a
Commandinclude:Run: A function that executes the command logic. It receives theCommandinstance and the remaining arguments (args) after the command name.UsageLine: A template-supported string defining how to call the command (e.g.,usage: {{.Exec}} run [options]).ShortandLong: Descriptions used for help output.Longsupports Go template syntax.Flag: Aflag.FlagSetcontaining flags specific to that command.Commands: A list of sub-commands associated with this command.
A command is considered
Runnableif itsRunfield is not nil. IfRunis nil, the command is treated as a documentation pseudo-command.type Command struct { Run func(cmd *Command, args []string) UsageLine string Short string Long string Flag flag.FlagSet CustomFlags bool Commands []*Command }Configure V2Ray via environment variables
masterV2Ray can be configured using environment variables to define configuration locations without passing CLI flags:
v2ray.location.confdir: Specifies a directory containing configuration files to be loaded.v2ray.location.config: Specifies a specific path to a configuration file.
Note: If both CLI flags and environment variables are used, the CLI flags take precedence in determining which files are loaded.
Configure HTTP/1.1 skip-wait-for-reply behavior
masterIn the
ClientConfig, theH1SkipWaitForReplyboolean option controls how the client handles the initial payload when using HTTP/1.1.- If
false(default): The client waits for a specific timeout (proxy.FirstPayloadTimeout) to see if the inbound link has data. If data is present, it is sent immediately after the CONNECT request. - If
true: The client increases the wait time to 1 second. This is useful for certain servers that require the first write to be present in the client hello or when the server expects to initiate communication first.
- If
Configure the Observatory service
masterThe Observatory service is registered as a gRPC service within the V2Ray configuration. In the configuration schema, it is identified by the short name
observatory.message Config { option (v2ray.core.common.protoext.message_opt).type = "grpcservice"; option (v2ray.core.common.protoext.message_opt).short_name = "observatory"; }Configure the HTTP Server via ServerConfig
masterThe
Serverstruct is initialized using aServerConfig. While the full definition ofServerConfigis in a separate file, thehttp.Serverimplementation utilizes the following fields:UserLevel: Defines the privilege level for the inbound session.Timeout: If greater than 0 andUserLevelis 0, sets theConnectionIdletimeout.Accounts: A list of valid credentials forProxy-Authorization(Basic Auth). If provided, the server enforces authentication.AllowTransparent: Iffalse, the server rejects requests with an emptyURL.Host(enforcing RFC 2068).policy.Managerintegration: The server uses the configured policy to manageTimeouts(Handshake, ConnectionIdle, DownlinkOnly, UplinkOnly) andBuffersettings.
Configure SOCKS client via ClientConfig
masterThe
ClientConfig(implied by theNewClientsignature andinitregistration) is used to define the behavior of the SOCKS client. Based on the implementation, it includes:Server: A list of server specifications used to populate theServerList.Version: The SOCKS protocol version (e.g.,Version_SOCKS4,Version_SOCKS4A,Version_SOCKS5).DelayAuthWrite: A boolean flag used during the SOCKS5 handshake.
Registration is handled automatically via
common.RegisterConfigin theinit()function, allowing it to be instantiated from a V2Ray configuration file.