service.go 77 KB

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