1
0

service.go 82 KB

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