Introducing a new way to review your PRs.

Read the announcement

2dust / v2rayn

A GUI client for Windows, Linux and macOS, support Xray and sing-box and others

View on GitHub

13 documents · Updated Nov 16, 2026

docs / service-lib-core-config-generation

ServiceLib core config generation

Overview

This area turns the application's selected ProfileItem plus global Config settings into the runtime config file consumed by Xray/v2ray-style cores, sing-box, or Mihomo/Clash. The orchestration entry point is v2rayN/…/CoreConfigHandler.cs: GenerateClientConfig copies non-Clash custom config files directly, sends Mihomo custom profiles through CoreConfigClashService, sends sing-box runs through CoreConfigSingboxService, and otherwise uses CoreConfigV2rayService. Speed-test config generation in the same file builds temporary mixed inbounds and per-node outbounds for either sing-box or Xray.

The shared build state is assembled by v2rayN/…/CoreConfigContextBuilder.cs into CoreConfigContext (v2rayN/…/CoreConfigContext.cs). The context captures the selected node, actual run core, app settings, default routing and DNS records, full-config template, TUN state, OS flags, IPv6 availability, all resolved proxy nodes, custom outbound file contents, and domain/core lists that must be protected from proxy loops. The builder normalizes all non-sing-box cores to the Xray config family for templates and DNS settings, resolves subscription prev/next profiles into virtual ProxyChain nodes, walks policy groups and proxy chains into AllProxiesMap, resolves routing-rule outbounds by remarks into remark:<outboundTag> entries, filters invalid TUN route exclusions, and drops invalid SendThrough or BindInterface values before generation.

Node validation is centralized in v2rayN/…/NodeValidator.cs. It rejects unsupported core/protocol/transport combinations, missing address/port/password fields, invalid TLS certificate PEM and REALITY public keys, malformed XHTTP extra JSON, and malformed Finalmask JSON. Sing-box validation is stricter for transports: kcp and xhttp are rejected, non-raw transports are limited to VMess/VLESS/Trojan/Shadowsocks, and Shadowsocks only allows raw or ws. Warnings are returned for combinations such as XTLS with mux, insecure TLS, and WebSocket with h2/h3 ALPN.

Xray/v2ray-family generation

v2rayN/…/CoreConfigV2rayService.cs starts from the embedded Global.V2raySampleClient, then applies log, inbound, outbound, routing, DNS, statistics, fragmentation, final routing, bind/send-through, custom outbound replacement, and full-config-template merging. Its target object graph is defined in v2rayN/…/V2rayConfig.cs.

v2rayN/…/V2rayInboundService.cs builds local mixed SOCKS/HTTP inbounds from Config.Inbound, including a second local port and optional LAN port with password auth. In TUN mode it adds the embedded Xray TUN inbound, chooses a macOS utun* or xray_tun name, sets MTU and gateway addresses, computes IPv4/IPv6 routing tables from route exclusions, copies sniffing with routeOnly=true, and enables Windows WFP leak blocking or Linux DNS-to-gateway behavior when configured.

v2rayN/…/V2rayOutboundService.cs builds one or many proxy outbounds from Global.V2raySampleOutbound. Single profiles fill protocol-specific settings for VMess, VLESS, Trojan, Shadowsocks, SOCKS, HTTP, Hysteria2, MASQUE, and WireGuard, then fill transport and TLS/REALITY settings. Xray-specific transports include raw HTTP headers, kcp with finalmask masks, ws/httpupgrade, xhttp including downloadSettings, grpc, xdrive, Hysteria2 finalmask obfuscation/hop/realm settings, and MASQUE warp/header settings. Policy groups expand into multiple tagged outbounds; proxy chains reverse the user order and connect hops through streamSettings.sockopt.dialerProxy, also propagating dialer settings into xhttp download settings. If a group expands to more than one proxy, v2rayN/…/V2rayBalancerService.cs adds Xray balancers and observatory or burstObservatory entries according to the nearest policy group's multiple-load mode. TUN mode also adds a dns outbound.

