1
0

service.go 84 KB

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