1
0

service.go 71 KB

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