service.go 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687
  1. package sub
  2. import (
  3. "crypto/sha256"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "fmt"
  7. "maps"
  8. "net"
  9. "net/url"
  10. "slices"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/gin-gonic/gin"
  15. "github.com/goccy/go-json"
  16. "github.com/mhsanaei/3x-ui/v3/internal/database"
  17. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  18. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  20. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  21. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  22. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  23. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  24. )
  25. // SubService provides business logic for generating subscription links and managing subscription data.
  26. type SubService struct {
  27. address string
  28. remarkTemplate string
  29. datepicker string
  30. // subscriptionBody is true only when rendering the actual subscription
  31. // content a client app imports (raw /sub fetch, /json, /clash). The remark
  32. // template's per-client info is emitted there (on the first link); every
  33. // other context — the sub info page, the panel's link/QR displays — renders
  34. // the name-only template, like Remnawave.
  35. subscriptionBody bool
  36. // usageShown emits info once per subscription identity, including twins.
  37. // PrepareForRequest resets this per-request state.
  38. usageShown map[string]bool
  39. showIdentityOnAllLinks bool
  40. inboundService service.InboundService
  41. settingService service.SettingService
  42. // nodesByID is populated per request from the Node table so
  43. // resolveInboundAddress can return the node's address for any
  44. // inbound whose NodeID is set. Keeps the per-link host derivation
  45. // O(1) instead of O(N) DB hits.
  46. nodesByID map[int]*model.Node
  47. // statsByEmail maps a client email to its traffic row across ALL inbounds
  48. // loaded for the request. client_traffics.email is globally unique, so this
  49. // lets statsForClient resolve usage for a client even on an inbound that
  50. // doesn't own its row (multi-inbound subscriptions). Filled in
  51. // getInboundsBySubId; reset per request in PrepareForRequest.
  52. statsByEmail map[string]xray.ClientTraffic
  53. // clientsByInbound caches clients resolved for this request keyed by
  54. // inbound id then email, so the per-protocol link generators look a client
  55. // up without re-parsing the inbound's settings JSON per link.
  56. // fullyPrimedInbounds marks inbounds whose complete client list is cached
  57. // (a miss there is authoritative). Reset per request in PrepareForRequest.
  58. clientsByInbound map[int]map[string]model.Client
  59. fullyPrimedInbounds map[int]bool
  60. // settingsByInbound caches each inbound's settings decoded once per request
  61. // with the clients array left out; generators read only inbound-level
  62. // fields (encryption, method, version, …) from it.
  63. settingsByInbound map[int]map[string]any
  64. }
  65. // NewSubService creates a new subscription service with the given configuration.
  66. func NewSubService(remarkTemplate string) *SubService {
  67. return &SubService{
  68. remarkTemplate: remarkTemplate,
  69. }
  70. }
  71. // ForRequest returns a shallow copy with request-scoped state populated.
  72. // Subscription controllers share one base SubService, so request-specific
  73. // fields such as address and nodesByID must live on a per-request copy.
  74. func (s *SubService) ForRequest(host string) *SubService {
  75. req := *s
  76. req.PrepareForRequest(host)
  77. return &req
  78. }
  79. // PrepareForRequest sets per-request state (host + nodes map) on this
  80. // SubService instance. HTTP handlers should call ForRequest instead so the
  81. // controller's shared base service is never mutated by concurrent requests.
  82. func (s *SubService) PrepareForRequest(host string) {
  83. if !isRoutableHost(host) {
  84. if d := s.configuredPublicHost(); d != "" {
  85. host = d
  86. } else if isLoopbackHost(host) {
  87. host = "localhost"
  88. }
  89. }
  90. s.address = host
  91. s.usageShown = map[string]bool{}
  92. s.statsByEmail = map[string]xray.ClientTraffic{}
  93. s.clientsByInbound = map[int]map[string]model.Client{}
  94. s.fullyPrimedInbounds = map[int]bool{}
  95. s.settingsByInbound = map[int]map[string]any{}
  96. s.loadNodes()
  97. s.loadRemarkSettings()
  98. }
  99. // primeLinkClients caches clients (first occurrence per email, matching the
  100. // old settings-JSON iteration order) so clientForLink resolves them without a
  101. // parse. complete marks the inbound's whole client list as cached.
  102. func (s *SubService) primeLinkClients(inboundId int, clients []model.Client, complete bool) {
  103. if inboundId <= 0 {
  104. return
  105. }
  106. if s.clientsByInbound == nil {
  107. s.clientsByInbound = map[int]map[string]model.Client{}
  108. }
  109. m := s.clientsByInbound[inboundId]
  110. if m == nil {
  111. m = make(map[string]model.Client, len(clients))
  112. s.clientsByInbound[inboundId] = m
  113. }
  114. for _, c := range clients {
  115. if _, exists := m[c.Email]; !exists {
  116. m[c.Email] = c
  117. }
  118. }
  119. if complete {
  120. if s.fullyPrimedInbounds == nil {
  121. s.fullyPrimedInbounds = map[int]bool{}
  122. }
  123. s.fullyPrimedInbounds[inboundId] = true
  124. }
  125. }
  126. // clientForLink resolves one client of an inbound by email for link
  127. // generation: from the per-request cache when primed, otherwise by parsing
  128. // the settings JSON once and caching every client from it.
  129. func (s *SubService) clientForLink(inbound *model.Inbound, email string) (model.Client, bool) {
  130. if m, ok := s.clientsByInbound[inbound.Id]; ok {
  131. if c, hit := m[email]; hit {
  132. return c, true
  133. }
  134. if s.fullyPrimedInbounds[inbound.Id] {
  135. return model.Client{}, false
  136. }
  137. }
  138. clients, err := s.inboundService.GetClients(inbound)
  139. if err != nil {
  140. return model.Client{}, false
  141. }
  142. s.primeLinkClients(inbound.Id, clients, true)
  143. for i := range clients {
  144. if clients[i].Email == email {
  145. return clients[i], true
  146. }
  147. }
  148. return model.Client{}, false
  149. }
  150. // linkSettings returns the inbound's settings decoded once per request with
  151. // the clients array left out — the link generators read only inbound-level
  152. // fields from it and resolve clients via clientForLink. The shallow
  153. // RawMessage pass skips materializing a huge clients array entirely.
  154. func (s *SubService) linkSettings(inbound *model.Inbound) map[string]any {
  155. if inbound.Id > 0 {
  156. if cached, ok := s.settingsByInbound[inbound.Id]; ok {
  157. return cached
  158. }
  159. }
  160. shallow := map[string]json.RawMessage{}
  161. _ = json.Unmarshal([]byte(inbound.Settings), &shallow)
  162. out := make(map[string]any, len(shallow))
  163. for key, raw := range shallow {
  164. if key == "clients" {
  165. continue
  166. }
  167. var value any
  168. _ = json.Unmarshal(raw, &value)
  169. out[key] = value
  170. }
  171. if inbound.Id > 0 {
  172. if s.settingsByInbound == nil {
  173. s.settingsByInbound = map[int]map[string]any{}
  174. }
  175. s.settingsByInbound[inbound.Id] = out
  176. }
  177. return out
  178. }
  179. // loadRemarkSettings populates the per-request remark formatting state so
  180. // every subscription format — raw, JSON, Clash — renders remarks the same way
  181. // (the date formatter reads datepicker). Loading it only in getSubs left
  182. // JSON/Clash with the zero value.
  183. func (s *SubService) loadRemarkSettings() {
  184. var err error
  185. s.datepicker, err = s.settingService.GetDatepicker()
  186. if err != nil {
  187. s.datepicker = "gregorian"
  188. }
  189. s.showIdentityOnAllLinks, err = s.settingService.GetSubShowIdentityOnAllLinks()
  190. if err != nil {
  191. s.showIdentityOnAllLinks = false
  192. }
  193. }
  194. func (s *SubService) configuredPublicHost() string {
  195. if d, err := s.settingService.GetSubDomain(); err == nil && d != "" {
  196. return d
  197. }
  198. if d, err := s.settingService.GetWebDomain(); err == nil && d != "" {
  199. return d
  200. }
  201. return ""
  202. }
  203. func isRoutableHost(host string) bool {
  204. if host == "" {
  205. return false
  206. }
  207. if ip := net.ParseIP(strings.Trim(host, "[]")); ip != nil {
  208. return !ip.IsLoopback() && !ip.IsUnspecified()
  209. }
  210. return true
  211. }
  212. func isLoopbackHost(host string) bool {
  213. ip := net.ParseIP(strings.Trim(host, "[]"))
  214. return ip != nil && ip.IsLoopback()
  215. }
  216. // listenIsInternalOnly reports whether a bind address is reachable only from
  217. // the same host — a loopback IP or a unix-domain socket. Such an inbound can't
  218. // be dialed directly by a remote client, so when it is the child side of a
  219. // fallback its share link must be projected through the master. A public or
  220. // wildcard listen (""/0.0.0.0/::) is reachable on its own port and advertises
  221. // itself.
  222. func listenIsInternalOnly(listen string) bool {
  223. if listen == "" {
  224. return false
  225. }
  226. if listen[0] == '@' || listen[0] == '/' {
  227. return true
  228. }
  229. return isLoopbackHost(listen)
  230. }
  231. // matchingClients returns the inbound's clients whose SubID equals subId,
  232. // resolved from the normalized clients/client_inbounds tables (both filter
  233. // columns indexed) instead of parsing the settings JSON — at large client
  234. // counts that parse made every subscription fetch cost seconds. The
  235. // case-insensitive email dedupe stays as cheap insurance even though
  236. // clients.email is unique, preserving the #5134 guarantee that duplicate
  237. // settings entries never fan out into duplicate profiles. Resolved clients
  238. // are primed into the per-request cache so the link generators don't parse
  239. // settings either.
  240. func (s *SubService) matchingClients(inbound *model.Inbound, subId string) []model.Client {
  241. clients, err := s.inboundService.GetClientsBySubId(inbound.Id, subId)
  242. if err != nil {
  243. logger.Error("SubService - GetClientsBySubId: Unable to get clients from inbound")
  244. return nil
  245. }
  246. var out []model.Client
  247. seen := make(map[string]struct{}, len(clients))
  248. for _, client := range clients {
  249. key := strings.ToLower(client.Email)
  250. if _, dup := seen[key]; dup {
  251. continue
  252. }
  253. seen[key] = struct{}{}
  254. out = append(out, client)
  255. }
  256. s.primeLinkClients(inbound.Id, out, false)
  257. return out
  258. }
  259. // GetSubs retrieves subscription links for a given subscription ID and host.
  260. func (s *SubService) GetSubs(subId string, host string) ([]string, []string, int64, xray.ClientTraffic, error) {
  261. return s.ForRequest(host).getSubs(subId)
  262. }
  263. func (s *SubService) getSubs(subId string) ([]string, []string, int64, xray.ClientTraffic, error) {
  264. var result []string
  265. var emails []string
  266. var traffic xray.ClientTraffic
  267. var hasEnabledClient bool
  268. inbounds, err := s.getInboundsBySubId(subId)
  269. if err != nil {
  270. return nil, nil, 0, traffic, err
  271. }
  272. externalLinks, err := s.getClientExternalLinksBySubId(subId)
  273. if err != nil {
  274. return nil, nil, 0, traffic, err
  275. }
  276. if len(inbounds) == 0 && len(externalLinks) == 0 {
  277. return nil, nil, 0, traffic, nil
  278. }
  279. seenEmails := make(map[string]struct{})
  280. for _, inbound := range inbounds {
  281. clients := s.matchingClients(inbound, subId)
  282. if len(clients) == 0 {
  283. continue
  284. }
  285. s.projectThroughFallbackMaster(inbound)
  286. // Host overrides apply AFTER fallback projection so a host's
  287. // address/TLS wins over the projected master stream.
  288. hostEps := s.hostEndpoints(inbound, "raw")
  289. for _, client := range clients {
  290. if client.Enable {
  291. hasEnabledClient = true
  292. }
  293. var link string
  294. if len(hostEps) > 0 {
  295. link = s.linkFromHosts(inbound, client, hostEps)
  296. } else {
  297. link = s.GetLink(inbound, client.Email)
  298. }
  299. result = append(result, link)
  300. emails = append(emails, client.Email)
  301. seenEmails[client.Email] = struct{}{}
  302. }
  303. }
  304. for _, ext := range externalLinks {
  305. if ext.Enable {
  306. hasEnabledClient = true
  307. }
  308. for _, el := range expandEntry(ext) {
  309. if link := applyRemarkToLink(el.Link, el.Name); link != "" {
  310. result = append(result, link)
  311. emails = append(emails, ext.Email)
  312. seenEmails[ext.Email] = struct{}{}
  313. }
  314. }
  315. }
  316. uniqueEmails := make([]string, 0, len(seenEmails))
  317. for e := range seenEmails {
  318. uniqueEmails = append(uniqueEmails, e)
  319. }
  320. traffic, lastOnline := s.AggregateTrafficByEmails(uniqueEmails)
  321. traffic.Enable = hasEnabledClient
  322. return result, emails, lastOnline, traffic, nil
  323. }
  324. // inboundLinks builds the share links for every distinct client of one inbound
  325. // the same way getSubs does — managed Host endpoints win over the plain link so
  326. // {{HOST}} and per-host variants render — but across all clients rather than a
  327. // single subId. Dedups duplicate client JSON entries by email (#5134). Backs the
  328. // panel's "Export all inbound links" so it matches the client/QR pages.
  329. func (s *SubService) inboundLinks(inbound *model.Inbound) []string {
  330. clients, err := s.inboundService.GetClients(inbound)
  331. if err != nil {
  332. return nil
  333. }
  334. s.primeLinkClients(inbound.Id, clients, true)
  335. s.projectThroughFallbackMaster(inbound)
  336. hostEps := s.hostEndpoints(inbound, "raw")
  337. var out []string
  338. seen := make(map[string]struct{}, len(clients))
  339. for _, client := range clients {
  340. key := strings.ToLower(client.Email)
  341. if _, dup := seen[key]; dup {
  342. continue
  343. }
  344. seen[key] = struct{}{}
  345. var link string
  346. if len(hostEps) > 0 {
  347. link = s.linkFromHosts(inbound, client, hostEps)
  348. } else {
  349. link = s.GetLink(inbound, client.Email)
  350. }
  351. out = append(out, splitLinkLines(link)...)
  352. }
  353. return out
  354. }
  355. // AggregateTrafficByEmails resolves traffic for every email in one
  356. // query and folds the rows into a single ClientTraffic + lastOnline.
  357. // xray.ClientTraffic.Email is globally unique, so a multi-inbound
  358. // client's single row is attached to exactly one inbound — iterating
  359. // per-inbound ClientStats would miss it on the others. Used by GetSubs,
  360. // SubClashService.GetClash, and SubJsonService.GetJson to keep the
  361. // sub-info header consistent across all three formats.
  362. func (s *SubService) AggregateTrafficByEmails(emails []string) (xray.ClientTraffic, int64) {
  363. var agg xray.ClientTraffic
  364. var lastOnline int64
  365. if len(emails) == 0 {
  366. return agg, 0
  367. }
  368. db := database.GetDB()
  369. var rows []xray.ClientTraffic
  370. if err := db.
  371. Model(&xray.ClientTraffic{}).
  372. Where("email IN ?", emails).
  373. Find(&rows).Error; err != nil {
  374. logger.Warning("SubService - AggregateTrafficByEmails: load by email:", err)
  375. return agg, 0
  376. }
  377. // total/expiry are configured limits owned by the clients table, not the
  378. // runtime traffic rows. In a multi-node setup the node snapshot can reset
  379. // client_traffics.total/expiry_time to 0, so fall back to the clients
  380. // table to keep the Subscription-Userinfo header in sync with the UI (#4645).
  381. limits := make(map[string][2]int64, len(emails))
  382. var records []model.ClientRecord
  383. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails).Find(&records).Error; err != nil {
  384. logger.Warning("SubService - AggregateTrafficByEmails: load client limits:", err)
  385. } else {
  386. for _, r := range records {
  387. limits[r.Email] = [2]int64{r.TotalGB, r.ExpiryTime}
  388. }
  389. }
  390. now := time.Now().UnixMilli()
  391. first := true
  392. for _, ct := range rows {
  393. if ct.LastOnline > lastOnline {
  394. lastOnline = ct.LastOnline
  395. }
  396. total, expiry := ct.Total, ct.ExpiryTime
  397. if lim, ok := limits[ct.Email]; ok {
  398. if total == 0 {
  399. total = lim[0]
  400. }
  401. if expiry == 0 {
  402. expiry = lim[1]
  403. }
  404. }
  405. if first {
  406. agg.Up = ct.Up
  407. agg.Down = ct.Down
  408. agg.Total = total
  409. agg.ExpiryTime = subscriptionExpiryFromClient(now, expiry)
  410. first = false
  411. continue
  412. }
  413. agg.Up += ct.Up
  414. agg.Down += ct.Down
  415. if agg.Total == 0 || total == 0 {
  416. agg.Total = 0
  417. } else {
  418. agg.Total += total
  419. }
  420. normalized := subscriptionExpiryFromClient(now, expiry)
  421. if normalized != agg.ExpiryTime {
  422. agg.ExpiryTime = 0
  423. }
  424. }
  425. return agg, lastOnline
  426. }
  427. func subscriptionExpiryFromClient(nowMs, expiryTime int64) int64 {
  428. if expiryTime > 0 {
  429. return expiryTime
  430. }
  431. if expiryTime < 0 {
  432. return nowMs + (-expiryTime)
  433. }
  434. return 0
  435. }
  436. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  437. db := database.GetDB()
  438. var inbounds []*model.Inbound
  439. err := db.Model(model.Inbound{}).Where(`id in (
  440. SELECT DISTINCT inbounds.id
  441. FROM inbounds
  442. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  443. JOIN clients ON clients.id = client_inbounds.client_id
  444. WHERE
  445. inbounds.protocol in ('vmess','vless','trojan','shadowsocks','hysteria','wireguard','mtproto')
  446. AND clients.sub_id = ? AND inbounds.enable = ?
  447. )`, subId, true).Order("sub_sort_index ASC").Order("id ASC").Find(&inbounds).Error
  448. if err != nil {
  449. return nil, err
  450. }
  451. s.indexStatsBySubId(subId)
  452. return inbounds, nil
  453. }
  454. // indexStatsBySubId loads the traffic rows for just this subscriber's clients
  455. // into statsByEmail so statsForClient can resolve a client's usage on any of
  456. // its inbounds. It replaces preloading every matched inbound's ClientStats,
  457. // which read the entire client_traffics table on every subscription fetch of
  458. // a large inbound; statsForClient's per-email DB fallback covers any miss.
  459. func (s *SubService) indexStatsBySubId(subId string) {
  460. if s.statsByEmail == nil {
  461. s.statsByEmail = map[string]xray.ClientTraffic{}
  462. }
  463. db := database.GetDB()
  464. var emails []string
  465. if err := db.Model(&model.ClientRecord{}).Where("sub_id = ?", subId).Pluck("email", &emails).Error; err != nil {
  466. logger.Error("SubService - indexStatsBySubId: load emails:", err)
  467. return
  468. }
  469. const chunk = 400
  470. for lo := 0; lo < len(emails); lo += chunk {
  471. hi := min(lo+chunk, len(emails))
  472. var rows []xray.ClientTraffic
  473. if err := db.Where("email IN ?", emails[lo:hi]).Find(&rows).Error; err != nil {
  474. logger.Error("SubService - indexStatsBySubId: load traffics:", err)
  475. return
  476. }
  477. for _, st := range rows {
  478. s.statsByEmail[st.Email] = st
  479. }
  480. }
  481. }
  482. // projectThroughFallbackMaster mutates the inbound in place so its
  483. // Listen/Port/StreamSettings reflect the externally reachable master
  484. // when applicable. Covers both fallback mechanisms:
  485. // - panel-tracked: an inbound_fallbacks row where child_id = inbound.Id
  486. // - legacy unix-socket: inbound.Listen begins with "@" and some VLESS/
  487. // Trojan inbound's settings.fallbacks references that listen address
  488. //
  489. // Returns true when a projection happened; sub services call this before
  490. // generating links so a child VLESS-WS bound to 127.0.0.1 emits the
  491. // master's :443 + TLS state instead of its own loopback endpoint.
  492. //
  493. // Projection only applies to a child that is not directly reachable on its
  494. // own listen (loopback or a unix-domain socket). An inbound on a public or
  495. // wildcard listen is reachable on its own port, so it advertises its own
  496. // port + security even when a stale fallback rule still names it as a child —
  497. // otherwise its share link would leak the master's port and Reality/TLS
  498. // settings (#4987).
  499. func (s *SubService) projectThroughFallbackMaster(inbound *model.Inbound) bool {
  500. if inbound == nil {
  501. return false
  502. }
  503. if !listenIsInternalOnly(inbound.Listen) {
  504. return false
  505. }
  506. db := database.GetDB()
  507. var master *model.Inbound
  508. var rule model.InboundFallback
  509. if err := db.Where("child_id = ?", inbound.Id).
  510. Order("sort_order ASC, id ASC").
  511. First(&rule).Error; err == nil {
  512. var m model.Inbound
  513. if err := db.Where("id = ?", rule.MasterId).First(&m).Error; err == nil {
  514. master = &m
  515. }
  516. }
  517. if master == nil && len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  518. var m model.Inbound
  519. if err := db.Model(model.Inbound{}).
  520. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  521. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", inbound.Listen).
  522. First(&m).Error; err == nil {
  523. master = &m
  524. }
  525. }
  526. if master == nil {
  527. return false
  528. }
  529. inbound.StreamSettings = mergeStreamFromMaster(inbound.StreamSettings, master.StreamSettings)
  530. inbound.Listen = master.Listen
  531. inbound.Port = master.Port
  532. return true
  533. }
  534. // mergeStreamFromMaster copies the master's security + tlsSettings +
  535. // realitySettings + externalProxy onto the child's stream so the child's
  536. // link advertises the master's TLS / Reality state. Transport (network
  537. // + ws/grpc/etc. settings) stays the child's.
  538. func mergeStreamFromMaster(childStream, masterStream string) string {
  539. var stream map[string]any
  540. _ = json.Unmarshal([]byte(childStream), &stream)
  541. if stream == nil {
  542. stream = map[string]any{}
  543. }
  544. var mst map[string]any
  545. _ = json.Unmarshal([]byte(masterStream), &mst)
  546. if mst == nil {
  547. return childStream
  548. }
  549. stream["security"] = mst["security"]
  550. if v, ok := mst["tlsSettings"]; ok {
  551. stream["tlsSettings"] = v
  552. } else {
  553. delete(stream, "tlsSettings")
  554. }
  555. if v, ok := mst["realitySettings"]; ok {
  556. stream["realitySettings"] = v
  557. } else {
  558. delete(stream, "realitySettings")
  559. }
  560. if v, ok := mst["externalProxy"]; ok {
  561. stream["externalProxy"] = v
  562. }
  563. out, err := json.MarshalIndent(stream, "", " ")
  564. if err != nil {
  565. return childStream
  566. }
  567. return string(out)
  568. }
  569. // GetLink dispatches to the protocol-specific generator for one (inbound, client)
  570. // pair. Returns "" when the inbound's protocol doesn't produce a subscription URL
  571. // (socks, http, mixed, wireguard, dokodemo, tunnel). The returned string may
  572. // contain multiple `\n`-separated URLs when the inbound has externalProxy set.
  573. func (s *SubService) GetLink(inbound *model.Inbound, email string) string {
  574. switch inbound.Protocol {
  575. case "vmess":
  576. return s.genVmessLink(inbound, email)
  577. case "vless":
  578. return s.genVlessLink(inbound, email)
  579. case "trojan":
  580. return s.genTrojanLink(inbound, email)
  581. case "shadowsocks":
  582. return s.genShadowsocksLink(inbound, email)
  583. case "hysteria":
  584. return s.genHysteriaLink(inbound, email)
  585. case "mtproto":
  586. return s.genMtprotoLink(inbound, email)
  587. case "wireguard":
  588. return s.genWireguardLink(inbound, email)
  589. }
  590. return ""
  591. }
  592. // genWireguardLink builds a per-client wireguard:// share link mirroring the
  593. // frontend genWireguardLink: the client's private key is the userinfo, the
  594. // server public key (derived from the inbound secretKey) and the client's
  595. // tunnel address ride in the query. Returns "" when the client has no key.
  596. func (s *SubService) genWireguardLink(inbound *model.Inbound, email string) string {
  597. if inbound.Protocol != model.WireGuard {
  598. return ""
  599. }
  600. settings := s.linkSettings(inbound)
  601. secretKey, _ := settings["secretKey"].(string)
  602. resolved, ok := s.clientForLink(inbound, email)
  603. if !ok || resolved.PrivateKey == "" {
  604. return ""
  605. }
  606. client := &resolved
  607. link := fmt.Sprintf("wireguard://%s@%s", encodeUserinfo(client.PrivateKey), joinHostPort(s.resolveInboundAddress(inbound), inbound.Port))
  608. params := make(map[string]string)
  609. if secretKey != "" {
  610. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  611. params["publickey"] = pub
  612. }
  613. }
  614. if joined := strings.Join(client.AllowedIPs, ","); joined != "" {
  615. params["address"] = joined
  616. }
  617. if mtu, ok := settings["mtu"].(float64); ok && mtu > 0 {
  618. params["mtu"] = strconv.Itoa(int(mtu))
  619. }
  620. if dns, ok := settings["dns"].(string); ok && dns != "" {
  621. params["dns"] = dns
  622. }
  623. if client.PreSharedKey != "" {
  624. params["presharedkey"] = client.PreSharedKey
  625. }
  626. if client.KeepAlive > 0 {
  627. params["keepalive"] = strconv.Itoa(client.KeepAlive)
  628. }
  629. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", ""))
  630. }
  631. // genMtprotoLink builds a per-client Telegram proxy deep link for an mtproto
  632. // inbound: the server/port pair plus the client's own FakeTLS secret. The link
  633. // carries no remark fragment — Telegram proxy deep links have no name field, and
  634. // a trailing "#remark" is appended to the last query value by lenient parsers,
  635. // corrupting the server address. The remark is shown separately in the panel UI.
  636. // Returns "" when the client has no secret.
  637. func (s *SubService) genMtprotoLink(inbound *model.Inbound, email string) string {
  638. if inbound.Protocol != model.MTProto {
  639. return ""
  640. }
  641. resolved, ok := s.clientForLink(inbound, email)
  642. if !ok || resolved.Secret == "" {
  643. return ""
  644. }
  645. params := map[string]string{
  646. "server": s.resolveInboundAddress(inbound),
  647. "port": fmt.Sprintf("%d", inbound.Port),
  648. "secret": resolved.Secret,
  649. }
  650. return buildLinkWithParams("tg://proxy", params, "")
  651. }
  652. // Protocol link generators are intentionally ordered as:
  653. // vmess -> vless -> trojan -> shadowsocks -> hysteria.
  654. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  655. if inbound.Protocol != model.VMESS {
  656. return ""
  657. }
  658. address := s.resolveInboundAddress(inbound)
  659. obj := map[string]any{
  660. "v": "2",
  661. "add": address,
  662. "port": inbound.Port,
  663. "type": "none",
  664. }
  665. stream := unmarshalStreamSettings(inbound.StreamSettings)
  666. network, _ := stream["network"].(string)
  667. applyVmessNetworkParams(stream, network, obj)
  668. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  669. applyFinalMaskObj(finalmask, obj)
  670. }
  671. security, _ := stream["security"].(string)
  672. obj["tls"] = security
  673. if security == "tls" {
  674. applyVmessTLSParams(stream, obj)
  675. }
  676. client, ok := s.clientForLink(inbound, email)
  677. if !ok {
  678. return ""
  679. }
  680. obj["id"] = client.ID
  681. obj["scy"] = normalizeVmessSecurity(client.Security)
  682. externalProxies, _ := stream["externalProxy"].([]any)
  683. if len(externalProxies) > 0 {
  684. return s.buildVmessExternalProxyLinks(externalProxies, obj, inbound, email, network)
  685. }
  686. obj["ps"] = s.genRemark(inbound, email, "", network)
  687. return buildVmessLink(obj)
  688. }
  689. // normalizeVmessSecurity maps the vmess security values xray-core v26.7.11
  690. // removed ("none"/"zero"), plus the legacy empty string, to "auto" so links
  691. // and subscriptions stop advertising values the upgraded server rejects on
  692. // the wire.
  693. func normalizeVmessSecurity(security string) string {
  694. switch security {
  695. case "", "none", "zero":
  696. return "auto"
  697. }
  698. return security
  699. }
  700. // vlessEncryptionEnabled reports whether the VLESS inbound settings enable
  701. // VLESS-level encryption (vlessenc / ML-KEM). When on, the encryption/decryption
  702. // fields hold a generated dotted string (e.g. "mlkem768x25519plus.native.0rtt.<key>");
  703. // "none" or empty means off. The value is never the literal "vlessenc" — that is
  704. // the `xray vlessenc` CLI subcommand name, not a stored value.
  705. func vlessEncryptionEnabled(settings map[string]any) bool {
  706. for _, key := range []string{"encryption", "decryption"} {
  707. if v, ok := settings[key].(string); ok && v != "" && v != "none" {
  708. return true
  709. }
  710. }
  711. return false
  712. }
  713. // vlessFlowAllowed reports whether a client's XTLS Vision flow belongs in
  714. // generated links/configs. Mirrors inboundCanEnableTlsFlow in
  715. // internal/web/service: Vision runs on TCP with tls/reality (classic), and on
  716. // XHTTP whenever VLESS encryption (vlessenc / ML-KEM) is enabled — there the
  717. // VLESS-level encryption stands in for the transport TLS that Vision relies
  718. // on, regardless of the stream security layer (so XHTTP+REALITY+vlessenc
  719. // keeps its flow too).
  720. func vlessFlowAllowed(network, security string, settings map[string]any) bool {
  721. switch network {
  722. case "tcp":
  723. return security == "tls" || security == "reality"
  724. case "xhttp":
  725. return vlessEncryptionEnabled(settings)
  726. }
  727. return false
  728. }
  729. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  730. if inbound.Protocol != model.VLESS {
  731. return ""
  732. }
  733. address := s.resolveInboundAddress(inbound)
  734. stream := unmarshalStreamSettings(inbound.StreamSettings)
  735. client, ok := s.clientForLink(inbound, email)
  736. if !ok {
  737. return ""
  738. }
  739. uuid := client.ID
  740. port := inbound.Port
  741. streamNetwork, _ := stream["network"].(string)
  742. params := make(map[string]string)
  743. params["type"] = streamNetwork
  744. // Add encryption parameter for VLESS from inbound settings
  745. settings := s.linkSettings(inbound)
  746. if encryption, ok := settings["encryption"].(string); ok {
  747. params["encryption"] = encryption
  748. }
  749. applyShareNetworkParams(stream, streamNetwork, params)
  750. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  751. applyFinalMaskParams(finalmask, params)
  752. }
  753. security, _ := stream["security"].(string)
  754. switch security {
  755. case "tls":
  756. applyShareTLSParams(stream, params)
  757. case "reality":
  758. applyShareRealityParams(stream, params, subKey(client))
  759. default:
  760. params["security"] = "none"
  761. }
  762. if len(client.Flow) > 0 && vlessFlowAllowed(streamNetwork, security, settings) {
  763. params["flow"] = client.Flow
  764. }
  765. externalProxies, _ := stream["externalProxy"].([]any)
  766. if len(externalProxies) > 0 {
  767. return s.buildExternalProxyURLLinks(
  768. externalProxies,
  769. params,
  770. security,
  771. func(ep map[string]any, dest string, port int) string {
  772. return fmt.Sprintf("vless://%s@%s", applyVlessRoute(uuid, hostVlessRoute(ep)), joinHostPort(dest, port))
  773. },
  774. func(ep map[string]any) string {
  775. return s.endpointRemark(inbound, email, ep, streamNetwork)
  776. },
  777. )
  778. }
  779. link := fmt.Sprintf("vless://%s@%s", uuid, joinHostPort(address, port))
  780. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  781. }
  782. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  783. if inbound.Protocol != model.Trojan {
  784. return ""
  785. }
  786. address := s.resolveInboundAddress(inbound)
  787. stream := unmarshalStreamSettings(inbound.StreamSettings)
  788. client, ok := s.clientForLink(inbound, email)
  789. if !ok {
  790. return ""
  791. }
  792. password := encodeUserinfo(client.Password)
  793. port := inbound.Port
  794. streamNetwork, _ := stream["network"].(string)
  795. params := make(map[string]string)
  796. params["type"] = streamNetwork
  797. applyShareNetworkParams(stream, streamNetwork, params)
  798. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  799. applyFinalMaskParams(finalmask, params)
  800. }
  801. security, _ := stream["security"].(string)
  802. switch security {
  803. case "tls":
  804. applyShareTLSParams(stream, params)
  805. case "reality":
  806. applyShareRealityParams(stream, params, subKey(client))
  807. if streamNetwork == "tcp" && len(client.Flow) > 0 {
  808. params["flow"] = client.Flow
  809. }
  810. default:
  811. params["security"] = "none"
  812. }
  813. externalProxies, _ := stream["externalProxy"].([]any)
  814. if len(externalProxies) > 0 {
  815. return s.buildExternalProxyURLLinks(
  816. externalProxies,
  817. params,
  818. security,
  819. func(_ map[string]any, dest string, port int) string {
  820. return fmt.Sprintf("trojan://%s@%s", password, joinHostPort(dest, port))
  821. },
  822. func(ep map[string]any) string {
  823. return s.endpointRemark(inbound, email, ep, streamNetwork)
  824. },
  825. )
  826. }
  827. link := fmt.Sprintf("trojan://%s@%s", password, joinHostPort(address, port))
  828. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  829. }
  830. // encodeUserinfo percent-encodes a userinfo (password/auth) value so it
  831. // can be safely embedded in a `scheme://<value>@host:port` URL. RFC 3986
  832. // allows `=` in userinfo as a sub-delim, but several Trojan and Hysteria
  833. // clients reject share-links where the password contains literal `/`
  834. // or `=` (notably the common base64-with-padding shape produced by the
  835. // panel). Encode them too — this matches encodeURIComponent() on the
  836. // frontend and round-trips cleanly through net/url's parser.
  837. func encodeUserinfo(s string) string {
  838. return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
  839. }
  840. // joinHostPort wraps an IPv6 host in square brackets the way RFC 3986
  841. // requires for URI authorities, while leaving IPv4 addresses and hostnames
  842. // untouched. It also strips any brackets already present on the input so
  843. // callers don't have to normalize upstream.
  844. func joinHostPort(host string, port int) string {
  845. host = strings.Trim(host, "[]")
  846. return net.JoinHostPort(host, strconv.Itoa(port))
  847. }
  848. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  849. if inbound.Protocol != model.Shadowsocks {
  850. return ""
  851. }
  852. address := s.resolveInboundAddress(inbound)
  853. stream := unmarshalStreamSettings(inbound.StreamSettings)
  854. client, ok := s.clientForLink(inbound, email)
  855. if !ok {
  856. return ""
  857. }
  858. settings := s.linkSettings(inbound)
  859. inboundPassword, _ := settings["password"].(string)
  860. method, _ := settings["method"].(string)
  861. streamNetwork, _ := stream["network"].(string)
  862. params := make(map[string]string)
  863. params["type"] = streamNetwork
  864. applyShareNetworkParams(stream, streamNetwork, params)
  865. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  866. applyFinalMaskParams(finalmask, params)
  867. }
  868. security, _ := stream["security"].(string)
  869. if security == "tls" {
  870. applyShareTLSParams(stream, params)
  871. }
  872. // SIP002 clients (v2rayN) ignore the xray-native type/headerType/host/path
  873. // params and only read `plugin`. Re-encode a TCP http header as obfs-local so
  874. // they build a matching tcp/http outbound (v2rayN forces request path "/").
  875. if streamNetwork == "tcp" && params["headerType"] == "http" {
  876. host := params["host"]
  877. delete(params, "type")
  878. delete(params, "headerType")
  879. delete(params, "host")
  880. delete(params, "path")
  881. params["plugin"] = "obfs-local;obfs=http;obfs-host=" + host
  882. }
  883. // SIP002 userinfo is base64(method:password). For SIP022 (2022-blake3-*) the
  884. // userinfo MUST NOT be base64-encoded; method and password are percent-encoded.
  885. var userInfo string
  886. if strings.HasPrefix(method, "2022") {
  887. userInfo = fmt.Sprintf("%s:%s:%s",
  888. url.QueryEscape(method),
  889. url.QueryEscape(inboundPassword),
  890. url.QueryEscape(client.Password))
  891. } else {
  892. userInfo = base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", method, client.Password))
  893. }
  894. externalProxies, _ := stream["externalProxy"].([]any)
  895. if len(externalProxies) > 0 {
  896. proxyParams := cloneStringMap(params)
  897. proxyParams["security"] = security
  898. return s.buildExternalProxyURLLinks(
  899. externalProxies,
  900. proxyParams,
  901. security,
  902. func(_ map[string]any, dest string, port int) string {
  903. return fmt.Sprintf("ss://%s@%s", userInfo, joinHostPort(dest, port))
  904. },
  905. func(ep map[string]any) string {
  906. return s.endpointRemark(inbound, email, ep, streamNetwork)
  907. },
  908. )
  909. }
  910. link := fmt.Sprintf("ss://%s@%s", userInfo, joinHostPort(address, inbound.Port))
  911. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", streamNetwork))
  912. }
  913. func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) string {
  914. if inbound.Protocol != model.Hysteria {
  915. return ""
  916. }
  917. var stream map[string]any
  918. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  919. client, ok := s.clientForLink(inbound, email)
  920. if !ok {
  921. return ""
  922. }
  923. auth := encodeUserinfo(client.Auth)
  924. params := make(map[string]string)
  925. params["security"] = "tls"
  926. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  927. alpns, _ := tlsSetting["alpn"].([]any)
  928. var alpn []string
  929. for _, a := range alpns {
  930. if s, ok := a.(string); ok {
  931. alpn = append(alpn, s)
  932. }
  933. }
  934. if len(alpn) > 0 {
  935. params["alpn"] = strings.Join(alpn, ",")
  936. }
  937. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  938. params["sni"], _ = sniValue.(string)
  939. }
  940. tlsSettings, _ := searchKey(tlsSetting, "settings")
  941. if tlsSetting != nil {
  942. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  943. params["fp"], _ = fpValue.(string)
  944. }
  945. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  946. if ech, _ := echValue.(string); ech != "" {
  947. params["ech"] = ech
  948. }
  949. }
  950. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  951. params["vcn"] = vcn
  952. }
  953. if pins, ok := pinnedSha256List(tlsSettings); ok {
  954. for i, p := range pins {
  955. pins[i] = hysteriaPinHex(p)
  956. }
  957. params["pinSHA256"] = strings.Join(pins, ",")
  958. }
  959. }
  960. // salamander obfs (Hysteria2). Emit only the standard URI fields;
  961. // the non-standard fm=<json> finalmask dump breaks mihomo and other
  962. // Hysteria2 clients that reject unknown query params.
  963. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  964. if udpMasks, ok := finalmask["udp"].([]any); ok {
  965. for _, m := range udpMasks {
  966. mask, _ := m.(map[string]any)
  967. if mask == nil || mask["type"] != "salamander" {
  968. continue
  969. }
  970. settings, _ := mask["settings"].(map[string]any)
  971. if pw, ok := settings["password"].(string); ok && pw != "" {
  972. params["obfs"] = "salamander"
  973. params["obfs-password"] = pw
  974. break
  975. }
  976. }
  977. }
  978. }
  979. settings := s.linkSettings(inbound)
  980. version, _ := settings["version"].(float64)
  981. protocol := "hysteria2"
  982. if int(version) == 1 {
  983. protocol = "hysteria"
  984. }
  985. // Fan out one link per External Proxy entry if any. Previously this
  986. // generator ignored `externalProxy` entirely, so the link kept the
  987. // server's own IP/port even when the admin configured an alternate
  988. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  989. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  990. externalProxies, _ := stream["externalProxy"].([]any)
  991. if len(externalProxies) > 0 {
  992. links := make([]string, 0, len(externalProxies))
  993. for _, externalProxy := range externalProxies {
  994. ep, ok := externalProxy.(map[string]any)
  995. if !ok {
  996. continue
  997. }
  998. dest, _ := ep["dest"].(string)
  999. portF, okPort := ep["port"].(float64)
  1000. if dest == "" || !okPort {
  1001. continue
  1002. }
  1003. epParams := cloneStringMap(params)
  1004. applyExternalProxyHysteriaParams(ep, epParams)
  1005. link := fmt.Sprintf("%s://%s@%s", protocol, auth, joinHostPort(dest, int(portF)))
  1006. links = append(links, buildLinkWithParams(link, epParams, s.endpointRemark(inbound, email, ep, "quic")))
  1007. }
  1008. return strings.Join(links, "\n")
  1009. }
  1010. // No external proxy configured — use the inbound's resolved address so
  1011. // node-managed inbounds get the node's host instead of the central panel's.
  1012. if hopPorts := hysteriaHopPorts(stream); hopPorts != "" {
  1013. params["mport"] = hopPorts
  1014. }
  1015. link := fmt.Sprintf("%s://%s@%s", protocol, auth, joinHostPort(s.resolveInboundAddress(inbound), inbound.Port))
  1016. return buildLinkWithParams(link, params, s.genRemark(inbound, email, "", "quic"))
  1017. }
  1018. // hysteriaHopPorts returns the configured Hysteria2 UDP port-hopping range
  1019. // (finalmask.quicParams.udpHop.ports), or "" when port hopping is off. The
  1020. // range is emitted as the v2rayN-compatible `mport` query param; the URL port
  1021. // field stays numeric so .NET-Uri-based importers (v2rayN) can parse the link.
  1022. func hysteriaHopPorts(stream map[string]any) string {
  1023. finalmask, _ := stream["finalmask"].(map[string]any)
  1024. quicParams, _ := finalmask["quicParams"].(map[string]any)
  1025. udpHop, _ := quicParams["udpHop"].(map[string]any)
  1026. ports, _ := udpHop["ports"].(string)
  1027. return strings.TrimSpace(ports)
  1028. }
  1029. // loadNodes refreshes nodesByID from the DB. Called once per request so
  1030. // the per-inbound resolveInboundAddress lookups are pure map reads.
  1031. // We filter to address != ” so a half-configured node row doesn't
  1032. // accidentally produce a useless host like "https://:2053".
  1033. func (s *SubService) loadNodes() {
  1034. db := database.GetDB()
  1035. var nodes []*model.Node
  1036. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  1037. logger.Warning("subscription: load nodes failed:", err)
  1038. s.nodesByID = nil
  1039. return
  1040. }
  1041. m := make(map[int]*model.Node, len(nodes))
  1042. for _, n := range nodes {
  1043. m[n.Id] = n
  1044. }
  1045. s.nodesByID = m
  1046. }
  1047. // resolveInboundAddress picks the host an external client should connect to,
  1048. // honoring the inbound's share address strategy the same way the panel's
  1049. // share/QR link builder does (#5208):
  1050. // - "listen": an explicit, client-reachable bind Listen wins, backed by the
  1051. // node's address for node-managed inbounds;
  1052. // - "custom": the inbound's ShareAddr wins, then node, then listen;
  1053. // - "node" (default, and any unknown value): the node's address for
  1054. // node-managed inbounds, then a routable Listen — the pre-strategy order.
  1055. //
  1056. // Every chain ends at the admin's configured public host (Sub/Web domain) and
  1057. // then the subscriber's request host (s.address). Preferring the configured
  1058. // host over the request host for this last resort keeps a wildcard local inbound
  1059. // from advertising a bogus client IP that leaked into the request Host header
  1060. // behind NAT/proxy/CDN (#5425). A loopback/wildcard bind or a unix-domain-socket
  1061. // listen is a server-side detail and is never advertised; External Proxy still
  1062. // overrides everything upstream of this call.
  1063. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  1064. var nodeAddr string
  1065. if inbound.NodeID != nil && s.nodesByID != nil {
  1066. if n, ok := s.nodesByID[*inbound.NodeID]; ok {
  1067. nodeAddr = n.Address
  1068. }
  1069. }
  1070. var listenAddr string
  1071. if listen := inbound.Listen; listen != "" && listen[0] != '@' && listen[0] != '/' && isRoutableHost(listen) {
  1072. listenAddr = listen
  1073. }
  1074. candidates := []string{nodeAddr, listenAddr}
  1075. switch inbound.ShareAddrStrategy {
  1076. case "listen":
  1077. candidates = []string{listenAddr, nodeAddr}
  1078. case "custom":
  1079. candidates = []string{strings.TrimSpace(inbound.ShareAddr), nodeAddr, listenAddr}
  1080. }
  1081. for _, c := range candidates {
  1082. if c != "" {
  1083. return c
  1084. }
  1085. }
  1086. if d := s.configuredPublicHost(); d != "" {
  1087. return d
  1088. }
  1089. return s.address
  1090. }
  1091. func findClientIndex(clients []model.Client, email string) int {
  1092. for i, client := range clients {
  1093. if client.Email == email {
  1094. return i
  1095. }
  1096. }
  1097. return -1
  1098. }
  1099. func unmarshalStreamSettings(streamSettings string) map[string]any {
  1100. var stream map[string]any
  1101. _ = json.Unmarshal([]byte(streamSettings), &stream)
  1102. return stream
  1103. }
  1104. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  1105. params["path"], _ = settings["path"].(string)
  1106. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  1107. params["host"] = host
  1108. } else {
  1109. headers, _ := settings["headers"].(map[string]any)
  1110. params["host"] = searchHost(headers)
  1111. }
  1112. }
  1113. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  1114. obj["path"], _ = settings["path"].(string)
  1115. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  1116. obj["host"] = host
  1117. } else {
  1118. headers, _ := settings["headers"].(map[string]any)
  1119. obj["host"] = searchHost(headers)
  1120. }
  1121. }
  1122. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  1123. switch streamNetwork {
  1124. case "tcp":
  1125. tcp, _ := stream["tcpSettings"].(map[string]any)
  1126. header, _ := tcp["header"].(map[string]any)
  1127. typeStr, _ := header["type"].(string)
  1128. if typeStr == "http" {
  1129. request, _ := header["request"].(map[string]any)
  1130. requestPath, _ := request["path"].([]any)
  1131. if len(requestPath) > 0 {
  1132. params["path"], _ = requestPath[0].(string)
  1133. }
  1134. host := ""
  1135. if response, ok := header["response"].(map[string]any); ok {
  1136. if respHeaders, ok := response["headers"].(map[string]any); ok {
  1137. host = searchHost(respHeaders)
  1138. }
  1139. }
  1140. if host == "" {
  1141. headers, _ := request["headers"].(map[string]any)
  1142. host = searchHost(headers)
  1143. }
  1144. params["host"] = host
  1145. params["headerType"] = "http"
  1146. }
  1147. case "kcp":
  1148. applyKcpShareParams(stream, params)
  1149. case "ws":
  1150. ws, _ := stream["wsSettings"].(map[string]any)
  1151. applyPathAndHostParams(ws, params)
  1152. case "grpc":
  1153. grpc, _ := stream["grpcSettings"].(map[string]any)
  1154. params["serviceName"], _ = grpc["serviceName"].(string)
  1155. params["authority"], _ = grpc["authority"].(string)
  1156. if mm, _ := grpc["multiMode"].(bool); mm {
  1157. params["mode"] = "multi"
  1158. }
  1159. case "httpupgrade":
  1160. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  1161. applyPathAndHostParams(httpupgrade, params)
  1162. case "xhttp":
  1163. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1164. applyXhttpExtraParams(xhttp, params)
  1165. }
  1166. }
  1167. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  1168. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  1169. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  1170. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  1171. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1172. obj["x_padding_bytes"] = xpb
  1173. }
  1174. maps.Copy(obj, buildXhttpExtra(xhttp))
  1175. }
  1176. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  1177. obj["net"] = network
  1178. switch network {
  1179. case "tcp":
  1180. tcp, _ := stream["tcpSettings"].(map[string]any)
  1181. header, _ := tcp["header"].(map[string]any)
  1182. typeStr, _ := header["type"].(string)
  1183. obj["type"] = typeStr
  1184. if typeStr == "http" {
  1185. request, _ := header["request"].(map[string]any)
  1186. requestPath, _ := request["path"].([]any)
  1187. if len(requestPath) > 0 {
  1188. obj["path"], _ = requestPath[0].(string)
  1189. }
  1190. host := ""
  1191. if response, ok := header["response"].(map[string]any); ok {
  1192. if respHeaders, ok := response["headers"].(map[string]any); ok {
  1193. host = searchHost(respHeaders)
  1194. }
  1195. }
  1196. if host == "" {
  1197. headers, _ := request["headers"].(map[string]any)
  1198. host = searchHost(headers)
  1199. }
  1200. obj["host"] = host
  1201. }
  1202. case "kcp":
  1203. applyKcpShareObj(stream, obj)
  1204. case "ws":
  1205. ws, _ := stream["wsSettings"].(map[string]any)
  1206. applyPathAndHostObj(ws, obj)
  1207. case "grpc":
  1208. grpc, _ := stream["grpcSettings"].(map[string]any)
  1209. obj["path"], _ = grpc["serviceName"].(string)
  1210. obj["authority"], _ = grpc["authority"].(string)
  1211. if mm, _ := grpc["multiMode"].(bool); mm {
  1212. obj["type"] = "multi"
  1213. }
  1214. case "httpupgrade":
  1215. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  1216. applyPathAndHostObj(httpupgrade, obj)
  1217. case "xhttp":
  1218. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1219. applyPathAndHostObj(xhttp, obj)
  1220. if mode, ok := xhttp["mode"].(string); ok {
  1221. obj["mode"] = mode
  1222. }
  1223. applyXhttpExtraObj(xhttp, obj)
  1224. }
  1225. }
  1226. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  1227. params["security"] = "tls"
  1228. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1229. alpns, _ := tlsSetting["alpn"].([]any)
  1230. var alpn []string
  1231. for _, a := range alpns {
  1232. if s, ok := a.(string); ok {
  1233. alpn = append(alpn, s)
  1234. }
  1235. }
  1236. if len(alpn) > 0 {
  1237. params["alpn"] = strings.Join(alpn, ",")
  1238. }
  1239. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1240. params["sni"], _ = sniValue.(string)
  1241. }
  1242. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1243. if tlsSetting != nil {
  1244. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1245. params["fp"], _ = fpValue.(string)
  1246. }
  1247. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1248. if ech, _ := echValue.(string); ech != "" {
  1249. params["ech"] = ech
  1250. }
  1251. }
  1252. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1253. params["vcn"] = vcn
  1254. }
  1255. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1256. params["pcs"] = strings.Join(pins, ",")
  1257. }
  1258. }
  1259. }
  1260. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  1261. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  1262. alpns, _ := tlsSetting["alpn"].([]any)
  1263. if len(alpns) > 0 {
  1264. var alpn []string
  1265. for _, a := range alpns {
  1266. if s, ok := a.(string); ok {
  1267. alpn = append(alpn, s)
  1268. }
  1269. }
  1270. obj["alpn"] = strings.Join(alpn, ",")
  1271. }
  1272. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  1273. obj["sni"], _ = sniValue.(string)
  1274. }
  1275. tlsSettings, _ := searchKey(tlsSetting, "settings")
  1276. if tlsSetting != nil {
  1277. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  1278. obj["fp"], _ = fpValue.(string)
  1279. }
  1280. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  1281. if ech, _ := echValue.(string); ech != "" {
  1282. obj["ech"] = ech
  1283. }
  1284. }
  1285. if vcn, ok := verifyPeerCertByNameValue(tlsSettings); ok {
  1286. obj["vcn"] = vcn
  1287. }
  1288. if pins, ok := pinnedSha256List(tlsSettings); ok {
  1289. obj["pcs"] = strings.Join(pins, ",")
  1290. }
  1291. }
  1292. }
  1293. // verifyPeerCertByNameValue extracts tlsSettings.settings.verifyPeerCertByName
  1294. // (the v2rayN `vcn` param) as a trimmed string. Like pinnedPeerCertSha256 it is
  1295. // panel-only and flows into share links so clients verify the server
  1296. // certificate by this name — the replacement for the removed allowInsecure.
  1297. func verifyPeerCertByNameValue(tlsClientSettings any) (string, bool) {
  1298. raw, ok := searchKey(tlsClientSettings, "verifyPeerCertByName")
  1299. if !ok {
  1300. return "", false
  1301. }
  1302. s, ok := raw.(string)
  1303. if !ok {
  1304. return "", false
  1305. }
  1306. if s = strings.TrimSpace(s); s == "" {
  1307. return "", false
  1308. }
  1309. return s, true
  1310. }
  1311. // pinnedSha256List extracts tlsSettings.settings.pinnedPeerCertSha256 as a
  1312. // []string. The field is panel-only (stripped before the run-config reaches
  1313. // xray-core via internal/web/service/xray.go) but flows into share links so clients
  1314. // can pin the server's certificate hash.
  1315. func pinnedSha256List(tlsClientSettings any) ([]string, bool) {
  1316. raw, ok := searchKey(tlsClientSettings, "pinnedPeerCertSha256")
  1317. if !ok {
  1318. return nil, false
  1319. }
  1320. arr, ok := raw.([]any)
  1321. if !ok || len(arr) == 0 {
  1322. return nil, false
  1323. }
  1324. out := make([]string, 0, len(arr))
  1325. for _, v := range arr {
  1326. s, ok := v.(string)
  1327. if !ok || s == "" {
  1328. continue
  1329. }
  1330. out = append(out, s)
  1331. }
  1332. if len(out) == 0 {
  1333. return nil, false
  1334. }
  1335. return out, true
  1336. }
  1337. // hysteriaPinHex normalises a pinnedPeerCertSha256 entry into the 64-character
  1338. // lowercase hex form that Xray-core's Hysteria2 pinSHA256 parser requires.
  1339. //
  1340. // The panel stores pins in several shapes: base64 (xray-core's native TLS
  1341. // format, used by the generate button and the JSON subscription) and hex —
  1342. // either bare or colon-separated as `openssl x509 -fingerprint -sha256` emits
  1343. // it. Hysteria2 clients hex-decode pinSHA256 and crash on a base64 value, so
  1344. // each entry is coerced to bare hex here. Anything that is neither a 32-byte
  1345. // hex nor a 32-byte base64 SHA-256 is returned unchanged so unexpected data is
  1346. // not silently dropped. Mirrors decodeCertPin in internal/web/service/node.go.
  1347. func hysteriaPinHex(pin string) string {
  1348. pin = strings.TrimSpace(pin)
  1349. if h := strings.ReplaceAll(pin, ":", ""); len(h) == hex.EncodedLen(sha256.Size) {
  1350. if _, err := hex.DecodeString(h); err == nil {
  1351. return strings.ToLower(h)
  1352. }
  1353. }
  1354. for _, enc := range []*base64.Encoding{
  1355. base64.StdEncoding,
  1356. base64.RawStdEncoding,
  1357. base64.URLEncoding,
  1358. base64.RawURLEncoding,
  1359. } {
  1360. if b, err := enc.DecodeString(pin); err == nil && len(b) == sha256.Size {
  1361. return hex.EncodeToString(b)
  1362. }
  1363. }
  1364. return pin
  1365. }
  1366. func applyShareRealityParams(stream map[string]any, params map[string]string, clientKey string) {
  1367. params["security"] = "reality"
  1368. realitySetting, _ := stream["realitySettings"].(map[string]any)
  1369. realitySettings, _ := searchKey(realitySetting, "settings")
  1370. if realitySetting != nil {
  1371. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  1372. if sNames, _ := sniValue.([]any); len(sNames) > 0 {
  1373. params["sni"], _ = sNames[random.Num(len(sNames))].(string)
  1374. }
  1375. }
  1376. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  1377. params["pbk"], _ = pbkValue.(string)
  1378. }
  1379. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  1380. if shortIds, _ := sidValue.([]any); len(shortIds) > 0 {
  1381. params["sid"], _ = shortIds[random.Num(len(shortIds))].(string)
  1382. }
  1383. }
  1384. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  1385. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  1386. params["fp"] = fp
  1387. }
  1388. }
  1389. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  1390. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  1391. params["pqv"] = pqv
  1392. }
  1393. }
  1394. seed := ""
  1395. if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
  1396. seed, _ = spxValue.(string)
  1397. }
  1398. params["spx"] = deriveSpiderX(seed, clientKey)
  1399. }
  1400. }
  1401. // subKey returns a stable per-client identity for deterministic derivations,
  1402. // preferring the subscription id and falling back to the (unique) email.
  1403. func subKey(c model.Client) string {
  1404. if c.SubID != "" {
  1405. return c.SubID
  1406. }
  1407. return c.Email
  1408. }
  1409. // deriveSpiderX maps the inbound's spiderX seed plus a stable client key to a
  1410. // deterministic per-client "/path"; frontend/src/lib/xray/spider-x.ts mirrors it.
  1411. func deriveSpiderX(seed, clientKey string) string {
  1412. if seed == "" && clientKey == "" {
  1413. return "/" + random.Seq(15)
  1414. }
  1415. sum := sha256.Sum256([]byte(seed + "|" + clientKey))
  1416. return "/" + hex.EncodeToString(sum[:])[:15]
  1417. }
  1418. func buildVmessLink(obj map[string]any) string {
  1419. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  1420. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  1421. }
  1422. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  1423. newObj := map[string]any{}
  1424. for key, value := range baseObj {
  1425. if newSecurity != "none" || (key != "alpn" && key != "sni" && key != "fp" && key != "pcs") {
  1426. newObj[key] = value
  1427. }
  1428. }
  1429. return newObj
  1430. }
  1431. func applyExternalProxyTLSObj(ep map[string]any, obj map[string]any, security string) {
  1432. if security != "tls" {
  1433. return
  1434. }
  1435. if sni, ok := externalProxySNI(ep); ok {
  1436. obj["sni"] = sni
  1437. }
  1438. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1439. obj["fp"] = fp
  1440. }
  1441. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1442. obj["alpn"] = alpn
  1443. }
  1444. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1445. obj["pcs"] = joinAnyStrings(pins)
  1446. }
  1447. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1448. obj["vcn"] = vcn
  1449. }
  1450. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1451. obj["ech"] = ech
  1452. }
  1453. }
  1454. func applyExternalProxyTLSParams(ep map[string]any, params map[string]string, security string) {
  1455. if security != "tls" {
  1456. return
  1457. }
  1458. if sni, ok := externalProxySNI(ep); ok {
  1459. params["sni"] = sni
  1460. }
  1461. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1462. params["fp"] = fp
  1463. }
  1464. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  1465. params["alpn"] = alpn
  1466. }
  1467. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1468. params["pcs"] = joinAnyStrings(pins)
  1469. }
  1470. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1471. params["vcn"] = vcn
  1472. }
  1473. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1474. params["ech"] = ech
  1475. }
  1476. }
  1477. // applyExternalProxyHysteriaParams overrides the cert pin for a single
  1478. // external-proxy entry on a Hysteria link. Hysteria carries the pin as a hex
  1479. // `pinSHA256` (not the `pcs` the URL-param protocols use), so each entry is
  1480. // coerced through hysteriaPinHex like the main pin. sni/fp/alpn are left as
  1481. // the inbound's own — Hysteria external proxies are typically alternate
  1482. // endpoints (port-hop / CDN) fronting the same certificate.
  1483. func applyExternalProxyHysteriaParams(ep map[string]any, params map[string]string) {
  1484. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1485. hexPins := make([]string, 0, len(pins))
  1486. for _, p := range pins {
  1487. if s, ok := p.(string); ok {
  1488. hexPins = append(hexPins, hysteriaPinHex(s))
  1489. }
  1490. }
  1491. params["pinSHA256"] = strings.Join(hexPins, ",")
  1492. }
  1493. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  1494. params["insecure"] = "1"
  1495. }
  1496. }
  1497. // cloneStreamForExternalProxy returns a shallow clone of stream with
  1498. // tlsSettings (and its nested settings map) deep-copied. The external
  1499. // proxy loop mutates tlsSettings per iteration, so without isolating
  1500. // those maps each proxy's SNI/fingerprint/ALPN would leak into the next.
  1501. func cloneStreamForExternalProxy(stream map[string]any) map[string]any {
  1502. out := cloneMap(stream)
  1503. ts, ok := out["tlsSettings"].(map[string]any)
  1504. if !ok || ts == nil {
  1505. return out
  1506. }
  1507. clonedTs := cloneMap(ts)
  1508. if inner, ok := clonedTs["settings"].(map[string]any); ok && inner != nil {
  1509. clonedTs["settings"] = cloneMap(inner)
  1510. }
  1511. out["tlsSettings"] = clonedTs
  1512. return out
  1513. }
  1514. func applyExternalProxyTLSToStream(ep map[string]any, stream map[string]any, security string) {
  1515. if security != "tls" {
  1516. return
  1517. }
  1518. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  1519. if tlsSettings == nil {
  1520. tlsSettings = map[string]any{}
  1521. stream["tlsSettings"] = tlsSettings
  1522. }
  1523. if sni, ok := externalProxySNI(ep); ok {
  1524. tlsSettings["serverName"] = sni
  1525. }
  1526. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1527. tlsSettings["fingerprint"] = fp
  1528. }
  1529. if alpn, ok := externalProxyALPNList(ep["alpn"]); ok {
  1530. tlsSettings["alpn"] = alpn
  1531. }
  1532. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1533. settings, _ := tlsSettings["settings"].(map[string]any)
  1534. if settings == nil {
  1535. settings = map[string]any{}
  1536. tlsSettings["settings"] = settings
  1537. }
  1538. settings["pinnedPeerCertSha256"] = pins
  1539. }
  1540. if ech, ok := ep["echConfigList"].(string); ok && ech != "" {
  1541. settings, _ := tlsSettings["settings"].(map[string]any)
  1542. if settings == nil {
  1543. settings = map[string]any{}
  1544. tlsSettings["settings"] = settings
  1545. }
  1546. settings["echConfigList"] = ech
  1547. }
  1548. if vcn, ok := ep["verifyPeerCertByName"].(string); ok && vcn != "" {
  1549. settings, _ := tlsSettings["settings"].(map[string]any)
  1550. if settings == nil {
  1551. settings = map[string]any{}
  1552. tlsSettings["settings"] = settings
  1553. }
  1554. settings["verifyPeerCertByName"] = vcn
  1555. }
  1556. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  1557. settings, _ := tlsSettings["settings"].(map[string]any)
  1558. if settings == nil {
  1559. settings = map[string]any{}
  1560. tlsSettings["settings"] = settings
  1561. }
  1562. settings["allowInsecure"] = true
  1563. }
  1564. }
  1565. func externalProxySNI(ep map[string]any) (string, bool) {
  1566. if sni, ok := ep["sni"].(string); ok && sni != "" {
  1567. return sni, true
  1568. }
  1569. return "", false
  1570. }
  1571. func externalProxyALPN(value any) (string, bool) {
  1572. switch v := value.(type) {
  1573. case string:
  1574. return v, v != ""
  1575. case []string:
  1576. if len(v) == 0 {
  1577. return "", false
  1578. }
  1579. return strings.Join(v, ","), true
  1580. case []any:
  1581. alpn := make([]string, 0, len(v))
  1582. for _, item := range v {
  1583. if s, ok := item.(string); ok && s != "" {
  1584. alpn = append(alpn, s)
  1585. }
  1586. }
  1587. if len(alpn) == 0 {
  1588. return "", false
  1589. }
  1590. return strings.Join(alpn, ","), true
  1591. default:
  1592. return "", false
  1593. }
  1594. }
  1595. func externalProxyALPNList(value any) ([]any, bool) {
  1596. switch v := value.(type) {
  1597. case string:
  1598. if v == "" {
  1599. return nil, false
  1600. }
  1601. parts := strings.Split(v, ",")
  1602. out := make([]any, 0, len(parts))
  1603. for _, part := range parts {
  1604. if part = strings.TrimSpace(part); part != "" {
  1605. out = append(out, part)
  1606. }
  1607. }
  1608. return out, len(out) > 0
  1609. case []string:
  1610. out := make([]any, 0, len(v))
  1611. for _, item := range v {
  1612. if item != "" {
  1613. out = append(out, item)
  1614. }
  1615. }
  1616. return out, len(out) > 0
  1617. case []any:
  1618. out := make([]any, 0, len(v))
  1619. for _, item := range v {
  1620. if s, ok := item.(string); ok && s != "" {
  1621. out = append(out, s)
  1622. }
  1623. }
  1624. return out, len(out) > 0
  1625. default:
  1626. return nil, false
  1627. }
  1628. }
  1629. // externalProxyPins extracts an external-proxy entry's pinnedPeerCertSha256
  1630. // as a []any of non-empty strings. The []any element type matches what the
  1631. // JSON/Clash sub builders expect when reading the value back off the cloned
  1632. // stream's tlsSettings.settings.
  1633. func externalProxyPins(value any) ([]any, bool) {
  1634. switch v := value.(type) {
  1635. case []string:
  1636. out := make([]any, 0, len(v))
  1637. for _, item := range v {
  1638. if item != "" {
  1639. out = append(out, item)
  1640. }
  1641. }
  1642. return out, len(out) > 0
  1643. case []any:
  1644. out := make([]any, 0, len(v))
  1645. for _, item := range v {
  1646. if s, ok := item.(string); ok && s != "" {
  1647. out = append(out, s)
  1648. }
  1649. }
  1650. return out, len(out) > 0
  1651. default:
  1652. return nil, false
  1653. }
  1654. }
  1655. func joinAnyStrings(items []any) string {
  1656. parts := make([]string, 0, len(items))
  1657. for _, item := range items {
  1658. if s, ok := item.(string); ok {
  1659. parts = append(parts, s)
  1660. }
  1661. }
  1662. return strings.Join(parts, ",")
  1663. }
  1664. // buildVmessExternalProxyLinks is a thin adapter: it maps the legacy
  1665. // externalProxy entries to []ShareEndpoint and renders them through the unified
  1666. // endpoint path. Kept as a thin shim over the unified endpoint builder so
  1667. // genVmessLink keeps calling one helper (now threading transport through).
  1668. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string, transport string) string {
  1669. eps := make([]ShareEndpoint, 0, len(externalProxies))
  1670. for _, externalProxy := range externalProxies {
  1671. ep, _ := externalProxy.(map[string]any)
  1672. eps = append(eps, externalProxyToEndpoint(ep))
  1673. }
  1674. return s.buildEndpointVmessLinks(eps, baseObj, inbound, email, transport)
  1675. }
  1676. // buildLinkWithParams appends ?query and #fragment to a pre-built
  1677. // scheme://userinfo@host:port string without re-parsing it. The caller
  1678. // has already escaped userinfo via encodeUserinfo (or chosen a base64
  1679. // alphabet with no reserved chars); a url.Parse + .String() round-trip
  1680. // would silently decode that escaping because Go's userinfo emitter
  1681. // leaves sub-delims (=, +, ;) literal, which breaks Trojan/Hysteria/SS
  1682. // clients that reject those chars in the password.
  1683. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  1684. return appendQueryAndFragment(link, params, fragment, "", false)
  1685. }
  1686. // buildLinkWithParamsAndSecurity is buildLinkWithParams plus an
  1687. // external-proxy override: the `security` key in params is replaced with
  1688. // the supplied value, and TLS hint fields (alpn/sni/fp/pcs) are stripped
  1689. // when the override is `none`.
  1690. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  1691. return appendQueryAndFragment(link, params, fragment, security, omitTLSFields)
  1692. }
  1693. func appendQueryAndFragment(link string, params map[string]string, fragment, securityOverride string, omitTLSFields bool) string {
  1694. var sb strings.Builder
  1695. sb.WriteString(link)
  1696. if len(params) > 0 {
  1697. q := url.Values{}
  1698. for k, v := range params {
  1699. if securityOverride != "" && k == "security" {
  1700. v = securityOverride
  1701. }
  1702. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp" || k == "pcs") {
  1703. continue
  1704. }
  1705. q.Set(k, v)
  1706. }
  1707. encoded := q.Encode()
  1708. if encoded != "" {
  1709. if strings.Contains(link, "?") {
  1710. sb.WriteByte('&')
  1711. } else {
  1712. sb.WriteByte('?')
  1713. }
  1714. sb.WriteString(encoded)
  1715. }
  1716. }
  1717. if fragment != "" {
  1718. sb.WriteByte('#')
  1719. // Match the frontend's encodeURIComponent(remark): spaces become
  1720. // %20 (not + as in query strings).
  1721. sb.WriteString(strings.ReplaceAll(url.QueryEscape(fragment), "+", "%20"))
  1722. }
  1723. return sb.String()
  1724. }
  1725. // buildExternalProxyURLLinks is a thin adapter: it maps the legacy externalProxy
  1726. // entries to []ShareEndpoint and renders them through the unified endpoint path.
  1727. // Kept so the genVless/genTrojan/genShadowsocks call sites are unchanged.
  1728. func (s *SubService) buildExternalProxyURLLinks(
  1729. externalProxies []any,
  1730. params map[string]string,
  1731. baseSecurity string,
  1732. makeLink func(ep map[string]any, dest string, port int) string,
  1733. makeRemark func(ep map[string]any) string,
  1734. ) string {
  1735. eps := make([]ShareEndpoint, 0, len(externalProxies))
  1736. for _, externalProxy := range externalProxies {
  1737. ep, _ := externalProxy.(map[string]any)
  1738. eps = append(eps, externalProxyToEndpoint(ep))
  1739. }
  1740. return s.buildEndpointLinks(eps, params, baseSecurity, func(e ShareEndpoint) string {
  1741. return makeLink(e.ep, e.Address, e.Port)
  1742. }, func(e ShareEndpoint) string {
  1743. return makeRemark(e.ep)
  1744. })
  1745. }
  1746. func cloneStringMap(source map[string]string) map[string]string {
  1747. cloned := make(map[string]string, len(source))
  1748. maps.Copy(cloned, source)
  1749. return cloned
  1750. }
  1751. // genRemark builds the remark for a non-host link (raw default / legacy
  1752. // externalProxy / synthetic JSON-Clash entry). A set remark template drives it
  1753. // in both the body and display contexts (genTemplatedRemark renders the
  1754. // name-only part on displays); with no template it falls back to the inbound
  1755. // remark, extra and email joined by "-".
  1756. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string, transport string) string {
  1757. if s.remarkTemplate != "" {
  1758. return s.genTemplatedRemark(inbound, s.lookupClient(inbound, email), extra, transport)
  1759. }
  1760. return fallbackRemark(inbound.Remark, extra, email)
  1761. }
  1762. func fallbackRemark(parts ...string) string {
  1763. out := make([]string, 0, len(parts))
  1764. for _, p := range parts {
  1765. if p != "" {
  1766. out = append(out, p)
  1767. }
  1768. }
  1769. return strings.Join(out, "-")
  1770. }
  1771. // findClientStats returns the inbound's traffic record for email, if present.
  1772. func (s *SubService) findClientStats(inbound *model.Inbound, email string) (xray.ClientTraffic, bool) {
  1773. for _, clientStat := range inbound.ClientStats {
  1774. if clientStat.Email == email {
  1775. return clientStat, true
  1776. }
  1777. }
  1778. return xray.ClientTraffic{}, false
  1779. }
  1780. // statsByEmailFromDB resolves a client's traffic row straight from the DB by its
  1781. // globally-unique email, caching the hit into statsByEmail for the rest of the
  1782. // request. It's the last-resort lookup behind statsForClient: the preloaded
  1783. // ClientStats and the statsByEmail index are both keyed by
  1784. // client_traffics.inbound_id, which is written once by AddClientStat and never
  1785. // updated. When an inbound is deleted and recreated it gets a new id, so the old
  1786. // row is orphaned from every loaded inbound and both in-memory paths miss —
  1787. // leaving {{TRAFFIC_USED}} stuck at 0 for pre-existing clients even though their
  1788. // usage is intact (#5567). Matching by email recovers it, the same way the
  1789. // sub-info header's AggregateTrafficByEmails already does.
  1790. func (s *SubService) statsByEmailFromDB(email string) (xray.ClientTraffic, bool) {
  1791. db := database.GetDB()
  1792. if db == nil {
  1793. return xray.ClientTraffic{}, false
  1794. }
  1795. var row xray.ClientTraffic
  1796. if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", email).First(&row).Error; err != nil {
  1797. return xray.ClientTraffic{}, false
  1798. }
  1799. if s.statsByEmail == nil {
  1800. s.statsByEmail = map[string]xray.ClientTraffic{}
  1801. }
  1802. s.statsByEmail[email] = row
  1803. return row, true
  1804. }
  1805. func searchKey(data any, key string) (any, bool) {
  1806. switch val := data.(type) {
  1807. case map[string]any:
  1808. for k, v := range val {
  1809. if k == key {
  1810. return v, true
  1811. }
  1812. if result, ok := searchKey(v, key); ok {
  1813. return result, true
  1814. }
  1815. }
  1816. case []any:
  1817. for _, v := range val {
  1818. if result, ok := searchKey(v, key); ok {
  1819. return result, true
  1820. }
  1821. }
  1822. }
  1823. return nil, false
  1824. }
  1825. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  1826. // that goes into the URL's `extra` param (or, for VMess, the link
  1827. // object). Carries ONLY the bidirectional fields from xray-core's
  1828. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  1829. // must match. Strictly one-sided fields are excluded:
  1830. //
  1831. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  1832. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  1833. // them just bloats the URL.
  1834. // - client-only values are included only when present in the inbound
  1835. // JSON. Some deployments/imported configs carry them there, and the
  1836. // subscription link is the only place clients can receive them.
  1837. //
  1838. // Truthy-only guards keep default inbounds emitting the same compact URL
  1839. // they did before this helper grew.
  1840. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  1841. if xhttp == nil {
  1842. return nil
  1843. }
  1844. extra := map[string]any{}
  1845. if mode, ok := xhttp["mode"].(string); ok && len(mode) > 0 {
  1846. extra["mode"] = mode
  1847. }
  1848. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1849. extra["xPaddingBytes"] = xpb
  1850. }
  1851. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  1852. extra["xPaddingObfsMode"] = true
  1853. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  1854. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1855. extra[field] = v
  1856. }
  1857. }
  1858. }
  1859. stringFields := []string{
  1860. "uplinkHTTPMethod",
  1861. "sessionIDPlacement", "sessionIDKey", "sessionIDTable", "sessionIDLength",
  1862. "seqPlacement", "seqKey",
  1863. "uplinkDataPlacement", "uplinkDataKey",
  1864. "scMaxEachPostBytes", "scMinPostsIntervalMs",
  1865. }
  1866. // Values matching xray-core's own defaults are redundant on the wire and
  1867. // the literal scMinPostsIntervalMs=30 is a known DPI fingerprint (#5141).
  1868. // Old panels seeded these defaults into every xhttp inbound, so filter
  1869. // them here instead of requiring every stored config to be re-saved.
  1870. coreDefaults := map[string]string{
  1871. "scMaxEachPostBytes": "1000000",
  1872. "scMinPostsIntervalMs": "30",
  1873. }
  1874. for _, field := range stringFields {
  1875. if v, ok := xhttp[field].(string); ok && len(v) > 0 && v != coreDefaults[field] {
  1876. extra[field] = v
  1877. }
  1878. }
  1879. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  1880. // Lift them onto the renamed keys so links from not-yet-resaved configs
  1881. // still carry the session settings. Mirrors the frontend migration.
  1882. for legacy, renamed := range map[string]string{
  1883. "sessionPlacement": "sessionIDPlacement",
  1884. "sessionKey": "sessionIDKey",
  1885. } {
  1886. if _, exists := extra[renamed]; !exists {
  1887. if v, ok := xhttp[legacy].(string); ok && len(v) > 0 {
  1888. extra[renamed] = v
  1889. }
  1890. }
  1891. }
  1892. // Older clients still read the pre-#6258 names from the subscription
  1893. // extra JSON. Emit aliases after lifting legacy inputs so both old and
  1894. // new clients can consume the same link.
  1895. if v, ok := extra["sessionIDPlacement"].(string); ok && len(v) > 0 {
  1896. extra["sessionPlacement"] = v
  1897. }
  1898. if v, ok := extra["sessionIDKey"].(string); ok && len(v) > 0 {
  1899. extra["sessionKey"] = v
  1900. }
  1901. for _, field := range []string{"uplinkChunkSize"} {
  1902. if v, ok := nonZeroShareValue(xhttp[field]); ok {
  1903. extra[field] = v
  1904. }
  1905. }
  1906. for _, field := range []string{"noGRPCHeader"} {
  1907. if v, ok := xhttp[field].(bool); ok && v {
  1908. extra[field] = v
  1909. }
  1910. }
  1911. for _, field := range []string{"xmux", "downloadSettings"} {
  1912. if v, ok := nonEmptyShareObject(xhttp[field]); ok {
  1913. extra[field] = v
  1914. }
  1915. }
  1916. // Headers — emitted as the {name: value} map upstream's struct
  1917. // expects. The server runtime ignores this field, but the client
  1918. // (consuming the share link) honors it. Drop any "host" entry —
  1919. // host already wins as a top-level URL param.
  1920. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  1921. out := map[string]any{}
  1922. for k, v := range rawHeaders {
  1923. if strings.EqualFold(k, "host") {
  1924. continue
  1925. }
  1926. out[k] = v
  1927. }
  1928. if len(out) > 0 {
  1929. extra["headers"] = out
  1930. }
  1931. }
  1932. if len(extra) == 0 {
  1933. return nil
  1934. }
  1935. return extra
  1936. }
  1937. func nonZeroShareValue(v any) (any, bool) {
  1938. switch value := v.(type) {
  1939. case string:
  1940. return value, value != ""
  1941. case int:
  1942. return value, value != 0
  1943. case int32:
  1944. return value, value != 0
  1945. case int64:
  1946. return value, value != 0
  1947. case float32:
  1948. return value, value != 0
  1949. case float64:
  1950. return value, value != 0
  1951. default:
  1952. return nil, false
  1953. }
  1954. }
  1955. func nonEmptyShareObject(v any) (any, bool) {
  1956. switch value := v.(type) {
  1957. case map[string]any:
  1958. return value, len(value) > 0
  1959. case map[string]string:
  1960. return value, len(value) > 0
  1961. case []any:
  1962. return value, len(value) > 0
  1963. default:
  1964. return nil, false
  1965. }
  1966. }
  1967. // applyXhttpExtraParams emits the full xhttp config into the URL query
  1968. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  1969. // top level (xray's Build() always lets these win over `extra`) and packs
  1970. // everything else into a JSON `extra` param. Also writes the flat
  1971. // `x_padding_bytes` param sing-box-family clients understand.
  1972. //
  1973. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  1974. // reach the client and handshakes are silently rejected with
  1975. // `invalid padding (...) length: 0` — the client-visible symptom is
  1976. // "xhttp doesn't connect" on OpenWRT / sing-box.
  1977. //
  1978. // Two encodings are written so every popular client can read at least one:
  1979. //
  1980. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  1981. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  1982. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  1983. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  1984. // bidirectional fields beyond path/host/mode.
  1985. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  1986. if xhttp == nil {
  1987. return
  1988. }
  1989. applyPathAndHostParams(xhttp, params)
  1990. if mode, ok := xhttp["mode"].(string); ok {
  1991. params["mode"] = mode
  1992. }
  1993. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1994. params["x_padding_bytes"] = xpb
  1995. }
  1996. extra := buildXhttpExtra(xhttp)
  1997. if extra != nil {
  1998. if b, err := json.Marshal(extra); err == nil {
  1999. params["extra"] = string(b)
  2000. }
  2001. }
  2002. }
  2003. var kcpMaskToHeaderType = map[string]string{
  2004. "dns": "dns",
  2005. "dtls": "dtls",
  2006. "srtp": "srtp",
  2007. "utp": "utp",
  2008. "wechat": "wechat-video",
  2009. "wireguard": "wireguard",
  2010. }
  2011. var validFinalMaskUDPTypes = map[string]struct{}{
  2012. "salamander": {},
  2013. "mkcp-legacy": {},
  2014. "xdns": {},
  2015. "xicmp": {},
  2016. "noise": {},
  2017. "header-custom": {},
  2018. "realm": {},
  2019. }
  2020. var validFinalMaskTCPTypes = map[string]struct{}{
  2021. "header-custom": {},
  2022. "fragment": {},
  2023. "sudoku": {},
  2024. "xmc": {},
  2025. }
  2026. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  2027. // the historical kcpSettings.header/seed shape or the current finalmask model.
  2028. // This keeps subscription output compatible while avoiding panics when older
  2029. // keys are absent from modern inbounds.
  2030. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  2031. extractKcpShareFields(stream).applyToParams(params)
  2032. }
  2033. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  2034. extractKcpShareFields(stream).applyToObj(obj)
  2035. }
  2036. type kcpShareFields struct {
  2037. headerType string
  2038. seed string
  2039. mtu int
  2040. tti int
  2041. }
  2042. func (f kcpShareFields) applyToParams(params map[string]string) {
  2043. if f.headerType != "" && f.headerType != "none" {
  2044. params["headerType"] = f.headerType
  2045. }
  2046. setStringParam(params, "seed", f.seed)
  2047. setIntParam(params, "mtu", f.mtu)
  2048. setIntParam(params, "tti", f.tti)
  2049. }
  2050. func (f kcpShareFields) applyToObj(obj map[string]any) {
  2051. if f.headerType != "" && f.headerType != "none" {
  2052. obj["type"] = f.headerType
  2053. }
  2054. setStringField(obj, "path", f.seed)
  2055. setIntField(obj, "mtu", f.mtu)
  2056. setIntField(obj, "tti", f.tti)
  2057. }
  2058. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  2059. fields := kcpShareFields{headerType: "none"}
  2060. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  2061. if header, ok := kcp["header"].(map[string]any); ok {
  2062. if value, ok := header["type"].(string); ok && value != "" {
  2063. fields.headerType = value
  2064. }
  2065. }
  2066. if value, ok := kcp["seed"].(string); ok && value != "" {
  2067. fields.seed = value
  2068. }
  2069. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  2070. fields.mtu = value
  2071. }
  2072. if value, ok := readPositiveInt(kcp["tti"]); ok {
  2073. fields.tti = value
  2074. }
  2075. }
  2076. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  2077. mask, _ := rawMask.(map[string]any)
  2078. if mask == nil {
  2079. continue
  2080. }
  2081. if maskType, _ := mask["type"].(string); maskType != "mkcp-legacy" {
  2082. continue
  2083. }
  2084. settings, _ := mask["settings"].(map[string]any)
  2085. header, _ := settings["header"].(string)
  2086. value, _ := settings["value"].(string)
  2087. if header == "" {
  2088. fields.seed = value
  2089. continue
  2090. }
  2091. if mapped, ok := kcpMaskToHeaderType[header]; ok {
  2092. fields.headerType = mapped
  2093. }
  2094. }
  2095. return fields
  2096. }
  2097. func readPositiveInt(value any) (int, bool) {
  2098. switch number := value.(type) {
  2099. case int:
  2100. return number, number > 0
  2101. case int32:
  2102. return int(number), number > 0
  2103. case int64:
  2104. return int(number), number > 0
  2105. case float32:
  2106. parsed := int(number)
  2107. return parsed, parsed > 0
  2108. case float64:
  2109. parsed := int(number)
  2110. return parsed, parsed > 0
  2111. default:
  2112. return 0, false
  2113. }
  2114. }
  2115. func setStringParam(params map[string]string, key, value string) {
  2116. if value == "" {
  2117. delete(params, key)
  2118. return
  2119. }
  2120. params[key] = value
  2121. }
  2122. func setIntParam(params map[string]string, key string, value int) {
  2123. if value <= 0 {
  2124. delete(params, key)
  2125. return
  2126. }
  2127. params[key] = fmt.Sprintf("%d", value)
  2128. }
  2129. func setStringField(obj map[string]any, key, value string) {
  2130. if value == "" {
  2131. delete(obj, key)
  2132. return
  2133. }
  2134. obj[key] = value
  2135. }
  2136. func setIntField(obj map[string]any, key string, value int) {
  2137. if value <= 0 {
  2138. delete(obj, key)
  2139. return
  2140. }
  2141. obj[key] = value
  2142. }
  2143. // applyFinalMaskParams exports the finalmask payload as the compact
  2144. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  2145. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  2146. if fm, ok := marshalFinalMask(finalmask); ok {
  2147. params["fm"] = fm
  2148. }
  2149. }
  2150. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  2151. if fm, ok := marshalFinalMask(finalmask); ok {
  2152. obj["fm"] = fm
  2153. }
  2154. }
  2155. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  2156. normalized := normalizeFinalMask(finalmask)
  2157. if !hasFinalMaskContent(normalized) {
  2158. return "", false
  2159. }
  2160. b, err := json.Marshal(normalized)
  2161. if err != nil || len(b) == 0 || string(b) == "null" {
  2162. return "", false
  2163. }
  2164. return string(b), true
  2165. }
  2166. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  2167. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  2168. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  2169. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  2170. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  2171. return nil
  2172. }
  2173. result := map[string]any{}
  2174. if len(tcpMasks) > 0 {
  2175. result["tcp"] = tcpMasks
  2176. }
  2177. if len(udpMasks) > 0 {
  2178. result["udp"] = udpMasks
  2179. }
  2180. if hasQuicParams && len(quicParams) > 0 {
  2181. result["quicParams"] = quicParams
  2182. }
  2183. return result
  2184. }
  2185. func normalizedFinalMaskTCPMasks(value any) []any {
  2186. finalmask, _ := value.(map[string]any)
  2187. if finalmask == nil {
  2188. return nil
  2189. }
  2190. rawMasks, _ := finalmask["tcp"].([]any)
  2191. if len(rawMasks) == 0 {
  2192. return nil
  2193. }
  2194. normalized := make([]any, 0, len(rawMasks))
  2195. for _, rawMask := range rawMasks {
  2196. mask, _ := rawMask.(map[string]any)
  2197. if mask == nil {
  2198. continue
  2199. }
  2200. maskType, _ := mask["type"].(string)
  2201. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  2202. continue
  2203. }
  2204. normalizedMask := map[string]any{"type": maskType}
  2205. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  2206. normalizedMask["settings"] = settings
  2207. }
  2208. normalized = append(normalized, normalizedMask)
  2209. }
  2210. if len(normalized) == 0 {
  2211. return nil
  2212. }
  2213. return normalized
  2214. }
  2215. func normalizedFinalMaskUDPMasks(value any) []any {
  2216. finalmask, _ := value.(map[string]any)
  2217. if finalmask == nil {
  2218. return nil
  2219. }
  2220. rawMasks, _ := finalmask["udp"].([]any)
  2221. if len(rawMasks) == 0 {
  2222. return nil
  2223. }
  2224. normalized := make([]any, 0, len(rawMasks))
  2225. for _, rawMask := range rawMasks {
  2226. mask, _ := rawMask.(map[string]any)
  2227. if mask == nil {
  2228. continue
  2229. }
  2230. maskType, _ := mask["type"].(string)
  2231. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  2232. continue
  2233. }
  2234. normalizedMask := map[string]any{"type": maskType}
  2235. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  2236. normalizedMask["settings"] = settings
  2237. }
  2238. normalized = append(normalized, normalizedMask)
  2239. }
  2240. if len(normalized) == 0 {
  2241. return nil
  2242. }
  2243. return normalized
  2244. }
  2245. func hasFinalMaskContent(value any) bool {
  2246. switch v := value.(type) {
  2247. case nil:
  2248. return false
  2249. case string:
  2250. return len(v) > 0
  2251. case map[string]any:
  2252. for _, item := range v {
  2253. if hasFinalMaskContent(item) {
  2254. return true
  2255. }
  2256. }
  2257. return false
  2258. case []any:
  2259. return slices.ContainsFunc(v, hasFinalMaskContent)
  2260. default:
  2261. return true
  2262. }
  2263. }
  2264. func searchHost(headers any) string {
  2265. data, _ := headers.(map[string]any)
  2266. for k, v := range data {
  2267. if strings.EqualFold(k, "host") {
  2268. switch v.(type) {
  2269. case []any:
  2270. hosts, _ := v.([]any)
  2271. if len(hosts) > 0 {
  2272. h, _ := hosts[0].(string)
  2273. return h
  2274. }
  2275. return ""
  2276. case any:
  2277. h, _ := v.(string)
  2278. return h
  2279. }
  2280. }
  2281. }
  2282. return ""
  2283. }
  2284. // PageData is a view model for subpage.html
  2285. // PageData contains data for rendering the subscription information page.
  2286. type PageData struct {
  2287. Host string
  2288. BasePath string
  2289. SId string
  2290. Enabled bool
  2291. IsOnline bool
  2292. Download string
  2293. Upload string
  2294. Total string
  2295. Used string
  2296. Remained string
  2297. Expire int64
  2298. LastOnline int64
  2299. Datepicker string
  2300. DownloadByte int64
  2301. UploadByte int64
  2302. TotalByte int64
  2303. SubUrl string
  2304. SubJsonUrl string
  2305. SubClashUrl string
  2306. SubTitle string
  2307. SubSupportUrl string
  2308. Result []string
  2309. Emails []string
  2310. }
  2311. // ResolveRequest extracts scheme and host info from request/headers consistently.
  2312. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  2313. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  2314. trusted := s.forwardedHeadersTrusted(c)
  2315. if !trusted {
  2316. warnSuppressedForwardedHeaders(c)
  2317. }
  2318. forwarded := func(name string) string {
  2319. if !trusted {
  2320. return ""
  2321. }
  2322. return c.GetHeader(name)
  2323. }
  2324. // scheme
  2325. scheme = "http"
  2326. if c.Request.TLS != nil || strings.EqualFold(forwarded("X-Forwarded-Proto"), "https") {
  2327. scheme = "https"
  2328. }
  2329. // base host (no port)
  2330. if h, err := getHostFromXFH(forwarded("X-Forwarded-Host")); err == nil && h != "" {
  2331. host = h
  2332. }
  2333. if host == "" {
  2334. host = forwarded("X-Real-IP")
  2335. }
  2336. if host == "" {
  2337. var err error
  2338. host, _, err = net.SplitHostPort(c.Request.Host)
  2339. if err != nil {
  2340. host = c.Request.Host
  2341. }
  2342. }
  2343. // host:port for URLs
  2344. hostWithPort = forwarded("X-Forwarded-Host")
  2345. if hostWithPort == "" {
  2346. hostWithPort = c.Request.Host
  2347. }
  2348. if hostWithPort == "" {
  2349. hostWithPort = host
  2350. }
  2351. // header display host
  2352. hostHeader = forwarded("X-Forwarded-Host")
  2353. if hostHeader == "" {
  2354. hostHeader = forwarded("X-Real-IP")
  2355. }
  2356. if hostHeader == "" {
  2357. hostHeader = host
  2358. }
  2359. return
  2360. }
  2361. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  2362. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  2363. func (s *SubService) BuildURLs(subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  2364. if subId == "" {
  2365. return "", "", ""
  2366. }
  2367. configuredSubURI, _ := s.settingService.GetSubURI()
  2368. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  2369. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  2370. // Same base as the panel's Client Information page; s.address is the
  2371. // subscriber's host already normalized away from any loopback/bind IP.
  2372. base := s.settingService.BuildSubURIBase(s.address)
  2373. subURL = s.buildSingleURL(configuredSubURI, base, subPath, subId)
  2374. // When subURI is explicitly configured (reverse-proxy setup), use its
  2375. // scheme+host as the base for JSON and Clash URLs so they match the
  2376. // reverse-proxy endpoint instead of the raw sub-server port. Fall back
  2377. // to the request-derived base if subURI is empty or can't be parsed
  2378. // into a scheme+host (e.g. a malformed value with no scheme).
  2379. jsonClashBase := base
  2380. if configuredSubURI != "" {
  2381. if derived := s.extractBaseFromURI(configuredSubURI); derived != "" {
  2382. jsonClashBase = derived
  2383. }
  2384. }
  2385. subJsonURL = s.buildSingleURL(configuredSubJsonURI, jsonClashBase, subJsonPath, subId)
  2386. subClashURL = s.buildSingleURL(configuredSubClashURI, jsonClashBase, subClashPath, subId)
  2387. return subURL, subJsonURL, subClashURL
  2388. }
  2389. // extractBaseFromURI extracts scheme://host from a configured URI.
  2390. // e.g., "https://example.com/sub-xxx/" → "https://example.com".
  2391. // Returns "" when the URI is empty or lacks a scheme/host, so callers can
  2392. // fall back to the request-derived base instead of emitting a broken value.
  2393. func (s *SubService) extractBaseFromURI(uri string) string {
  2394. u, err := url.Parse(uri)
  2395. if err != nil || u.Scheme == "" || u.Host == "" {
  2396. return ""
  2397. }
  2398. return fmt.Sprintf("%s://%s", u.Scheme, u.Host)
  2399. }
  2400. // buildSingleURL constructs a single URL using configured URI or base components
  2401. func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string {
  2402. if configuredURI != "" {
  2403. return s.joinPathWithID(configuredURI, subId)
  2404. }
  2405. return s.joinPathWithID(base+basePath, subId)
  2406. }
  2407. // joinPathWithID safely joins a base path with a subscription ID
  2408. func (s *SubService) joinPathWithID(basePath, subId string) string {
  2409. if strings.HasSuffix(basePath, "/") {
  2410. return basePath + subId
  2411. }
  2412. return basePath + "/" + subId
  2413. }
  2414. // BuildPageData parses header and prepares the template view model.
  2415. // BuildPageData constructs page data for rendering the subscription information page.
  2416. func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray.ClientTraffic, lastOnline int64, subs []string, emails []string, subURL, subJsonURL, subClashURL string, basePath string, subTitle string, subSupportUrl string) PageData {
  2417. download := common.FormatTraffic(traffic.Down)
  2418. upload := common.FormatTraffic(traffic.Up)
  2419. total := "∞"
  2420. used := common.FormatTraffic(traffic.Up + traffic.Down)
  2421. remained := ""
  2422. if traffic.Total > 0 {
  2423. total = common.FormatTraffic(traffic.Total)
  2424. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  2425. remained = common.FormatTraffic(left)
  2426. }
  2427. datepicker := s.datepicker
  2428. if datepicker == "" {
  2429. datepicker = "gregorian"
  2430. }
  2431. pageLinks := make([]string, 0, len(subs))
  2432. pageEmails := make([]string, 0, len(subs))
  2433. for i, sub := range subs {
  2434. email := ""
  2435. if i < len(emails) {
  2436. email = emails[i]
  2437. }
  2438. for _, link := range splitLinkLines(sub) {
  2439. pageLinks = append(pageLinks, link)
  2440. pageEmails = append(pageEmails, email)
  2441. }
  2442. }
  2443. return PageData{
  2444. Host: hostHeader,
  2445. BasePath: basePath,
  2446. SId: subId,
  2447. Enabled: traffic.Enable,
  2448. IsOnline: subIsOnline(emails, s.inboundService.GetOnlineClients()),
  2449. Download: download,
  2450. Upload: upload,
  2451. Total: total,
  2452. Used: used,
  2453. Remained: remained,
  2454. Expire: traffic.ExpiryTime / 1000,
  2455. LastOnline: lastOnline,
  2456. Datepicker: datepicker,
  2457. DownloadByte: traffic.Down,
  2458. UploadByte: traffic.Up,
  2459. TotalByte: traffic.Total,
  2460. SubUrl: subURL,
  2461. SubJsonUrl: subJsonURL,
  2462. SubClashUrl: subClashURL,
  2463. SubTitle: subTitle,
  2464. SubSupportUrl: subSupportUrl,
  2465. Result: pageLinks,
  2466. Emails: pageEmails,
  2467. }
  2468. }
  2469. func subIsOnline(subEmails, onlineEmails []string) bool {
  2470. if len(subEmails) == 0 || len(onlineEmails) == 0 {
  2471. return false
  2472. }
  2473. onlineSet := make(map[string]struct{}, len(onlineEmails))
  2474. for _, email := range onlineEmails {
  2475. onlineSet[email] = struct{}{}
  2476. }
  2477. for _, email := range subEmails {
  2478. if _, online := onlineSet[email]; online {
  2479. return true
  2480. }
  2481. }
  2482. return false
  2483. }
  2484. func getHostFromXFH(s string) (string, error) {
  2485. if strings.Contains(s, ":") {
  2486. realHost, _, err := net.SplitHostPort(s)
  2487. if err != nil {
  2488. return "", err
  2489. }
  2490. return realHost, nil
  2491. }
  2492. return s, nil
  2493. }