1
0

service.go 77 KB

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