service.go 71 KB

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