ServiceLib profile formats and subscriptions
Overview
This area owns the import/export boundary between text subscription data, share links, custom core configs, and persisted ProfileItem rows. The main subscription entry point is v2rayN/…/SubscriptionHandler.cs: UpdateProcess loads enabled SubItem records, validates that each has an HTTP(S) URL, downloads the primary subscription (optionally through a subconverter target), appends any comma-separated MoreUrl subscription results, base64-decodes appended results when needed, and then hands the combined text to ConfigDbHandler.AddBatchServers(result, subId, true). Progress and final success/failure are surfaced through the injected updateFunc; the parser itself surfaces success as an imported-row count.
Single share links are routed by v2rayN/…/FmtHandler.cs. ResolveConfig trims input, matches the protocol prefix, and dispatches to protocol-specific format handlers under v2rayN/ServiceLib/Handler/Fmt/**; GetShareUri performs the reverse dispatch from ProfileItem.ConfigType. The protocol handlers normalize parsed data into ProfileItem fields (Address, Port, Password, Username, Remarks, Network, StreamSecurity, etc.) and the JSON-backed extension records exposed by ProfileItem.GetProtocolExtra() and ProfileItem.GetTransportExtra(). v2rayN/…/BaseFmt.cs centralizes common URI query handling for TLS/REALITY/ECH/finalMask fields and transports (raw, kcp, ws, httpupgrade, xhttp, grpc), including IPv6 bracket handling and percent-encoding discipline.
Batch subscription parsing is orchestrated by ConfigDbHandler.AddBatchServers (direct dependency of this flow). It first tries common line-oriented share links, with base64-decoded and raw variants, then falls back to SIP008 Shadowsocks JSON, WireGuard config files, mixed internal v2rayn:// links, and finally custom core configs. During common subscription imports it de-duplicates lines, applies the subscription filter regex to ProfileItem.Remarks, optionally pre-resolves hostnames with the subscription resolver, validates each profile through the protocol-specific add methods, sets Subid/IsSub, inserts successful rows, removes old subscription rows after a successful refresh, and attempts to preserve the active profile and traffic statistics by matching new profiles to old ones.
Supported share and config formats are:
- v2rayN/…/VmessFmt.cs: legacy base64 JSON
vmess://using v2rayN/…/VmessQRCode.cs, plus standard URI-stylevmess://user@host:port?...when an@is present. VMess exports back to the base64 QR JSON form and maps modern transport extras into the older QR keys. - v2rayN/…/ShadowsocksFmt.cs: legacy base64
ss://, SIP002 URI, SIP008 JSON viaResolveSip008,v2ray-pluginwebsocket/TLS plugin metadata, andobfs-localHTTP obfuscation. v2rayN/…/SsSIP008.cs allows numeric ports to be read from strings. - v2rayN/…/SocksFmt.cs: modern
socks://user:pass@host:portor base64 userinfo, plus legacy base64socks://user:pass@host:portpayloads; it acceptssocks://,socks5://, andsocks4://prefixes throughFmtHandler. - v2rayN/…/TrojanFmt.cs and v2rayN/…/VLESSFmt.cs: URI-style links with shared transport query parsing. Trojan preserves
allowInsecure/insecureandflow; VLESS preservesencryptionandflow. - v2rayN/…/Hysteria2Fmt.cs and v2rayN/…/HyRealm.cs:
hysteria2:///hy2://links, defaulting omitted ports to 443, plushysteria2+realm://andhysteria2+realm+http://forms. Realm links parse rendezvous host/port, token, realm name, STUN list, and the auth password query, and can export either a normal Hysteria2 link or a realm link depending onProtocolExtraItem.Hy2RealmUrl. - v2rayN/…/TuicFmt.cs:
tuic://username:password@host:portwith SNI/ALPN,allow_insecure, andcongestion_controlquery fields. - v2rayN/…/WireguardFmt.cs:
wireguard://privateKey@host:portURI fields for peer/interface metadata and full WireGuard[Interface]/[Peer]config import. Full configs produce oneProfileItemper peer, carrying interface private key, address, DNS, MTU, peer public/preshared/reserved values, and endpoint parsing for IPv4, hostnames, and bracketed IPv6. - v2rayN/…/AnytlsFmt.cs:
anytls://password@host[:port]with a default port of 443 when omitted, common transport/TLS query fields, andinsecure=1. - v2rayN/…/NaiveFmt.cs:
naive+https://andnaive+quic://links, defaulting omitted ports to 443, splitting userinfo before URL-decoding so colons embedded in credentials survive round-trip, and preservinginsecure-concurrency. - v2rayN/…/InnerFmt.cs: internal
v2rayn://<config-type>/<url-safe-base64-json>exports/imports for native profile transfer. It rejects unsupported enum/core values, skipsCustomprofiles, rewrites importedIndexIdvalues to avoid trusting external IDs, rewrites group child references to the new IDs, and supports embedded custom outbound JSON through temporary files. - v2rayN/…/V2rayFmt.cs and v2rayN/…/SingboxFmt.cs: custom JSON import for complete Xray/sing-box configs and individual outbound definitions. Complete configs are stored as
EConfigType.Customtemp files; individual usable outbounds are stored asEConfigType.Outboundtemp files.v2rayN/ServiceLib/Sample/SampleClientConfig,SampleOutbound,SingboxSampleClientConfig, andSingboxSampleOutboundare representative templates for those shapes. - v2rayN/…/ClashFmt.cs, HtmlPageFmt.cs, and
Hysteria2Fmt.ResolveFull2: fallback custom-file detection for Clash YAML-like content, HTML rejection, and full Hysteria2 config files.
UI-facing models in v2rayN/…/ProfileItemModel.cs summarize imported profiles for lists with protocol, remark, endpoint, subscription metadata, delay/speed, and traffic fields. v2rayN/…/RetResult.cs is the generic success/message/data DTO used by service callers outside the parser-specific count/msg return conventions.
Routing / covers
This doc owns:
v2rayN/ServiceLib/Handler/Fmt/**- v2rayN/…/SubscriptionHandler.cs
v2rayN/ServiceLib/Models/Dto/*Profile*v2rayN/ServiceLib/Models/Dto/*QRCode*- v2rayN/…/SsSIP008.cs
- v2rayN/…/HyRealm.cs
- v2rayN/…/RetResult.cs
v2rayN/ServiceLib/Sample/**
Coupling
- If a new share protocol or
EConfigTypeis added, update both dispatch directions in v2rayN/…/FmtHandler.cs and the add switch inConfigDbHandler.AddBatchServersCommon; otherwise links may export but never import, or import but never persist. - If query keys for TLS, REALITY, ECH, finalMask, or transport settings change in v2rayN/…/BaseFmt.cs, verify all URI-style handlers that call
ResolveUriQuery/ToUriQuery(VmessFmt,VLESSFmt,TrojanFmt,AnytlsFmt,NaiveFmt) still round-trip those fields and that lite handlers (Hysteria2Fmt,TuicFmt) intentionally omit the broader transport set. - If
ProfileItem.ProtoExtraorProfileItem.TransportExtraserialization changes, update v2rayN/…/InnerFmt.cs; it flattens/unflattensProtoExtraObjandTransportExtraObjin exported JSON rather than relying only on current entity serialization. - If subscription download behavior changes in v2rayN/…/SubscriptionHandler.cs, verify
ConfigDbHandler.AddBatchServersstill receives either raw share-link lines or decoded text. Additional subscription content is decoded before concatenation only whenUtils.IsBase64Stringsays so, while the main result is passed through for the batch importer to retry raw/base64 variants. - If custom config recognition changes in v2rayN/…/V2rayFmt.cs or SingboxFmt.cs, check
v2rayN/ServiceLib/Sample/SampleClientConfig,SampleOutbound,SingboxSampleClientConfig, andSingboxSampleOutbound; those samples reflect the minimum fields the parsers use to identify complete configs and usable outbounds.
Risks
- v2rayN/…/BaseFmt.cs intentionally does not URL-decode query values a second time after
Utils.ParseQueryString; double-decoding would corrupt values that legitimately contain percent sequences, and recent history includes format fixes for once-only password decoding. - v2rayN/…/NaiveFmt.cs, AnytlsFmt.cs, SocksFmt.cs, and ShadowsocksFmt.cs are fragile around URI defaults and credential encoding. Recent commits fixed omitted default ports, base64 SOCKS import, Naive colon round-trips, and SIP002 password decoding, so changes to userinfo splitting or
Uri.Port == -1handling can break imported links that previously worked. - v2rayN/…/InnerFmt.cs rewrites imported IDs and forbids imported
Customprofiles to avoid trusting externally supplied identifiers or file paths. Removing those checks would let imported internal links reference existing local profiles or arbitrary custom outbound files.