service.go 73 KB

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