v2rayN/…/V2rayRoutingService.cs loads embedded TUN rules when needed, protects v2rayN and selected core executables from being captured by the tunnel, translates enabled user routing rules into Xray field rules, lazily adds additional routing-rule outbounds by resolving their remarks from CoreConfigContext.AllProxiesMap, and appends a final proxy or balancer rule. Domain, IP, and process matches are split into separate Xray rules so each match family can omit unrelated fields. v2rayN/…/V2rayDnsService.cs either uses raw DNS JSON from DNSItem or builds DNS from SimpleDNSItem: it creates direct/remote/bootstrap server lists, adds protected domains for proxy server names and ECH/xhttp download hosts, supports hosts entries and system hosts, optional FakeDNS IPv4/IPv6, direct-DNS routing tags, expected IP handling, DNS-tag routing, and strategy propagation to freedom/proxy/dial-proxy outbounds.

v2rayN/…/V2rayConfigTemplateService.cs performs final mutation. It applies bind interface and send-through only to non-loopback proxy outbounds without an upstream dialer, replaces custom outbound placeholder objects with the JSON read by CoreConfigContextBuilder, supports {{tag}}, {{detour}}, and {{interface}}, and then merges the generated outbounds into the optional full config template. Template merging appends generated balancers/observatories, can drop direct/block/dns/freedom outbounds when AddProxyOnly is set, and can force a template ProxyDetour onto generated non-private proxy outbounds.

sing-box generation

v2rayN/…/CoreConfigSingboxService.cs starts from Global.SingboxSampleClient, then applies log, inbounds, outbounds/endpoints, routing, DNS, experimental settings, geosite/geoip-to-rule-set conversion, bind/send-through, custom outbound replacement, and full-config-template merging. Its target object graph is defined in v2rayN/…/SingboxConfig.cs.

v2rayN/…/SingboxInboundService.cs creates a local mixed inbound plus optional second/LAN ports, and adds a sing-box TUN inbound from the embedded Global.TunSingboxInboundFileName when TUN is enabled. TUN settings include interface name, MTU, auto-route, strict-route, stack, DNS mode, IPv4/IPv6 addresses, and route exclusions; unlike the Xray path, route exclusion calculation is left to sing-box via route_exclude_address.

v2rayN/…/SingboxOutboundService.cs emits both outbounds and endpoints. WireGuard and MASQUE become sing-box endpoints; other supported profile types become outbounds. It fills VMess/VLESS/Trojan/Shadowsocks/SOCKS/HTTP/Hysteria2/TUIC/Anytls/Naive fields, TLS/REALITY/ECH, mux, Shadowsocks plugin settings, Hysteria2 hop/realm fields, and raw/ws/httpupgrade/grpc transports. Policy groups expand to child outbounds and, when multiple child tags exist, prepend a selector and urltest pair tagged at the base proxy tag. Proxy chains connect hops through sing-box detour. Custom outbound profiles can choose endpoint replacement via IsSingboxEndpoint.

v2rayN/…/SingboxRoutingService.cs sets route final to proxy, configures default_domain_resolver, adds TUN rules and loop-protection reject rules for the TUN interface's own addresses, protects selected core executables from the tunnel, handles ICMP routing policy, adds sniff/hijack-dns/route-options rules, injects host-resolution rules, adds Clash mode shortcuts, and translates application routing rules into sing-box route rules. It maps v2ray domain prefixes to sing-box fields, maps geo entries to geosite/geoip fields for later rule-set conversion, maps negative IP matches into logical rules, and converts process paths/names with platform-specific handling. v2rayN/…/SingboxDnsService.cs either uses raw sing-box DNS JSON or builds bootstrap/direct/remote/hosts/fakeip servers and DNS rules from SimpleDNSItem plus routing rules. It supports preferred hosts DNS, protected domains through direct DNS, Clash global/direct DNS behavior, predefined answers and rcode overrides from hosts entries, HTTPS/H3/DHCP/local DNS parsing, fake-ip filters, blocked HTTPS/SVCB and AAAA queries, direct expected IP races, parallel or serial DNS rule evaluation, and minimized DNS for speed tests.

v2rayN/…/SingboxRulesetService.cs converts generated geosite and geoip route/DNS matches into sing-box rule_set names, loads custom ruleset definitions from RoutingItem.CustomRulesetPath4Singbox, prefers local .srs files under the srss bin path, and otherwise declares remote binary rulesets downloaded through a generated HTTP client detoured via proxy. v2rayN/…/SingboxConfigTemplateService.cs replaces custom outbounds/endpoints using the same {{tag}}, {{detour}}, and {{interface}} placeholders as Xray, then merges generated outbounds and endpoints into a full config template. Sing-box bind/send-through maps to bind_interface and inet4_bind_address on direct network outbounds.

