service.go 83 KB

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