V2Ray Core (Project V)

repository·master·Indexed 13 days ago

https://github.com/v2fly/v2ray-core

A 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.

Tokens
32.1K
Snippets
123
Records
158
Agent score
99%

What's inside V2Ray

  1. Overview of Project V (v2ray-core)

    master
    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.
  2. Understand the AppEnvironmentCapabilitySet interface hierarchy

    master

    The AppEnvironmentCapabilitySet is 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.

  3. Understand HTTP/2 connection multiplexing in the HTTP client

    master

    The HTTP client implements connection caching for HTTP/2. When a connection to a destination is established via HTTP/2 (h2), the h2Conn (containing the raw connection and the http2.ClientConn) is stored in a global cachedH2Conns map.

    Subsequent requests to the same destination can reuse the existing http2.ClientConn to perform new RoundTrip operations, effectively multiplexing multiple proxy tunnels over a single underlying TCP/TLS connection. This is managed via cachedH2Mutex to ensure thread safety.

  4. Implement Hysteria2 as a proxy client

    master

    The hysteria2.Client type implements the OutboundHandler interface, 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 ClientConfig containing 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) error
  5. Understand V2Ray API stability annotations

    master

    V2Ray uses Annotation metadata within code comments to signal the stability and intended usage of functions and types. These annotations always begin with the prefix v2ray:.

    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 Annotation struct itself is a documentation-only concept and is not used in the runtime logic of the project.

  6. How UDP connection state is managed in Shadowsocks 2022

    master

    Shadowsocks 2022 uses a ClientUDPConnState to manage and reuse UDP sessions. This state is stored in the ProxyEnvironment's transient storage under the key UDPConnectionState (constant value: "UDPConnectionState").

    When a new UDP connection is needed, GetOrCreateSession is used to ensure that a session is initialized exactly once using a sync.Once mechanism. This allows multiple concurrent UDP requests to share the same underlying transport session where appropriate.

  7. Understand the Command structure in v2ray-core

    master

    The Command struct 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 Command include:

    • Run: A function that executes the command logic. It receives the Command instance 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]).
    • Short and Long: Descriptions used for help output. Long supports Go template syntax.
    • Flag: A flag.FlagSet containing flags specific to that command.
    • Commands: A list of sub-commands associated with this command.

    A command is considered Runnable if its Run field is not nil. If Run is 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
    }
  8. Configure V2Ray via environment variables

    master

    V2Ray 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.

  9. Configure HTTP/1.1 skip-wait-for-reply behavior

    master

    In the ClientConfig, the H1SkipWaitForReply boolean 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.
  10. Configure the Observatory service

    master

    The 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";
    }
  11. Configure the HTTP Server via ServerConfig

    master

    The Server struct is initialized using a ServerConfig. While the full definition of ServerConfig is in a separate file, the http.Server implementation utilizes the following fields:

    • UserLevel: Defines the privilege level for the inbound session.
    • Timeout: If greater than 0 and UserLevel is 0, sets the ConnectionIdle timeout.
    • Accounts: A list of valid credentials for Proxy-Authorization (Basic Auth). If provided, the server enforces authentication.
    • AllowTransparent: If false, the server rejects requests with an empty URL.Host (enforcing RFC 2068).
    • policy.Manager integration: The server uses the configured policy to manage Timeouts (Handshake, ConnectionIdle, DownlinkOnly, UplinkOnly) and Buffer settings.
  12. Configure SOCKS client via ClientConfig

    master

    The ClientConfig (implied by the NewClient signature and init registration) 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 the ServerList.
    • 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.RegisterConfig in the init() function, allowing it to be instantiated from a V2Ray configuration file.