V2Ray Core

repository·master·Indexed 13 days ago

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

A set of network tools for building custom computer networks, securing connections, and protecting privacy. It includes a DNS server with domain matching and GeoIP filtering, a gRPC-based LoggerService for remote log management, and a HandlerServiceClient for dynamically managing proxy inbounds and outbounds at runtime.

Tokens
17.4K
Snippets
69
Records
83
Agent score
99%

What's inside V2Ray

  1. Structure of the V2Ray Config object

    master

    The Config struct is the master configuration for V2Ray. It defines how the core handles incoming connections, outgoing connections, application-specific features, and extensions.

    Key components:

    • Inbound: A list of InboundHandlerConfig objects. V2Ray requires at least one inbound handler.
    • Outbound: A list of OutboundHandlerConfig objects. The first item in this list is used as the default for routing.
    • App: A list of serial.TypedMessage objects used for configuring V2Ray features. Each feature must implement the Feature interface and be registered via common.RegisterConfig.
    • Extension: A list of serial.TypedMessage objects for extensions. If an extension is not loaded into V2Ray, the corresponding configuration is ignored during initialization.
    • Transport: (Deprecated) Global transport settings. Use individual inbound/outbound transport configurations instead.
    type Config struct {
    	Inbound []*InboundHandlerConfig
    	Outbound []*OutboundHandlerConfig
    	App []*serial.TypedMessage
    	Extension []*serial.TypedMessage
    	Transport *transport.Config // Deprecated
    }
  2. Understand the RoutingContext data structure

    master

    The RoutingContext message contains the metadata associated with a routing process. It is used by both the SubscribeRoutingStats stream and the TestRoute request to describe the properties of a connection.

    Fields:

    • InboundTag (string): The tag of the inbound connection.
    • Network (v2ray.core.common.net.Network): The network type.
    • SourceIPs (repeated bytes): The source IP addresses.
    • TargetIPs (repeated bytes): The target IP addresses.
    • SourcePort (uint32): The source port.
    • TargetPort (uint32): The target port.
    • TargetDomain (string): The destination domain.
    • Protocol (string): The connection protocol.
    • User (string): The user identifier (e.g., email).
    • Attributes (map<string, string>): Additional connection attributes.
    • OutboundGroupTags (repeated string): Tags for the outbound groups.
    • OutboundTag (string): The specific outbound tag selected by the router.
  3. Understand V2Ray API stability annotations

    master

    V2Ray uses a documentation-only concept called Annotation to signal the stability and intended usage of exported types and functions. These annotations are embedded in code comments starting with v2ray:.

    When consuming the V2Ray core, you should check for these metadata tags to determine if a symbol is safe for external use:

    • v2ray:api:stable: Use these types or functions; they provide a guarantee of backward compatibility.
    • v2ray:api:beta: These are ready for use, but their implementation or signature may change in future versions.
    • v2ray:api:deprecated: These should no longer be used as they are slated for removal.
    • No annotation: If a type or function lacks an API annotation, it is considered internal and should not be used in external libraries.
  4. How DNS domain matching and GeoIP filtering work

    master

    The DNS Server uses two primary mechanisms to decide which name server to use for a specific query:

    1. Domain Matching: If PrioritizedDomain rules are configured for a name server, the server uses a domainMatcher (an IndexMatcher) to find which name server's rules match the queried domain. This allows routing specific domains (e.g., via regex or subdomains) to specific DNS providers.
    2. GeoIP Filtering: If Geoip rules are configured, the server uses a MultiGeoIPMatcher. After a name server returns IP addresses, the server checks if those IPs match the configured GeoIP rules. If the returned IPs do not match the expected GeoIP criteria, they are filtered out (returning errExpectedIPNonMatch).
  5. Configure ClientStrategy for worker limits

    master

    The ClientStrategy struct defines the capacity limits for a ClientWorker to prevent resource exhaustion.

    • MaxConcurrency: The maximum number of concurrent active sessions allowed in a single worker. If this limit is reached, IsFull() returns true.
    • MaxConnection: The maximum number of total connections allowed for the worker. If this limit is reached, IsClosing() returns true.
    strategy := mux.ClientStrategy{
    	MaxConcurrency: 100,
    	MaxConnection:  10,
    }
  6. Retrieve an Instance from a context using MustFromContext

    master

    Use MustFromContext when you require a core.Instance to be present in the context and want the program to panic if it is missing. This is useful in scenarios where the absence of an instance indicates a fundamental logic error or an unrecoverable state.

    // This will panic if the instance is not in the context
    instance := core.MustFromContext(ctx)
  7. Create workers using ClientWorkerFactory

    master

    The ClientWorkerFactory interface is used by pickers to generate new ClientWorker instances.

    A common implementation is DialingWorkerFactory, which creates a worker that establishes a connection through a specific proxy.Outbound and internet.Dialer using a defined ClientStrategy.

    factory := &mux.DialingWorkerFactory{
    	Proxy:    outbound,
    	Dialer:   dialer,
    	Strategy: strategy,
    }
  8. Manage Inbounds via Add, Remove, and Alter requests

    master

    The proxy system allows dynamic management of inbound connections using the following request types:

    • AddInboundRequest: Creates a new inbound handler. Requires an Inbound field containing a *core.InboundHandlerConfig.
    • RemoveInboundRequest: Removes an existing inbound handler identified by its Tag string.
    • AlterInboundRequest: Modifies an existing inbound handler. Requires the Tag of the inbound to alter and an Operation field of type *serial.TypedMessage which contains the specific changes to apply.
    type AddInboundRequest struct {
    	Inbound *core.InboundHandlerConfig `json:"inbound,omitempty"`
    }
    
    type RemoveInboundRequest struct {
    	Tag string `json:"tag,omitempty"`
    }
    
    type AlterInboundRequest struct {
    	Tag       string               `json:"tag,omitempty"`
    	Operation *serial.TypedMessage `json:"operation,omitempty"`
    }
  9. Retrieve system statistics with GetSysStats

    master

    Use the GetSysStats method to retrieve internal system and runtime statistics (e.g., memory usage, goroutines, uptime).

    Response Fields (SysStatsResponse):

    • NumGoroutine (uint32): Number of running goroutines.
    • NumGC (uint32): Number of completed GC cycles.
    • Alloc (uint64): Bytes allocated and still in use.
    • TotalAlloc (uint64): Total bytes allocated.
    • Sys (uint64): Total bytes obtained from the OS.
    • Mallocs (uint64): Total number of Mallocs.
    • Frees (uint64): Total number of Frees.
    • LiveObjects (uint64): Number of live objects.
    • PauseTotalNs (uint64): Total time spent in GC pause (nanoseconds).
    • Uptime (uint32): System uptime in seconds.
    // Conceptual usage of SysStatsRequest
    request := &command.SysStatsRequest{}
  10. Manage multiplexing clients with ClientManager

    master

    The ClientManager is the high-level entry point for dispatching network links through a multiplexing (mux) layer. It uses a WorkerPicker to select an available ClientWorker to handle the connection. If a worker is found, the link is dispatched; otherwise, it returns an error after attempting to find a worker up to 16 times.

    To use it, you must provide a WorkerPicker implementation (such as IncrementalWorkerPicker) and set the Enabled flag based on your configuration.

    manager := &mux.ClientManager{
    	Enabled: true,
    	Picker:  yourWorkerPicker,
    }
    
    err := manager.Dispatch(ctx, link)
  11. Use the DNS Client interface for IP lookups

    master

    The dns.Client interface is the primary stable API for querying DNS information in V2Ray. It allows you to resolve a domain name into a slice of net.IP addresses, which may include both IPv4 and IPv6 addresses. Implementations of this interface must also satisfy the features.Feature interface.

    // Example usage of the Client interface
    func resolve(client dns.Client, domain string) ([]net.IP, error) {
        ips, err := client.LookupIP(domain)
        if err != nil {
            return nil, err
        }
        return ips, nil
    }