service.go 75 KB

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