Clash/Mihomo custom configuration

v2rayN/…/CoreConfigClashService.cs is only used for custom Mihomo profiles. It reads YAML from the profile's address, resolves config-relative paths, preprocesses anchors, then forces runtime-owned settings: mixed-port, log-level, external-controller, allow-lan/bind-address, ipv6, and default mode. If the launch context has TUN enabled it merges the embedded Clash TUN YAML. Optional mixin content from Global.ClashMixinConfigFileName can replace keys or prepend/append/remove sequence entries with prepend-, append-, and removed- prefixes, skipping tun mixins when TUN is not active.

Coupling

  • If a new profile protocol or transport is added, update v2rayN/…/NodeValidator.cs, the outbound builder for each supported family (V2rayOutboundService.cs and/or SingboxOutboundService.cs), and the corresponding model classes in v2rayN/ServiceLib/Models/CoreConfigs/. The services serialize strongly typed objects; an unsupported field silently disappears from the generated JSON.
  • If routing rule fields or outbound-tag semantics change, verify both v2rayN/…/CoreConfigContextBuilder.cs and the family routing services. The builder resolves non-standard routing OutboundTag values by profile remarks into remark:<tag> entries, while V2rayRoutingService.cs and SingboxRoutingService.cs independently decide whether to materialize extra outbounds or fall back to proxy.
  • If TUN behavior changes, check the context builder and both inbound/routing implementations. CoreConfigContextBuilder.BuildAll may create a pre-SOCKS sing-box context and disables TUN on the main context, while V2rayInboundService.cs, SingboxInboundService.cs, V2rayRoutingService.cs, and SingboxRoutingService.cs each add different TUN inbounds, route exclusions, DNS hijack rules, and process-protection rules.
  • If DNS settings change, verify both simple-DNS and raw-DNS branches in V2rayDnsService.cs and SingboxDnsService.cs. The same application settings map to different core concepts: Xray uses DNS servers plus routing to a dns tag/outbound, while sing-box uses DNS servers/rules, route default_domain_resolver, fakeip servers, and optional ruleset-backed geosite/geoip conversion.
  • If custom outbound placeholders are changed, update both V2rayConfigTemplateService.cs and SingboxConfigTemplateService.cs. Both depend on CoreConfigContext.CustomOutboundMap being keyed by the generated outbound/endpoint object instance and support the same placeholder names, but Xray applies detour/interface inside streamSettings.sockopt and xhttp download settings while sing-box applies them as top-level detour and bind_interface.
  • If full-config-template behavior changes, check CoreConfigContextBuilder.cs for core-family template lookup and both config-template services. The builder fetches templates by normalized Xray-vs-sing-box family, and final services merge generated proxy material into user templates rather than replacing the whole template.

Risks

  • v2rayN/…/V2rayOutboundService.cs and v2rayN/…/SingboxOutboundService.cs preserve custom outbound replacement across proxy-chain cloning by copying context.CustomOutboundMap entries in CloneOutbounds. If new cloning paths are added without copying that map, custom outbound JSON files are left as sample placeholders and the user's raw outbound is not emitted.
  • v2rayN/…/V2rayConfigTemplateService.cs must mirror dialer-proxy and bind-interface values into xhttp downloadSettings.sockopt. If a future xhttp mutation only updates the main streamSettings.sockopt, Xray downloads can bypass the intended detour or interface while uploads use it.
  • v2rayN/…/SingboxRoutingService.cs contains explicit comments about dropping packets to the TUN interface's own addresses to avoid an auto-route loop. If that reject rule is removed or broadened to the whole TUN prefix, TUN traffic can either loop back into the outbound and pin CPU or drop the system resolver address and break name lookup.
  • v2rayN/…/CoreConfigContextBuilder.cs validates BindInterface differently by platform and TUN state, and BuildAll clears BindInterface/SendThrough for strict-route pre-SOCKS runs. If launch/elevation logic consumes a different TUN snapshot than this builder, the generated config can bind to an interface that the selected core cannot use.

Routing / Covers