ServiceLib configuration and persistence
Overview
This module owns the persistent application state used by ServiceLib: the JSON configuration file, the SQLite database tables for domain entities, import/update helpers for profiles and subscriptions, and the shared constants/enums that constrain those values.
The process starts in v2rayN/…/AppManager.cs: InitApp() loads text configuration through ConfigTextHandler.Init(), then creates SQLite tables for SubItem, ProfileItem, ServerStatItem, RoutingItem, ProfileExItem, DNSItem, FullConfigTemplateItem, and the obsolete ProfileGroupItem; InitComponents() then runs ConfigDbHandler.MigrateProfileExtra(). Although AppManager.cs is outside this doc's owned globs, it is the direct lifecycle entry point for the covered persistence code.
v2rayN/…/ConfigState.cs is the in-memory singleton for the current Config. ConfigTextHandler.Config delegates to ConfigState.Instance.Current; SetCurrent() replaces the whole object under a lock, while Current lazily creates an empty Config if a caller reads it before initialization. Callers should normally initialize through ConfigTextHandler.Init() rather than constructing Config directly, because initialization fills many default sections.
v2rayN/…/ConfigTextHandler.cs persists the main Config object in guiNConfig.json, whose name is defined by Global.ConfigFileName in v2rayN/…/Global.cs. LoadConfig() reads the file from Utils.GetConfigPath(), deserializes JSON when present, and then normalizes missing or migrated fields: default inbound SOCKS settings, routing strategy, KCP/gRPC/TUN defaults, UI language/window/column state, simple DNS, speed-test URLs and concurrency, mux settings, system proxy bypasses, fragment/happy-eyeballs settings, and hotkey lists. SaveConfig() writes serialized JSON to a temporary file and then replaces the real file with File.Move(..., overwrite: true), so consumers should mutate ConfigState.Instance.Current and call ConfigTextHandler.SaveConfig() for text-backed settings.
v2rayN/…/SqliteHelper.cs wraps sqlite-net around guiNDB.db in the config path. It exposes synchronous table creation plus async insert, insert-or-replace, update, delete, raw execute/query, and table access. Bulk insert/replace/update methods run in SQLite transactions. DeleteAsync<T>() discovers the mapped primary key and deletes by key, so every deletable persisted entity under v2rayN/ServiceLib/Models/Entities/** needs a [PrimaryKey] property.
v2rayN/…/Config.cs and ConfigItems.cs define the JSON-backed state. Config stores selected profile/subscription IDs (IndexId, SubIndexId) and nested settings for core behavior, inbound listeners, routing basics, GUI/UI state, constants/source URLs, speed tests, mux, Hysteria defaults, Clash UI, system proxy, WebDAV, update checks, fragmentation, simple DNS, hotkeys, and happy-eyeballs. These classes are plain DTOs; their defaults are mostly enforced by ConfigTextHandler.LoadConfig(), not by constructors.
The SQLite-backed domain entities live under v2rayN/ServiceLib/Models/Entities/**:
- ProfileItem.cs is the primary server/profile row, keyed by
IndexId. It stores protocol identity (EConfigType, optionalECoreType), subscription linkage (Subid,IsSub), endpoint/auth/TLS fields, custom config file references, and JSON stringsProtoExtraandTransportExtra.GetProtocolExtra()/SetProtocolExtra()andGetTransportExtra()/SetTransportExtra()cache and serializeProtocolExtraItemandTransportExtraItem; update these through the setters so the persisted JSON column stays in sync. - ProtocolExtraItem.cs holds protocol-specific and group-specific fields: VMess/VLESS/Shadowsocks settings, WireGuard keys, Hysteria2/realm/gecko settings, MASQUE/WARP fields, policy-group child selectors, multiple-load mode, and custom-outbound flags.
- TransportExtraItem.cs holds network transport fields for raw/ws/xhttp/gRPC/KCP/xdrive. It replaces several obsolete columns still present on
ProfileItemfor migration. - SubItem.cs stores subscription metadata, update controls, request headers, regex filter, custom core selection, optional pre-SOCKS port, and optional pre-resolver.
- RoutingItem.cs stores a named routing configuration with serialized
RulesItemJSON inRuleSet, rule count, sorting, active flag, per-core domain strategy, and sing-box custom ruleset path. RulesItem.cs is the in-memory serialized rule shape. - DNSItem.cs stores per-core DNS templates for Xray/sing-box. FullConfigTemplateItem.cs stores full custom core templates and optional TUN templates.
- ProfileExItem.cs stores sidecar profile state such as delay, speed, sort, message, and IP info. ServerStatItem.cs stores traffic counters by
IndexId. - ProfileGroupItem.cs is obsolete and exists so
ConfigDbHandler.MigrateProfileExtraGroupV2ToV3()can migrate old group rows intoProfileItem.ProtoExtra.
v2rayN/…/ConfigDbQuery.cs is the read side for common database lookups. It returns ordered subscriptions/routing items, profile lists by subscription, profile DTO models joined to SubItem, direct lookups for selected rows, batch lookups by IndexId, and per-core DNS/full-template rows. Most callers should prefer these methods over ad hoc SQL. One exception is ProfileModels(), which builds raw SQL for filtering; it strips single quotes from the free-text filter but interpolates subid, so upstream callers should pass trusted IDs produced by this module.
v2rayN/…/ConfigDbHandler.cs is the write/orchestration side. Server mutations flow through AddServer() or protocol-specific methods such as AddVMessServer(), AddShadowsocksServer(), AddVlessServer(), AddHysteria2Server(), AddWireguardServer(), and similar. These methods trim and validate protocol fields against constants from Global.cs, normalize protocol extras, and then call AddServerCommon(). AddServerCommon() sets ConfigVersion = 4, validates stream security and network names, assigns a new IndexId when needed, updates sort through ProfileExManager, serializes protocol extras, and writes the ProfileItem with SQLiteHelper.ReplaceAsync() when toFile is true.
Batch import is handled by ConfigDbHandler.AddBatchServers(). It tries base64-decoded and raw subscription lines through FmtHandler.ResolveConfig(), then SIP008 Shadowsocks, WireGuard config, internal v2rayn:// URIs, and finally full custom config formats resolved by V2Ray/sing-box/Clash/Hysteria format helpers. For subscription imports, it snapshots existing rows, imports new rows, removes old subscription rows if import succeeds, attempts to preserve the active profile by matching old/new rows, and clones traffic statistics through StatisticsManager. Custom full-config and outbound imports copy or write files into the config path and store the generated file name in ProfileItem.Address; deletion paths such as RemoveProfileItem() and RemoveServersViaSubid() delete those copied files for Custom/Outbound profiles.
The same handler owns subscription, routing, DNS, full-template, and preset persistence. AddSubItem() creates or updates SubItem rows, assigns IDs/sort order, and parses URL remarks when adding from a string. DeleteSubItem() removes the subscription and its profiles and adjusts CurrentConfig.SubIndexId if necessary. SaveRoutingItem(), AddBatchRoutingRules(), SetDefaultRouting(), InitBuiltinRouting(), and InitExternalRouting() persist routing configurations and keep exactly one active routing item by updating all rows. InitBuiltinDNS(), SaveDNSItems(), GetExternalDNSItem(), InitBuiltinFullConfigTemplate(), and SaveFullConfigTemplate() seed and update per-core DNS/template records. ApplyRegionalPreset() mutates text-backed source URLs/simple DNS and SQLite-backed DNS rows together, so callers should save the text config after applying a preset if they need it durable.
v2rayN/…/Global.cs centralizes persistence-relevant constants and allowed values: config file names, protocol share prefixes, supported EConfigType sets per core, network names, security methods, DNS/routing template sources, proxy tags, default DNS addresses, TUN address/range lists, timeout defaults, and SQLite batch size. The enums under v2rayN/ServiceLib/Enums/** are persisted into JSON/SQLite as enum values and drive switch statements across this module: protocol/core types (EConfigType, ECoreType), transports (ETransport), movement/sort controls (EMove, EServerColName), rule and preset types, UI/theme/system proxy options, hotkeys, and test actions.
Coupling
- If a new persisted entity is added under
v2rayN/ServiceLib/Models/Entities/**, also update the startup table creation in v2rayN/…/AppManager.cs;SQLiteHelper.CreateTable<T>()is not automatic, and handlers will fail only when a missing table is first queried. - If fields move into
ProfileItem.ProtoExtraorProfileItem.TransportExtra, updateProfileItem.Get*/Set*()and the migration methods in v2rayN/…/ConfigDbHandler.cs. Old rows are upgraded only byMigrateProfileExtra(); changing the target record without migration leaves stale obsolete columns unread. - If
EConfigTypeor a protocol share prefix changes in v2rayN/…/EConfigType.cs or v2rayN/…/Global.cs, update everyConfigDbHandlerswitch that imports/adds profiles and the format handlers that produceProfileItem; unsupported types return-1and silently skip batch-import entries. - If
Global.Networks,ETransport, orTransportExtraItemchanges, verifyProfileItem.GetNetwork(),ConfigDbHandler.AddServerCommon(), andMigrateProfileTransportV3ToV4(). Invalid networks are coerced toGlobal.DefaultNetwork, so a missing allowed value can silently change a user's transport. - If ConfigItems.cs adds a non-null config section or required property, add defaulting in
ConfigTextHandler.LoadConfig(). Existing guiNConfig.json files deserialize with missing sections as null/defaults, and most callers assume initialization has made nested sections usable. - If routing or DNS template source constants in Global.cs change, verify
ConfigDbHandler.InitExternalRouting(),GetExternalDNSItem(), andApplyRegionalPreset(). These methods download JSON that is deserialized directly intoRoutingTemplate,RoutingItem,RulesItem,DNSItem, orSimpleDNSItemshapes. - If custom profile deletion behavior changes, check both
RemoveProfileItem()andRemoveServersViaSubid()in ConfigDbHandler.cs; custom profiles store copied file names inProfileItem.Address, and failing to delete through both paths leaves config files behind.
Risks
- v2rayN/…/ConfigDbHandler.cs uses raw SQL string interpolation in
RemoveServersViaSubid()andConfigDbQuery.ProfileModels()(v2rayN/…/ConfigDbQuery.cs). If untrusted text reachessubid, the delete/select statements can be malformed or broader than intended; keep subscription IDs module-generated or parameterize these queries before accepting external IDs. - v2rayN/…/ConfigTextHandler.cs updates nested config objects in memory without locking after
ConfigStatereturns the current object. Concurrent callers can interleave mutations andSaveConfig()writes; code that changes multiple settings should serialize access at a higher layer or save only after the final mutation. - v2rayN/…/ConfigDbHandler.cs separates
ProfileItemsort/order state intoProfileExManager/ProfileExItemwhile core profile rows live inProfileItem. If a new move, sort, delete, or clone path updates only one side, the UI can display stale ordering or orphaned delay/speed metadata. - v2rayN/…/ConfigDbHandler.cs subscription refresh deletes old rows after a successful import and then attempts best-effort matching to preserve the active profile and traffic stats. If
CompareProfileItem()orFindMatchedProfileItem()omits a newly significant field, refreshes can select the wrong replacement profile or clone statistics to the wrongIndexId.
Routing / covers
This doc owns:
v2rayN/ServiceLib/Handler/Data/**v2rayN/ServiceLib/Models/Configs/**v2rayN/ServiceLib/Models/Entities/**- v2rayN/…/SqliteHelper.cs
- v2rayN/…/Global.cs
- v2rayN/…/GlobalUsings.cs
v2rayN/ServiceLib/Enums/**