ServiceLib Common Utilities
Overview
The ServiceLib common utility surface is the cross-cutting support layer for serialization, paths, logging, localization, embedded resources, QR/barcode handling, platform checks, and small data conversion helpers used by higher-level v2rayN services. The main entry points are static helpers under v2rayN/ServiceLib/Common/**, localized UI resources under v2rayN/ServiceLib/Resx/**, and package/resource wiring in v2rayN/ServiceLib/ServiceLib.csproj.
v2rayN/…/JsonUtils.cs centralizes JSON behavior. Deserialization is case-insensitive, skips comments, and returns default on invalid or blank input; serialization logs failures through Logging.SaveLog and supports indented/non-indented output plus either null omission or null preservation. All JSON operations use the source-generated AppJsonContext declared at the bottom of the same file, so any model type serialized through these helpers must be listed with a [JsonSerializable] attribute or GetTypeInfo can fail at runtime.
v2rayN/…/YamlUtils.cs wraps YamlDotNet for config-style YAML. FromYaml parses a string into a YamlMappingNode, returning an empty mapping on errors; ToYaml writes a mapping back to text without assigning anchors; PreprocessYaml runs YamlDotNet's MergingParser so YAML merge keys are expanded before downstream consumers read the document.
v2rayN/…/Utils.cs is the broad utility hub. It owns string/list conversions, Base64 and URL helpers, MD5/file hash helpers, permissive URL parsing, header and hosts parsing, domain/IP validation, regex matching with a timeout guard, free-port selection, active interface/address inspection, version/runtime strings, GUID generation, system hosts loading, command output through CliWrap, startup/config/temp/bin/log/fonts directory construction, and platform helpers. Paths are rooted at StartupPath(): normally AppDomain.CurrentDomain.BaseDirectory, but if the Global.LocalAppData environment variable is set to 1, state moves under %LocalAppData%/v2rayN. Directory helpers (GetConfigPath, GetTempPath, GetBinPath, GetLogPath, GetFontsPath, GetBinConfigPath, GetBackupPath) create their directories on demand.
v2rayN/…/Logging.cs configures NLog programmatically. Setup() writes all levels to ${shortdate}.txt under Utils.GetLogPath(), using the layout ${longdate}-${level:uppercase=true} ${message}. SaveLog(string) writes informational messages through logger Log1; SaveLog(string, Exception) writes exception messages and stack traces through logger Log2. LoggingEnabled(false) suspends NLog globally, and save methods no-op while logging is suspended.
v2rayN/…/EmbedUtils.cs reads embedded text resources from the ServiceLib assembly and caches them in a ConcurrentDictionary; resource names are the manifest names built from the embedded Sample\... entries declared in v2rayN/ServiceLib/ServiceLib.csproj. It also has a simple LoadResource helper for reading a local text file when the caller provides a path. The same project file declares third-party dependencies used by this module: YamlDotNet, QRCoder, ZXing.Net.Bindings.SkiaSharp, NLog, CliWrap, IPNetwork2, and archive/download-related packages used by adjacent utilities.
v2rayN/…/QRCodeUtils.cs generates PNG QR codes and decodes QR/barcode images. QR generation tries error-correction levels from H to L, allowing long payloads to fall back to lower correction before rethrowing the last DataTooLongException. Decoding accepts either a file path or bytes, decodes via SkiaSharp/ZXing, and retries a horizontally flipped bitmap when the first read fails.
v2rayN/…/FakeIPUtils.cs validates fake IPv6 CIDR ranges for DNS/TUN-style configuration. Blank input defaults to the first Global.FakeIPv6Ranges value; valid ranges must parse as IPv6 and must not be /128. It normalizes the range string through IPNetwork.ToString() and reports an Xray-oriented pool size of 65535, reduced to (1 << hostBits) - 1 when the prefix leaves fewer than 16 host bits.
v2rayN/…/CountryExtension.cs maps a curated set of ISO-style country codes to flag emoji through CountryToEmoji. Missing or unsupported codes return null; matching is case-insensitive.
v2rayN/…/Extension.cs contains small extension methods used throughout ServiceLib: null/whitespace checks, line break replacement, trimming/quoting helpers, enum-related config helpers, safe collection append, ReactiveUI Interaction.HandleSafe, and newline-aware TextReader.NonWhiteSpaceLines. HandleSafe is important for UI flows because it logs unhandled ReactiveUI interaction exceptions and returns a caller-provided default instead of letting the observable fail.
v2rayN/…/WindowsUtils.cs is explicitly Windows-only. It reads/writes Registry.CurrentUser values and removes known Wintun devices by deriving deterministic GUIDs from wintunsingbox_tun and xray_tun, then invoking C:\Windows\System32\pnputil.exe through Utils.GetCliWrapOutput.
v2rayN/ServiceLib/Resx/ResUI.resx is the neutral UI string table, with culture-specific translations in sibling files such as ResUI.zh-Hans.resx, ResUI.zh-Hant.resx, ResUI.ru.resx, ResUI.fa.resx, ResUI.fr.resx, ResUI.hu.resx, ResUI.id.resx, and ResUI.az.resx. v2rayN/…/ResUI.Designer.cs is generated and exposes strongly typed ResUI.<Name> properties backed by a ResourceManager named ServiceLib.Resx.ResUI; callers can override lookup culture by setting ResUI.Culture. The .csproj marks these .resx files with PublicResXFileCodeGenerator, and the neutral file records ResUI.Designer.cs as its generated output.
v2rayN/…/FileUtils.cs, NetworkUtils.cs, and ProcUtils.cs are part of the common utility surface but are covered in detail by the download/update documentation. At this level, treat them as adjacent helpers for archive/file operations, bind-interface discovery, and process/admin relaunch support rather than as owners of the serialization/localization/logging patterns described here.
Routing / Covers
This doc owns:
v2rayN/ServiceLib/Common/**v2rayN/ServiceLib/Resx/**v2rayN/ServiceLib/ServiceLib.csproj
Detailed behavior for v2rayN/…/NetworkUtils.cs, v2rayN/…/FileUtils.cs, and v2rayN/…/ProcUtils.cs should be routed to the download/update doc when the change is specifically about update/download/archive/process execution behavior.
Coupling
- If a new model is serialized through
JsonUtils.Serialize,JsonUtils.Deserialize, orJsonUtils.SerializeToNode, also update the[JsonSerializable]list in v2rayN/…/JsonUtils.cs; the helper usesAppJsonContext.Default.GetTypeInfo(...)rather than reflection-based fallback. - If a new embedded sample/config resource is added, declare it in the embedded-resource item group in
v2rayN/ServiceLib/ServiceLib.csprojand use the matching manifest resource name when callingEmbedUtils.GetEmbedText; missing resources are caught and logged, then cached as an empty string. - If a resource key is added, renamed, or removed in
v2rayN/ServiceLib/Resx/ResUI.resx, keep the culture-specificResUI.*.resxfiles and generated ResUI.Designer.cs in sync; callers compile against the generatedResUI.<Name>properties, while runtime lookup depends on the neutral and translated.resxkey sets. - If startup/storage behavior changes in
Utils.StartupPath()orUtils.HasWritePermission()in v2rayN/…/Utils.cs, verify logging, config, temp, backup, bin, bin config, and font paths because all of those helpers derive from the same startup root and create directories as side effects. - If logging is initialized before storage-path decisions are final, verify
Logging.Setup()in v2rayN/…/Logging.cs; it binds NLog's file target toUtils.GetLogPath("${shortdate}.txt")at setup time. - If command execution or Unix permission behavior changes in
Utils.GetCliWrapOutput,Utils.SetLinuxChmod, orUtils.SetUnixFileMode, verify Windows TUN cleanup in v2rayN/…/WindowsUtils.cs and shell-file creation in v2rayN/…/FileUtils.cs, which depend on those helpers.
Risks
- v2rayN/…/JsonUtils.cs silently returns
defaultfor deserialize and parse failures. If a caller treatsdefaultas a valid empty configuration, malformed JSON can be mistaken for absent input instead of surfacing an error. - v2rayN/…/QRCodeUtils.cs catches and ignores decode errors in
ParseBarcode, andReaderBarcodeassumes a non-nullSKBitmapwhen flipping. Invalid image bytes can therefore become a silentnullresult, while unexpected null bitmap paths risk a later null-reference failure. - v2rayN/…/Utils.cs quotes single command arguments in
GetCliWrapOutputdifferently depending on whether one or multiple arguments are passed. If callers pass a shell command as a single string where tokenization matters, the invoked command can observe different argument boundaries than expected. - v2rayN/…/WindowsUtils.cs derives Wintun device GUIDs from hard-coded tunnel names before calling
pnputil.exe. If the core changes its tunnel naming convention without updating this list, stale Windows TUN devices will not be removed.