1
0

service.go 70 KB

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