1
0

subService.go 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "maps"
  6. "net"
  7. "net/url"
  8. "slices"
  9. "strings"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. "github.com/goccy/go-json"
  13. "github.com/mhsanaei/3x-ui/v3/database"
  14. "github.com/mhsanaei/3x-ui/v3/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/util/random"
  18. "github.com/mhsanaei/3x-ui/v3/web/service"
  19. "github.com/mhsanaei/3x-ui/v3/xray"
  20. )
  21. // SubService provides business logic for generating subscription links and managing subscription data.
  22. type SubService struct {
  23. address string
  24. showInfo bool
  25. remarkModel string
  26. datepicker string
  27. emailInRemark bool
  28. inboundService service.InboundService
  29. settingService service.SettingService
  30. // nodesByID is populated per request from the Node table so
  31. // resolveInboundAddress can return the node's address for any
  32. // inbound whose NodeID is set. Keeps the per-link host derivation
  33. // O(1) instead of O(N) DB hits.
  34. nodesByID map[int]*model.Node
  35. }
  36. // NewSubService creates a new subscription service with the given configuration.
  37. func NewSubService(showInfo bool, remarkModel string) *SubService {
  38. return &SubService{
  39. showInfo: showInfo,
  40. remarkModel: remarkModel,
  41. }
  42. }
  43. // PrepareForRequest sets per-request state (host + nodes map) on the
  44. // shared SubService. Called by every entry point — GetSubs, GetJson,
  45. // GetClash — so resolveInboundAddress sees the right host and the
  46. // freshly-loaded node map regardless of which sub flavour the client
  47. // hit.
  48. func (s *SubService) PrepareForRequest(host string) {
  49. if !isRoutableHost(host) {
  50. if d := s.configuredPublicHost(); d != "" {
  51. host = d
  52. } else if isLoopbackHost(host) {
  53. host = "localhost"
  54. }
  55. }
  56. s.address = host
  57. s.loadNodes()
  58. }
  59. func (s *SubService) configuredPublicHost() string {
  60. if d, err := s.settingService.GetSubDomain(); err == nil && d != "" {
  61. return d
  62. }
  63. if d, err := s.settingService.GetWebDomain(); err == nil && d != "" {
  64. return d
  65. }
  66. return ""
  67. }
  68. func isRoutableHost(host string) bool {
  69. if host == "" {
  70. return false
  71. }
  72. if ip := net.ParseIP(strings.Trim(host, "[]")); ip != nil {
  73. return !ip.IsLoopback() && !ip.IsUnspecified()
  74. }
  75. return true
  76. }
  77. func isLoopbackHost(host string) bool {
  78. ip := net.ParseIP(strings.Trim(host, "[]"))
  79. return ip != nil && ip.IsLoopback()
  80. }
  81. // GetSubs retrieves subscription links for a given subscription ID and host.
  82. func (s *SubService) GetSubs(subId string, host string) ([]string, []string, int64, xray.ClientTraffic, error) {
  83. s.PrepareForRequest(host)
  84. var result []string
  85. var emails []string
  86. var traffic xray.ClientTraffic
  87. var hasEnabledClient bool
  88. inbounds, err := s.getInboundsBySubId(subId)
  89. if err != nil {
  90. return nil, nil, 0, traffic, err
  91. }
  92. if len(inbounds) == 0 {
  93. return nil, nil, 0, traffic, nil
  94. }
  95. s.datepicker, err = s.settingService.GetDatepicker()
  96. if err != nil {
  97. s.datepicker = "gregorian"
  98. }
  99. s.emailInRemark, err = s.settingService.GetSubEmailInRemark()
  100. if err != nil {
  101. s.emailInRemark = true
  102. }
  103. seenEmails := make(map[string]struct{})
  104. for _, inbound := range inbounds {
  105. clients, err := s.inboundService.GetClients(inbound)
  106. if err != nil {
  107. logger.Error("SubService - GetClients: Unable to get clients from inbound")
  108. }
  109. if clients == nil {
  110. continue
  111. }
  112. s.projectThroughFallbackMaster(inbound)
  113. for _, client := range clients {
  114. if client.SubID == subId {
  115. if client.Enable {
  116. hasEnabledClient = true
  117. }
  118. result = append(result, s.GetLink(inbound, client.Email))
  119. emails = append(emails, client.Email)
  120. seenEmails[client.Email] = struct{}{}
  121. }
  122. }
  123. }
  124. uniqueEmails := make([]string, 0, len(seenEmails))
  125. for e := range seenEmails {
  126. uniqueEmails = append(uniqueEmails, e)
  127. }
  128. traffic, lastOnline := s.AggregateTrafficByEmails(uniqueEmails)
  129. traffic.Enable = hasEnabledClient
  130. return result, emails, lastOnline, traffic, nil
  131. }
  132. // AggregateTrafficByEmails resolves traffic for every email in one
  133. // query and folds the rows into a single ClientTraffic + lastOnline.
  134. // xray.ClientTraffic.Email is globally unique, so a multi-inbound
  135. // client's single row is attached to exactly one inbound — iterating
  136. // per-inbound ClientStats would miss it on the others. Used by GetSubs,
  137. // SubClashService.GetClash, and SubJsonService.GetJson to keep the
  138. // sub-info header consistent across all three formats.
  139. func (s *SubService) AggregateTrafficByEmails(emails []string) (xray.ClientTraffic, int64) {
  140. var agg xray.ClientTraffic
  141. var lastOnline int64
  142. if len(emails) == 0 {
  143. return agg, 0
  144. }
  145. db := database.GetDB()
  146. var rows []xray.ClientTraffic
  147. if err := db.
  148. Model(&xray.ClientTraffic{}).
  149. Where("email IN ?", emails).
  150. Find(&rows).Error; err != nil {
  151. logger.Warning("SubService - AggregateTrafficByEmails: load by email:", err)
  152. return agg, 0
  153. }
  154. // total/expiry are configured limits owned by the clients table, not the
  155. // runtime traffic rows. In a multi-node setup the node snapshot can reset
  156. // client_traffics.total/expiry_time to 0, so fall back to the clients
  157. // table to keep the Subscription-Userinfo header in sync with the UI (#4645).
  158. limits := make(map[string][2]int64, len(emails))
  159. var records []model.ClientRecord
  160. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails).Find(&records).Error; err != nil {
  161. logger.Warning("SubService - AggregateTrafficByEmails: load client limits:", err)
  162. } else {
  163. for _, r := range records {
  164. limits[r.Email] = [2]int64{r.TotalGB, r.ExpiryTime}
  165. }
  166. }
  167. now := time.Now().UnixMilli()
  168. first := true
  169. for _, ct := range rows {
  170. if ct.LastOnline > lastOnline {
  171. lastOnline = ct.LastOnline
  172. }
  173. total, expiry := ct.Total, ct.ExpiryTime
  174. if lim, ok := limits[ct.Email]; ok {
  175. if total == 0 {
  176. total = lim[0]
  177. }
  178. if expiry == 0 {
  179. expiry = lim[1]
  180. }
  181. }
  182. if first {
  183. agg.Up = ct.Up
  184. agg.Down = ct.Down
  185. agg.Total = total
  186. agg.ExpiryTime = subscriptionExpiryFromClient(now, expiry)
  187. first = false
  188. continue
  189. }
  190. agg.Up += ct.Up
  191. agg.Down += ct.Down
  192. if agg.Total == 0 || total == 0 {
  193. agg.Total = 0
  194. } else {
  195. agg.Total += total
  196. }
  197. normalized := subscriptionExpiryFromClient(now, expiry)
  198. if normalized != agg.ExpiryTime {
  199. agg.ExpiryTime = 0
  200. }
  201. }
  202. return agg, lastOnline
  203. }
  204. func subscriptionExpiryFromClient(nowMs, expiryTime int64) int64 {
  205. if expiryTime > 0 {
  206. return expiryTime
  207. }
  208. if expiryTime < 0 {
  209. return nowMs + (-expiryTime)
  210. }
  211. return 0
  212. }
  213. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  214. db := database.GetDB()
  215. var inbounds []*model.Inbound
  216. err := db.Model(model.Inbound{}).Preload("ClientStats").Where(`id in (
  217. SELECT DISTINCT inbounds.id
  218. FROM inbounds
  219. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  220. JOIN clients ON clients.id = client_inbounds.client_id
  221. WHERE
  222. inbounds.protocol in ('vmess','vless','trojan','shadowsocks','hysteria')
  223. AND clients.sub_id = ? AND inbounds.enable = ?
  224. )`, subId, true).Find(&inbounds).Error
  225. if err != nil {
  226. return nil, err
  227. }
  228. return inbounds, nil
  229. }
  230. // projectThroughFallbackMaster mutates the inbound in place so its
  231. // Listen/Port/StreamSettings reflect the externally reachable master
  232. // when applicable. Covers both fallback mechanisms:
  233. // - panel-tracked: an inbound_fallbacks row where child_id = inbound.Id
  234. // - legacy unix-socket: inbound.Listen begins with "@" and some VLESS/
  235. // Trojan inbound's settings.fallbacks references that listen address
  236. //
  237. // Returns true when a projection happened; sub services call this before
  238. // generating links so a child VLESS-WS bound to 127.0.0.1 emits the
  239. // master's :443 + TLS state instead of its own loopback endpoint.
  240. func (s *SubService) projectThroughFallbackMaster(inbound *model.Inbound) bool {
  241. if inbound == nil {
  242. return false
  243. }
  244. db := database.GetDB()
  245. var master *model.Inbound
  246. var rule model.InboundFallback
  247. if err := db.Where("child_id = ?", inbound.Id).
  248. Order("sort_order ASC, id ASC").
  249. First(&rule).Error; err == nil {
  250. var m model.Inbound
  251. if err := db.Where("id = ?", rule.MasterId).First(&m).Error; err == nil {
  252. master = &m
  253. }
  254. }
  255. if master == nil && len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  256. var m model.Inbound
  257. if err := db.Model(model.Inbound{}).
  258. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  259. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", inbound.Listen).
  260. First(&m).Error; err == nil {
  261. master = &m
  262. }
  263. }
  264. if master == nil {
  265. return false
  266. }
  267. inbound.StreamSettings = mergeStreamFromMaster(inbound.StreamSettings, master.StreamSettings)
  268. inbound.Listen = master.Listen
  269. inbound.Port = master.Port
  270. return true
  271. }
  272. // mergeStreamFromMaster copies the master's security + tlsSettings +
  273. // realitySettings + externalProxy onto the child's stream so the child's
  274. // link advertises the master's TLS / Reality state. Transport (network
  275. // + ws/grpc/etc. settings) stays the child's.
  276. func mergeStreamFromMaster(childStream, masterStream string) string {
  277. var stream map[string]any
  278. json.Unmarshal([]byte(childStream), &stream)
  279. if stream == nil {
  280. stream = map[string]any{}
  281. }
  282. var mst map[string]any
  283. json.Unmarshal([]byte(masterStream), &mst)
  284. if mst == nil {
  285. return childStream
  286. }
  287. stream["security"] = mst["security"]
  288. if v, ok := mst["tlsSettings"]; ok {
  289. stream["tlsSettings"] = v
  290. } else {
  291. delete(stream, "tlsSettings")
  292. }
  293. if v, ok := mst["realitySettings"]; ok {
  294. stream["realitySettings"] = v
  295. } else {
  296. delete(stream, "realitySettings")
  297. }
  298. if v, ok := mst["externalProxy"]; ok {
  299. stream["externalProxy"] = v
  300. }
  301. out, err := json.MarshalIndent(stream, "", " ")
  302. if err != nil {
  303. return childStream
  304. }
  305. return string(out)
  306. }
  307. // GetLink dispatches to the protocol-specific generator for one (inbound, client)
  308. // pair. Returns "" when the inbound's protocol doesn't produce a subscription URL
  309. // (socks, http, mixed, wireguard, dokodemo, tunnel). The returned string may
  310. // contain multiple `\n`-separated URLs when the inbound has externalProxy set.
  311. func (s *SubService) GetLink(inbound *model.Inbound, email string) string {
  312. switch inbound.Protocol {
  313. case "vmess":
  314. return s.genVmessLink(inbound, email)
  315. case "vless":
  316. return s.genVlessLink(inbound, email)
  317. case "trojan":
  318. return s.genTrojanLink(inbound, email)
  319. case "shadowsocks":
  320. return s.genShadowsocksLink(inbound, email)
  321. case "hysteria":
  322. return s.genHysteriaLink(inbound, email)
  323. }
  324. return ""
  325. }
  326. // Protocol link generators are intentionally ordered as:
  327. // vmess -> vless -> trojan -> shadowsocks -> hysteria.
  328. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  329. if inbound.Protocol != model.VMESS {
  330. return ""
  331. }
  332. address := s.resolveInboundAddress(inbound)
  333. obj := map[string]any{
  334. "v": "2",
  335. "add": address,
  336. "port": inbound.Port,
  337. "type": "none",
  338. }
  339. stream := unmarshalStreamSettings(inbound.StreamSettings)
  340. network, _ := stream["network"].(string)
  341. applyVmessNetworkParams(stream, network, obj)
  342. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  343. applyFinalMaskObj(finalmask, obj)
  344. }
  345. security, _ := stream["security"].(string)
  346. obj["tls"] = security
  347. if security == "tls" {
  348. applyVmessTLSParams(stream, obj)
  349. }
  350. clients, _ := s.inboundService.GetClients(inbound)
  351. clientIndex := findClientIndex(clients, email)
  352. obj["id"] = clients[clientIndex].ID
  353. obj["scy"] = clients[clientIndex].Security
  354. externalProxies, _ := stream["externalProxy"].([]any)
  355. if len(externalProxies) > 0 {
  356. return s.buildVmessExternalProxyLinks(externalProxies, obj, inbound, email)
  357. }
  358. obj["ps"] = s.genRemark(inbound, email, "")
  359. return buildVmessLink(obj)
  360. }
  361. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  362. if inbound.Protocol != model.VLESS {
  363. return ""
  364. }
  365. address := s.resolveInboundAddress(inbound)
  366. stream := unmarshalStreamSettings(inbound.StreamSettings)
  367. clients, _ := s.inboundService.GetClients(inbound)
  368. clientIndex := findClientIndex(clients, email)
  369. uuid := clients[clientIndex].ID
  370. port := inbound.Port
  371. streamNetwork := stream["network"].(string)
  372. params := make(map[string]string)
  373. params["type"] = streamNetwork
  374. // Add encryption parameter for VLESS from inbound settings
  375. var settings map[string]any
  376. json.Unmarshal([]byte(inbound.Settings), &settings)
  377. if encryption, ok := settings["encryption"].(string); ok {
  378. params["encryption"] = encryption
  379. }
  380. applyShareNetworkParams(stream, streamNetwork, params)
  381. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  382. applyFinalMaskParams(finalmask, params)
  383. }
  384. security, _ := stream["security"].(string)
  385. switch security {
  386. case "tls":
  387. applyShareTLSParams(stream, params)
  388. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  389. params["flow"] = clients[clientIndex].Flow
  390. }
  391. case "reality":
  392. applyShareRealityParams(stream, params)
  393. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  394. params["flow"] = clients[clientIndex].Flow
  395. }
  396. default:
  397. params["security"] = "none"
  398. }
  399. externalProxies, _ := stream["externalProxy"].([]any)
  400. if len(externalProxies) > 0 {
  401. return s.buildExternalProxyURLLinks(
  402. externalProxies,
  403. params,
  404. security,
  405. func(dest string, port int) string {
  406. return fmt.Sprintf("vless://%s@%s:%d", uuid, dest, port)
  407. },
  408. func(ep map[string]any) string {
  409. return s.genRemark(inbound, email, ep["remark"].(string))
  410. },
  411. )
  412. }
  413. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  414. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  415. }
  416. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  417. if inbound.Protocol != model.Trojan {
  418. return ""
  419. }
  420. address := s.resolveInboundAddress(inbound)
  421. stream := unmarshalStreamSettings(inbound.StreamSettings)
  422. clients, _ := s.inboundService.GetClients(inbound)
  423. clientIndex := findClientIndex(clients, email)
  424. password := encodeUserinfo(clients[clientIndex].Password)
  425. port := inbound.Port
  426. streamNetwork := stream["network"].(string)
  427. params := make(map[string]string)
  428. params["type"] = streamNetwork
  429. applyShareNetworkParams(stream, streamNetwork, params)
  430. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  431. applyFinalMaskParams(finalmask, params)
  432. }
  433. security, _ := stream["security"].(string)
  434. switch security {
  435. case "tls":
  436. applyShareTLSParams(stream, params)
  437. case "reality":
  438. applyShareRealityParams(stream, params)
  439. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  440. params["flow"] = clients[clientIndex].Flow
  441. }
  442. default:
  443. params["security"] = "none"
  444. }
  445. externalProxies, _ := stream["externalProxy"].([]any)
  446. if len(externalProxies) > 0 {
  447. return s.buildExternalProxyURLLinks(
  448. externalProxies,
  449. params,
  450. security,
  451. func(dest string, port int) string {
  452. return fmt.Sprintf("trojan://%s@%s:%d", password, dest, port)
  453. },
  454. func(ep map[string]any) string {
  455. return s.genRemark(inbound, email, ep["remark"].(string))
  456. },
  457. )
  458. }
  459. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  460. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  461. }
  462. // encodeUserinfo percent-encodes a userinfo (password/auth) value so it
  463. // can be safely embedded in a `scheme://<value>@host:port` URL. RFC 3986
  464. // allows `=` in userinfo as a sub-delim, but several Trojan and Hysteria
  465. // clients reject share-links where the password contains literal `/`
  466. // or `=` (notably the common base64-with-padding shape produced by the
  467. // panel). Encode them too — this matches encodeURIComponent() on the
  468. // frontend and round-trips cleanly through net/url's parser.
  469. func encodeUserinfo(s string) string {
  470. return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
  471. }
  472. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  473. if inbound.Protocol != model.Shadowsocks {
  474. return ""
  475. }
  476. address := s.resolveInboundAddress(inbound)
  477. stream := unmarshalStreamSettings(inbound.StreamSettings)
  478. clients, _ := s.inboundService.GetClients(inbound)
  479. var settings map[string]any
  480. json.Unmarshal([]byte(inbound.Settings), &settings)
  481. inboundPassword := settings["password"].(string)
  482. method := settings["method"].(string)
  483. clientIndex := findClientIndex(clients, email)
  484. streamNetwork := stream["network"].(string)
  485. params := make(map[string]string)
  486. params["type"] = streamNetwork
  487. applyShareNetworkParams(stream, streamNetwork, params)
  488. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  489. applyFinalMaskParams(finalmask, params)
  490. }
  491. security, _ := stream["security"].(string)
  492. if security == "tls" {
  493. applyShareTLSParams(stream, params)
  494. }
  495. encPart := fmt.Sprintf("%s:%s", method, clients[clientIndex].Password)
  496. if method[0] == '2' {
  497. encPart = fmt.Sprintf("%s:%s:%s", method, inboundPassword, clients[clientIndex].Password)
  498. }
  499. externalProxies, _ := stream["externalProxy"].([]any)
  500. if len(externalProxies) > 0 {
  501. proxyParams := cloneStringMap(params)
  502. proxyParams["security"] = security
  503. return s.buildExternalProxyURLLinks(
  504. externalProxies,
  505. proxyParams,
  506. security,
  507. func(dest string, port int) string {
  508. return fmt.Sprintf("ss://%s@%s:%d", base64.RawURLEncoding.EncodeToString([]byte(encPart)), dest, port)
  509. },
  510. func(ep map[string]any) string {
  511. return s.genRemark(inbound, email, ep["remark"].(string))
  512. },
  513. )
  514. }
  515. link := fmt.Sprintf("ss://%s@%s:%d", base64.RawURLEncoding.EncodeToString([]byte(encPart)), address, inbound.Port)
  516. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  517. }
  518. func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) string {
  519. if inbound.Protocol != model.Hysteria {
  520. return ""
  521. }
  522. var stream map[string]any
  523. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  524. clients, _ := s.inboundService.GetClients(inbound)
  525. clientIndex := -1
  526. for i, client := range clients {
  527. if client.Email == email {
  528. clientIndex = i
  529. break
  530. }
  531. }
  532. auth := encodeUserinfo(clients[clientIndex].Auth)
  533. params := make(map[string]string)
  534. params["security"] = "tls"
  535. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  536. alpns, _ := tlsSetting["alpn"].([]any)
  537. var alpn []string
  538. for _, a := range alpns {
  539. alpn = append(alpn, a.(string))
  540. }
  541. if len(alpn) > 0 {
  542. params["alpn"] = strings.Join(alpn, ",")
  543. }
  544. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  545. params["sni"], _ = sniValue.(string)
  546. }
  547. tlsSettings, _ := searchKey(tlsSetting, "settings")
  548. if tlsSetting != nil {
  549. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  550. params["fp"], _ = fpValue.(string)
  551. }
  552. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  553. if insecure.(bool) {
  554. params["insecure"] = "1"
  555. }
  556. }
  557. if pins, ok := pinnedSha256List(tlsSettings); ok {
  558. params["pinSHA256"] = strings.Join(pins, ",")
  559. }
  560. }
  561. // salamander obfs (Hysteria2). The panel-side link generator already
  562. // emits these; keep the subscription output in sync so a client has
  563. // the obfs password to match the server.
  564. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  565. applyFinalMaskParams(finalmask, params)
  566. if udpMasks, ok := finalmask["udp"].([]any); ok {
  567. for _, m := range udpMasks {
  568. mask, _ := m.(map[string]any)
  569. if mask == nil || mask["type"] != "salamander" {
  570. continue
  571. }
  572. settings, _ := mask["settings"].(map[string]any)
  573. if pw, ok := settings["password"].(string); ok && pw != "" {
  574. params["obfs"] = "salamander"
  575. params["obfs-password"] = pw
  576. break
  577. }
  578. }
  579. }
  580. }
  581. var settings map[string]any
  582. json.Unmarshal([]byte(inbound.Settings), &settings)
  583. version, _ := settings["version"].(float64)
  584. protocol := "hysteria2"
  585. if int(version) == 1 {
  586. protocol = "hysteria"
  587. }
  588. // Fan out one link per External Proxy entry if any. Previously this
  589. // generator ignored `externalProxy` entirely, so the link kept the
  590. // server's own IP/port even when the admin configured an alternate
  591. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  592. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  593. externalProxies, _ := stream["externalProxy"].([]any)
  594. if len(externalProxies) > 0 {
  595. links := make([]string, 0, len(externalProxies))
  596. for _, externalProxy := range externalProxies {
  597. ep, ok := externalProxy.(map[string]any)
  598. if !ok {
  599. continue
  600. }
  601. dest, _ := ep["dest"].(string)
  602. portF, okPort := ep["port"].(float64)
  603. if dest == "" || !okPort {
  604. continue
  605. }
  606. epRemark, _ := ep["remark"].(string)
  607. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, dest, int(portF))
  608. links = append(links, buildLinkWithParams(link, params, s.genRemark(inbound, email, epRemark)))
  609. }
  610. return strings.Join(links, "\n")
  611. }
  612. // No external proxy configured — use the inbound's resolved address so
  613. // node-managed inbounds get the node's host instead of the central panel's.
  614. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, s.resolveInboundAddress(inbound), inbound.Port)
  615. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  616. }
  617. // loadNodes refreshes nodesByID from the DB. Called once per request so
  618. // the per-inbound resolveInboundAddress lookups are pure map reads.
  619. // We filter to address != ” so a half-configured node row doesn't
  620. // accidentally produce a useless host like "https://:2053".
  621. func (s *SubService) loadNodes() {
  622. db := database.GetDB()
  623. var nodes []*model.Node
  624. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  625. logger.Warning("subscription: load nodes failed:", err)
  626. s.nodesByID = nil
  627. return
  628. }
  629. m := make(map[int]*model.Node, len(nodes))
  630. for _, n := range nodes {
  631. m[n.Id] = n
  632. }
  633. s.nodesByID = m
  634. }
  635. // resolveInboundAddress returns the node's address for node-managed inbounds,
  636. // otherwise the subscriber's host (s.address). The inbound's bind Listen is
  637. // deliberately ignored: it's a server-side address, not a client-reachable
  638. // host, so operators advertise a specific endpoint via External Proxy instead.
  639. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  640. if inbound.NodeID != nil && s.nodesByID != nil {
  641. if n, ok := s.nodesByID[*inbound.NodeID]; ok && n.Address != "" {
  642. return n.Address
  643. }
  644. }
  645. return s.address
  646. }
  647. func findClientIndex(clients []model.Client, email string) int {
  648. for i, client := range clients {
  649. if client.Email == email {
  650. return i
  651. }
  652. }
  653. return -1
  654. }
  655. func unmarshalStreamSettings(streamSettings string) map[string]any {
  656. var stream map[string]any
  657. json.Unmarshal([]byte(streamSettings), &stream)
  658. return stream
  659. }
  660. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  661. params["path"] = settings["path"].(string)
  662. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  663. params["host"] = host
  664. } else {
  665. headers, _ := settings["headers"].(map[string]any)
  666. params["host"] = searchHost(headers)
  667. }
  668. }
  669. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  670. obj["path"] = settings["path"].(string)
  671. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  672. obj["host"] = host
  673. } else {
  674. headers, _ := settings["headers"].(map[string]any)
  675. obj["host"] = searchHost(headers)
  676. }
  677. }
  678. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  679. switch streamNetwork {
  680. case "tcp":
  681. tcp, _ := stream["tcpSettings"].(map[string]any)
  682. header, _ := tcp["header"].(map[string]any)
  683. typeStr, _ := header["type"].(string)
  684. if typeStr == "http" {
  685. request := header["request"].(map[string]any)
  686. requestPath, _ := request["path"].([]any)
  687. params["path"] = requestPath[0].(string)
  688. host := ""
  689. if response, ok := header["response"].(map[string]any); ok {
  690. if respHeaders, ok := response["headers"].(map[string]any); ok {
  691. host = searchHost(respHeaders)
  692. }
  693. }
  694. if host == "" {
  695. headers, _ := request["headers"].(map[string]any)
  696. host = searchHost(headers)
  697. }
  698. params["host"] = host
  699. params["headerType"] = "http"
  700. }
  701. case "kcp":
  702. applyKcpShareParams(stream, params)
  703. case "ws":
  704. ws, _ := stream["wsSettings"].(map[string]any)
  705. applyPathAndHostParams(ws, params)
  706. case "grpc":
  707. grpc, _ := stream["grpcSettings"].(map[string]any)
  708. params["serviceName"] = grpc["serviceName"].(string)
  709. params["authority"], _ = grpc["authority"].(string)
  710. if grpc["multiMode"].(bool) {
  711. params["mode"] = "multi"
  712. }
  713. case "httpupgrade":
  714. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  715. applyPathAndHostParams(httpupgrade, params)
  716. case "xhttp":
  717. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  718. applyXhttpExtraParams(xhttp, params)
  719. }
  720. }
  721. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  722. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  723. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  724. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  725. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  726. obj["x_padding_bytes"] = xpb
  727. }
  728. maps.Copy(obj, buildXhttpExtra(xhttp))
  729. }
  730. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  731. obj["net"] = network
  732. switch network {
  733. case "tcp":
  734. tcp, _ := stream["tcpSettings"].(map[string]any)
  735. header, _ := tcp["header"].(map[string]any)
  736. typeStr, _ := header["type"].(string)
  737. obj["type"] = typeStr
  738. if typeStr == "http" {
  739. request := header["request"].(map[string]any)
  740. requestPath, _ := request["path"].([]any)
  741. obj["path"] = requestPath[0].(string)
  742. host := ""
  743. if response, ok := header["response"].(map[string]any); ok {
  744. if respHeaders, ok := response["headers"].(map[string]any); ok {
  745. host = searchHost(respHeaders)
  746. }
  747. }
  748. if host == "" {
  749. headers, _ := request["headers"].(map[string]any)
  750. host = searchHost(headers)
  751. }
  752. obj["host"] = host
  753. }
  754. case "kcp":
  755. applyKcpShareObj(stream, obj)
  756. case "ws":
  757. ws, _ := stream["wsSettings"].(map[string]any)
  758. applyPathAndHostObj(ws, obj)
  759. case "grpc":
  760. grpc, _ := stream["grpcSettings"].(map[string]any)
  761. obj["path"] = grpc["serviceName"].(string)
  762. obj["authority"] = grpc["authority"].(string)
  763. if grpc["multiMode"].(bool) {
  764. obj["type"] = "multi"
  765. }
  766. case "httpupgrade":
  767. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  768. applyPathAndHostObj(httpupgrade, obj)
  769. case "xhttp":
  770. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  771. applyPathAndHostObj(xhttp, obj)
  772. if mode, ok := xhttp["mode"].(string); ok {
  773. obj["mode"] = mode
  774. }
  775. applyXhttpExtraObj(xhttp, obj)
  776. }
  777. }
  778. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  779. params["security"] = "tls"
  780. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  781. alpns, _ := tlsSetting["alpn"].([]any)
  782. var alpn []string
  783. for _, a := range alpns {
  784. alpn = append(alpn, a.(string))
  785. }
  786. if len(alpn) > 0 {
  787. params["alpn"] = strings.Join(alpn, ",")
  788. }
  789. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  790. params["sni"], _ = sniValue.(string)
  791. }
  792. tlsSettings, _ := searchKey(tlsSetting, "settings")
  793. if tlsSetting != nil {
  794. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  795. params["fp"], _ = fpValue.(string)
  796. }
  797. if pins, ok := pinnedSha256List(tlsSettings); ok {
  798. params["pcs"] = strings.Join(pins, ",")
  799. }
  800. }
  801. }
  802. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  803. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  804. alpns, _ := tlsSetting["alpn"].([]any)
  805. if len(alpns) > 0 {
  806. var alpn []string
  807. for _, a := range alpns {
  808. alpn = append(alpn, a.(string))
  809. }
  810. obj["alpn"] = strings.Join(alpn, ",")
  811. }
  812. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  813. obj["sni"], _ = sniValue.(string)
  814. }
  815. tlsSettings, _ := searchKey(tlsSetting, "settings")
  816. if tlsSetting != nil {
  817. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  818. obj["fp"], _ = fpValue.(string)
  819. }
  820. if pins, ok := pinnedSha256List(tlsSettings); ok {
  821. obj["pcs"] = strings.Join(pins, ",")
  822. }
  823. }
  824. }
  825. // pinnedSha256List extracts tlsSettings.settings.pinnedPeerCertSha256 as a
  826. // []string. The field is panel-only (stripped before the run-config reaches
  827. // xray-core via web/service/xray.go) but flows into share links so clients
  828. // can pin the server's certificate hash.
  829. func pinnedSha256List(tlsClientSettings any) ([]string, bool) {
  830. raw, ok := searchKey(tlsClientSettings, "pinnedPeerCertSha256")
  831. if !ok {
  832. return nil, false
  833. }
  834. arr, ok := raw.([]any)
  835. if !ok || len(arr) == 0 {
  836. return nil, false
  837. }
  838. out := make([]string, 0, len(arr))
  839. for _, v := range arr {
  840. s, ok := v.(string)
  841. if !ok || s == "" {
  842. continue
  843. }
  844. out = append(out, s)
  845. }
  846. if len(out) == 0 {
  847. return nil, false
  848. }
  849. return out, true
  850. }
  851. func applyShareRealityParams(stream map[string]any, params map[string]string) {
  852. params["security"] = "reality"
  853. realitySetting, _ := stream["realitySettings"].(map[string]any)
  854. realitySettings, _ := searchKey(realitySetting, "settings")
  855. if realitySetting != nil {
  856. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  857. sNames, _ := sniValue.([]any)
  858. params["sni"] = sNames[random.Num(len(sNames))].(string)
  859. }
  860. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  861. params["pbk"], _ = pbkValue.(string)
  862. }
  863. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  864. shortIds, _ := sidValue.([]any)
  865. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  866. }
  867. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  868. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  869. params["fp"] = fp
  870. }
  871. }
  872. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  873. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  874. params["pqv"] = pqv
  875. }
  876. }
  877. params["spx"] = "/" + random.Seq(15)
  878. }
  879. }
  880. func buildVmessLink(obj map[string]any) string {
  881. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  882. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  883. }
  884. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  885. newObj := map[string]any{}
  886. for key, value := range baseObj {
  887. if !(newSecurity == "none" && (key == "alpn" || key == "sni" || key == "fp")) {
  888. newObj[key] = value
  889. }
  890. }
  891. return newObj
  892. }
  893. func applyExternalProxyTLSObj(ep map[string]any, obj map[string]any, security string) {
  894. if security != "tls" {
  895. return
  896. }
  897. if sni, ok := externalProxySNI(ep); ok {
  898. obj["sni"] = sni
  899. }
  900. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  901. obj["fp"] = fp
  902. }
  903. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  904. obj["alpn"] = alpn
  905. }
  906. }
  907. func applyExternalProxyTLSParams(ep map[string]any, params map[string]string, security string) {
  908. if security != "tls" {
  909. return
  910. }
  911. if sni, ok := externalProxySNI(ep); ok {
  912. params["sni"] = sni
  913. }
  914. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  915. params["fp"] = fp
  916. }
  917. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  918. params["alpn"] = alpn
  919. }
  920. }
  921. // cloneStreamForExternalProxy returns a shallow clone of stream with
  922. // tlsSettings (and its nested settings map) deep-copied. The external
  923. // proxy loop mutates tlsSettings per iteration, so without isolating
  924. // those maps each proxy's SNI/fingerprint/ALPN would leak into the next.
  925. func cloneStreamForExternalProxy(stream map[string]any) map[string]any {
  926. out := cloneMap(stream)
  927. ts, ok := out["tlsSettings"].(map[string]any)
  928. if !ok || ts == nil {
  929. return out
  930. }
  931. clonedTs := cloneMap(ts)
  932. if inner, ok := clonedTs["settings"].(map[string]any); ok && inner != nil {
  933. clonedTs["settings"] = cloneMap(inner)
  934. }
  935. out["tlsSettings"] = clonedTs
  936. return out
  937. }
  938. func applyExternalProxyTLSToStream(ep map[string]any, stream map[string]any, security string) {
  939. if security != "tls" {
  940. return
  941. }
  942. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  943. if tlsSettings == nil {
  944. tlsSettings = map[string]any{}
  945. stream["tlsSettings"] = tlsSettings
  946. }
  947. if sni, ok := externalProxySNI(ep); ok {
  948. tlsSettings["serverName"] = sni
  949. }
  950. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  951. tlsSettings["fingerprint"] = fp
  952. settings, _ := tlsSettings["settings"].(map[string]any)
  953. if settings == nil {
  954. settings = map[string]any{}
  955. tlsSettings["settings"] = settings
  956. }
  957. settings["fingerprint"] = fp
  958. }
  959. if alpn, ok := externalProxyALPNList(ep["alpn"]); ok {
  960. tlsSettings["alpn"] = alpn
  961. }
  962. }
  963. func externalProxySNI(ep map[string]any) (string, bool) {
  964. if sni, ok := ep["sni"].(string); ok && sni != "" {
  965. return sni, true
  966. }
  967. return "", false
  968. }
  969. func externalProxyALPN(value any) (string, bool) {
  970. switch v := value.(type) {
  971. case string:
  972. return v, v != ""
  973. case []string:
  974. if len(v) == 0 {
  975. return "", false
  976. }
  977. return strings.Join(v, ","), true
  978. case []any:
  979. alpn := make([]string, 0, len(v))
  980. for _, item := range v {
  981. if s, ok := item.(string); ok && s != "" {
  982. alpn = append(alpn, s)
  983. }
  984. }
  985. if len(alpn) == 0 {
  986. return "", false
  987. }
  988. return strings.Join(alpn, ","), true
  989. default:
  990. return "", false
  991. }
  992. }
  993. func externalProxyALPNList(value any) ([]any, bool) {
  994. switch v := value.(type) {
  995. case string:
  996. if v == "" {
  997. return nil, false
  998. }
  999. parts := strings.Split(v, ",")
  1000. out := make([]any, 0, len(parts))
  1001. for _, part := range parts {
  1002. if part = strings.TrimSpace(part); part != "" {
  1003. out = append(out, part)
  1004. }
  1005. }
  1006. return out, len(out) > 0
  1007. case []string:
  1008. out := make([]any, 0, len(v))
  1009. for _, item := range v {
  1010. if item != "" {
  1011. out = append(out, item)
  1012. }
  1013. }
  1014. return out, len(out) > 0
  1015. case []any:
  1016. out := make([]any, 0, len(v))
  1017. for _, item := range v {
  1018. if s, ok := item.(string); ok && s != "" {
  1019. out = append(out, s)
  1020. }
  1021. }
  1022. return out, len(out) > 0
  1023. default:
  1024. return nil, false
  1025. }
  1026. }
  1027. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string) string {
  1028. var links strings.Builder
  1029. for index, externalProxy := range externalProxies {
  1030. ep, _ := externalProxy.(map[string]any)
  1031. newSecurity, _ := ep["forceTls"].(string)
  1032. securityToApply := baseObj["tls"].(string)
  1033. if newSecurity != "same" {
  1034. securityToApply = newSecurity
  1035. }
  1036. newObj := cloneVmessShareObj(baseObj, newSecurity)
  1037. newObj["ps"] = s.genRemark(inbound, email, ep["remark"].(string))
  1038. newObj["add"] = ep["dest"].(string)
  1039. newObj["port"] = int(ep["port"].(float64))
  1040. if newSecurity != "same" {
  1041. newObj["tls"] = newSecurity
  1042. }
  1043. applyExternalProxyTLSObj(ep, newObj, securityToApply)
  1044. if index > 0 {
  1045. links.WriteString("\n")
  1046. }
  1047. links.WriteString(buildVmessLink(newObj))
  1048. }
  1049. return links.String()
  1050. }
  1051. // buildLinkWithParams appends ?query and #fragment to a pre-built
  1052. // scheme://userinfo@host:port string without re-parsing it. The caller
  1053. // has already escaped userinfo via encodeUserinfo (or chosen a base64
  1054. // alphabet with no reserved chars); a url.Parse + .String() round-trip
  1055. // would silently decode that escaping because Go's userinfo emitter
  1056. // leaves sub-delims (=, +, ;) literal, which breaks Trojan/Hysteria/SS
  1057. // clients that reject those chars in the password.
  1058. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  1059. return appendQueryAndFragment(link, params, fragment, "", false)
  1060. }
  1061. // buildLinkWithParamsAndSecurity is buildLinkWithParams plus an
  1062. // external-proxy override: the `security` key in params is replaced with
  1063. // the supplied value, and TLS hint fields (alpn/sni/fp) are stripped when
  1064. // the override is `none`.
  1065. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  1066. return appendQueryAndFragment(link, params, fragment, security, omitTLSFields)
  1067. }
  1068. func appendQueryAndFragment(link string, params map[string]string, fragment, securityOverride string, omitTLSFields bool) string {
  1069. var sb strings.Builder
  1070. sb.WriteString(link)
  1071. if len(params) > 0 {
  1072. q := url.Values{}
  1073. for k, v := range params {
  1074. if securityOverride != "" && k == "security" {
  1075. v = securityOverride
  1076. }
  1077. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp") {
  1078. continue
  1079. }
  1080. q.Set(k, v)
  1081. }
  1082. encoded := q.Encode()
  1083. if encoded != "" {
  1084. if strings.Contains(link, "?") {
  1085. sb.WriteByte('&')
  1086. } else {
  1087. sb.WriteByte('?')
  1088. }
  1089. sb.WriteString(encoded)
  1090. }
  1091. }
  1092. if fragment != "" {
  1093. sb.WriteByte('#')
  1094. // Match the frontend's encodeURIComponent(remark): spaces become
  1095. // %20 (not + as in query strings).
  1096. sb.WriteString(strings.ReplaceAll(url.QueryEscape(fragment), "+", "%20"))
  1097. }
  1098. return sb.String()
  1099. }
  1100. func (s *SubService) buildExternalProxyURLLinks(
  1101. externalProxies []any,
  1102. params map[string]string,
  1103. baseSecurity string,
  1104. makeLink func(dest string, port int) string,
  1105. makeRemark func(ep map[string]any) string,
  1106. ) string {
  1107. links := make([]string, 0, len(externalProxies))
  1108. for _, externalProxy := range externalProxies {
  1109. ep, _ := externalProxy.(map[string]any)
  1110. newSecurity, _ := ep["forceTls"].(string)
  1111. dest, _ := ep["dest"].(string)
  1112. port := int(ep["port"].(float64))
  1113. securityToApply := baseSecurity
  1114. if newSecurity != "same" {
  1115. securityToApply = newSecurity
  1116. }
  1117. nextParams := cloneStringMap(params)
  1118. applyExternalProxyTLSParams(ep, nextParams, securityToApply)
  1119. links = append(
  1120. links,
  1121. buildLinkWithParamsAndSecurity(
  1122. makeLink(dest, port),
  1123. nextParams,
  1124. makeRemark(ep),
  1125. securityToApply,
  1126. newSecurity == "none",
  1127. ),
  1128. )
  1129. }
  1130. return strings.Join(links, "\n")
  1131. }
  1132. func cloneStringMap(source map[string]string) map[string]string {
  1133. cloned := make(map[string]string, len(source))
  1134. maps.Copy(cloned, source)
  1135. return cloned
  1136. }
  1137. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string) string {
  1138. separationChar := string(s.remarkModel[0])
  1139. orderChars := s.remarkModel[1:]
  1140. orders := map[byte]string{
  1141. 'i': "",
  1142. 'e': "",
  1143. 'o': "",
  1144. }
  1145. if len(email) > 0 && s.emailInRemark {
  1146. orders['e'] = email
  1147. }
  1148. if len(inbound.Remark) > 0 {
  1149. orders['i'] = inbound.Remark
  1150. }
  1151. if len(extra) > 0 {
  1152. orders['o'] = extra
  1153. }
  1154. var remark []string
  1155. for i := 0; i < len(orderChars); i++ {
  1156. char := orderChars[i]
  1157. order, exists := orders[char]
  1158. if exists && order != "" {
  1159. remark = append(remark, order)
  1160. }
  1161. }
  1162. if s.showInfo {
  1163. statsExist := false
  1164. var stats xray.ClientTraffic
  1165. for _, clientStat := range inbound.ClientStats {
  1166. if clientStat.Email == email {
  1167. stats = clientStat
  1168. statsExist = true
  1169. break
  1170. }
  1171. }
  1172. // Get remained days
  1173. if statsExist {
  1174. if !stats.Enable {
  1175. return fmt.Sprintf("⛔️N/A%s%s", separationChar, strings.Join(remark, separationChar))
  1176. }
  1177. if vol := stats.Total - (stats.Up + stats.Down); vol > 0 {
  1178. remark = append(remark, fmt.Sprintf("%s%s", common.FormatTraffic(vol), "📊"))
  1179. }
  1180. now := time.Now().Unix()
  1181. switch exp := stats.ExpiryTime / 1000; {
  1182. case exp > 0:
  1183. remainingSeconds := exp - now
  1184. days := remainingSeconds / 86400
  1185. hours := (remainingSeconds % 86400) / 3600
  1186. minutes := (remainingSeconds % 3600) / 60
  1187. if days > 0 {
  1188. if hours > 0 {
  1189. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  1190. } else {
  1191. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  1192. }
  1193. } else if hours > 0 {
  1194. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  1195. } else {
  1196. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  1197. }
  1198. case exp < 0:
  1199. days := exp / -86400
  1200. hours := (exp % -86400) / 3600
  1201. minutes := (exp % -3600) / 60
  1202. if days > 0 {
  1203. if hours > 0 {
  1204. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  1205. } else {
  1206. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  1207. }
  1208. } else if hours > 0 {
  1209. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  1210. } else {
  1211. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  1212. }
  1213. }
  1214. }
  1215. }
  1216. return strings.Join(remark, separationChar)
  1217. }
  1218. func searchKey(data any, key string) (any, bool) {
  1219. switch val := data.(type) {
  1220. case map[string]any:
  1221. for k, v := range val {
  1222. if k == key {
  1223. return v, true
  1224. }
  1225. if result, ok := searchKey(v, key); ok {
  1226. return result, true
  1227. }
  1228. }
  1229. case []any:
  1230. for _, v := range val {
  1231. if result, ok := searchKey(v, key); ok {
  1232. return result, true
  1233. }
  1234. }
  1235. }
  1236. return nil, false
  1237. }
  1238. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  1239. // that goes into the URL's `extra` param (or, for VMess, the link
  1240. // object). Carries ONLY the bidirectional fields from xray-core's
  1241. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  1242. // must match. Strictly one-sided fields are excluded:
  1243. //
  1244. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  1245. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  1246. // them just bloats the URL.
  1247. // - client-only values are included only when present in the inbound
  1248. // JSON. Some deployments/imported configs carry them there, and the
  1249. // subscription link is the only place clients can receive them.
  1250. //
  1251. // Truthy-only guards keep default inbounds emitting the same compact URL
  1252. // they did before this helper grew.
  1253. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  1254. if xhttp == nil {
  1255. return nil
  1256. }
  1257. extra := map[string]any{}
  1258. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1259. extra["xPaddingBytes"] = xpb
  1260. }
  1261. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  1262. extra["xPaddingObfsMode"] = true
  1263. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  1264. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1265. extra[field] = v
  1266. }
  1267. }
  1268. }
  1269. stringFields := []string{
  1270. "uplinkHTTPMethod",
  1271. "sessionPlacement", "sessionKey",
  1272. "seqPlacement", "seqKey",
  1273. "uplinkDataPlacement", "uplinkDataKey",
  1274. "scMaxEachPostBytes", "scMinPostsIntervalMs",
  1275. }
  1276. for _, field := range stringFields {
  1277. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1278. extra[field] = v
  1279. }
  1280. }
  1281. for _, field := range []string{"uplinkChunkSize"} {
  1282. if v, ok := nonZeroShareValue(xhttp[field]); ok {
  1283. extra[field] = v
  1284. }
  1285. }
  1286. for _, field := range []string{"noGRPCHeader"} {
  1287. if v, ok := xhttp[field].(bool); ok && v {
  1288. extra[field] = v
  1289. }
  1290. }
  1291. for _, field := range []string{"xmux", "downloadSettings"} {
  1292. if v, ok := nonEmptyShareObject(xhttp[field]); ok {
  1293. extra[field] = v
  1294. }
  1295. }
  1296. // Headers — emitted as the {name: value} map upstream's struct
  1297. // expects. The server runtime ignores this field, but the client
  1298. // (consuming the share link) honors it. Drop any "host" entry —
  1299. // host already wins as a top-level URL param.
  1300. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  1301. out := map[string]any{}
  1302. for k, v := range rawHeaders {
  1303. if strings.EqualFold(k, "host") {
  1304. continue
  1305. }
  1306. out[k] = v
  1307. }
  1308. if len(out) > 0 {
  1309. extra["headers"] = out
  1310. }
  1311. }
  1312. if len(extra) == 0 {
  1313. return nil
  1314. }
  1315. return extra
  1316. }
  1317. func nonZeroShareValue(v any) (any, bool) {
  1318. switch value := v.(type) {
  1319. case string:
  1320. return value, value != ""
  1321. case int:
  1322. return value, value != 0
  1323. case int32:
  1324. return value, value != 0
  1325. case int64:
  1326. return value, value != 0
  1327. case float32:
  1328. return value, value != 0
  1329. case float64:
  1330. return value, value != 0
  1331. default:
  1332. return nil, false
  1333. }
  1334. }
  1335. func nonEmptyShareObject(v any) (any, bool) {
  1336. switch value := v.(type) {
  1337. case map[string]any:
  1338. return value, len(value) > 0
  1339. case map[string]string:
  1340. return value, len(value) > 0
  1341. case []any:
  1342. return value, len(value) > 0
  1343. default:
  1344. return nil, false
  1345. }
  1346. }
  1347. // applyXhttpExtraParams emits the full xhttp config into the URL query
  1348. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  1349. // top level (xray's Build() always lets these win over `extra`) and packs
  1350. // everything else into a JSON `extra` param. Also writes the flat
  1351. // `x_padding_bytes` param sing-box-family clients understand.
  1352. //
  1353. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  1354. // reach the client and handshakes are silently rejected with
  1355. // `invalid padding (...) length: 0` — the client-visible symptom is
  1356. // "xhttp doesn't connect" on OpenWRT / sing-box.
  1357. //
  1358. // Two encodings are written so every popular client can read at least one:
  1359. //
  1360. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  1361. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  1362. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  1363. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  1364. // bidirectional fields beyond path/host/mode.
  1365. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  1366. if xhttp == nil {
  1367. return
  1368. }
  1369. applyPathAndHostParams(xhttp, params)
  1370. if mode, ok := xhttp["mode"].(string); ok {
  1371. params["mode"] = mode
  1372. }
  1373. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1374. params["x_padding_bytes"] = xpb
  1375. }
  1376. extra := buildXhttpExtra(xhttp)
  1377. if extra != nil {
  1378. if b, err := json.Marshal(extra); err == nil {
  1379. params["extra"] = string(b)
  1380. }
  1381. }
  1382. }
  1383. var kcpMaskToHeaderType = map[string]string{
  1384. "dns": "dns",
  1385. "dtls": "dtls",
  1386. "srtp": "srtp",
  1387. "utp": "utp",
  1388. "wechat": "wechat-video",
  1389. "wireguard": "wireguard",
  1390. }
  1391. var validFinalMaskUDPTypes = map[string]struct{}{
  1392. "salamander": {},
  1393. "mkcp-legacy": {},
  1394. "xdns": {},
  1395. "xicmp": {},
  1396. "noise": {},
  1397. "header-custom": {},
  1398. "realm": {},
  1399. }
  1400. var validFinalMaskTCPTypes = map[string]struct{}{
  1401. "header-custom": {},
  1402. "fragment": {},
  1403. "sudoku": {},
  1404. }
  1405. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  1406. // the historical kcpSettings.header/seed shape or the current finalmask model.
  1407. // This keeps subscription output compatible while avoiding panics when older
  1408. // keys are absent from modern inbounds.
  1409. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  1410. extractKcpShareFields(stream).applyToParams(params)
  1411. }
  1412. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  1413. extractKcpShareFields(stream).applyToObj(obj)
  1414. }
  1415. type kcpShareFields struct {
  1416. headerType string
  1417. seed string
  1418. mtu int
  1419. tti int
  1420. }
  1421. func (f kcpShareFields) applyToParams(params map[string]string) {
  1422. if f.headerType != "" && f.headerType != "none" {
  1423. params["headerType"] = f.headerType
  1424. }
  1425. setStringParam(params, "seed", f.seed)
  1426. setIntParam(params, "mtu", f.mtu)
  1427. setIntParam(params, "tti", f.tti)
  1428. }
  1429. func (f kcpShareFields) applyToObj(obj map[string]any) {
  1430. if f.headerType != "" && f.headerType != "none" {
  1431. obj["type"] = f.headerType
  1432. }
  1433. setStringField(obj, "path", f.seed)
  1434. setIntField(obj, "mtu", f.mtu)
  1435. setIntField(obj, "tti", f.tti)
  1436. }
  1437. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  1438. fields := kcpShareFields{headerType: "none"}
  1439. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  1440. if header, ok := kcp["header"].(map[string]any); ok {
  1441. if value, ok := header["type"].(string); ok && value != "" {
  1442. fields.headerType = value
  1443. }
  1444. }
  1445. if value, ok := kcp["seed"].(string); ok && value != "" {
  1446. fields.seed = value
  1447. }
  1448. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  1449. fields.mtu = value
  1450. }
  1451. if value, ok := readPositiveInt(kcp["tti"]); ok {
  1452. fields.tti = value
  1453. }
  1454. }
  1455. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  1456. mask, _ := rawMask.(map[string]any)
  1457. if mask == nil {
  1458. continue
  1459. }
  1460. if maskType, _ := mask["type"].(string); maskType != "mkcp-legacy" {
  1461. continue
  1462. }
  1463. settings, _ := mask["settings"].(map[string]any)
  1464. header, _ := settings["header"].(string)
  1465. value, _ := settings["value"].(string)
  1466. if header == "" {
  1467. fields.seed = value
  1468. continue
  1469. }
  1470. if mapped, ok := kcpMaskToHeaderType[header]; ok {
  1471. fields.headerType = mapped
  1472. }
  1473. }
  1474. return fields
  1475. }
  1476. func readPositiveInt(value any) (int, bool) {
  1477. switch number := value.(type) {
  1478. case int:
  1479. return number, number > 0
  1480. case int32:
  1481. return int(number), number > 0
  1482. case int64:
  1483. return int(number), number > 0
  1484. case float32:
  1485. parsed := int(number)
  1486. return parsed, parsed > 0
  1487. case float64:
  1488. parsed := int(number)
  1489. return parsed, parsed > 0
  1490. default:
  1491. return 0, false
  1492. }
  1493. }
  1494. func setStringParam(params map[string]string, key, value string) {
  1495. if value == "" {
  1496. delete(params, key)
  1497. return
  1498. }
  1499. params[key] = value
  1500. }
  1501. func setIntParam(params map[string]string, key string, value int) {
  1502. if value <= 0 {
  1503. delete(params, key)
  1504. return
  1505. }
  1506. params[key] = fmt.Sprintf("%d", value)
  1507. }
  1508. func setStringField(obj map[string]any, key, value string) {
  1509. if value == "" {
  1510. delete(obj, key)
  1511. return
  1512. }
  1513. obj[key] = value
  1514. }
  1515. func setIntField(obj map[string]any, key string, value int) {
  1516. if value <= 0 {
  1517. delete(obj, key)
  1518. return
  1519. }
  1520. obj[key] = value
  1521. }
  1522. // applyFinalMaskParams exports the finalmask payload as the compact
  1523. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  1524. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  1525. if fm, ok := marshalFinalMask(finalmask); ok {
  1526. params["fm"] = fm
  1527. }
  1528. }
  1529. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  1530. if fm, ok := marshalFinalMask(finalmask); ok {
  1531. obj["fm"] = fm
  1532. }
  1533. }
  1534. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  1535. normalized := normalizeFinalMask(finalmask)
  1536. if !hasFinalMaskContent(normalized) {
  1537. return "", false
  1538. }
  1539. b, err := json.Marshal(normalized)
  1540. if err != nil || len(b) == 0 || string(b) == "null" {
  1541. return "", false
  1542. }
  1543. return string(b), true
  1544. }
  1545. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  1546. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  1547. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  1548. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  1549. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  1550. return nil
  1551. }
  1552. result := map[string]any{}
  1553. if len(tcpMasks) > 0 {
  1554. result["tcp"] = tcpMasks
  1555. }
  1556. if len(udpMasks) > 0 {
  1557. result["udp"] = udpMasks
  1558. }
  1559. if hasQuicParams && len(quicParams) > 0 {
  1560. result["quicParams"] = quicParams
  1561. }
  1562. return result
  1563. }
  1564. func normalizedFinalMaskTCPMasks(value any) []any {
  1565. finalmask, _ := value.(map[string]any)
  1566. if finalmask == nil {
  1567. return nil
  1568. }
  1569. rawMasks, _ := finalmask["tcp"].([]any)
  1570. if len(rawMasks) == 0 {
  1571. return nil
  1572. }
  1573. normalized := make([]any, 0, len(rawMasks))
  1574. for _, rawMask := range rawMasks {
  1575. mask, _ := rawMask.(map[string]any)
  1576. if mask == nil {
  1577. continue
  1578. }
  1579. maskType, _ := mask["type"].(string)
  1580. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  1581. continue
  1582. }
  1583. normalizedMask := map[string]any{"type": maskType}
  1584. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1585. normalizedMask["settings"] = settings
  1586. }
  1587. normalized = append(normalized, normalizedMask)
  1588. }
  1589. if len(normalized) == 0 {
  1590. return nil
  1591. }
  1592. return normalized
  1593. }
  1594. func normalizedFinalMaskUDPMasks(value any) []any {
  1595. finalmask, _ := value.(map[string]any)
  1596. if finalmask == nil {
  1597. return nil
  1598. }
  1599. rawMasks, _ := finalmask["udp"].([]any)
  1600. if len(rawMasks) == 0 {
  1601. return nil
  1602. }
  1603. normalized := make([]any, 0, len(rawMasks))
  1604. for _, rawMask := range rawMasks {
  1605. mask, _ := rawMask.(map[string]any)
  1606. if mask == nil {
  1607. continue
  1608. }
  1609. maskType, _ := mask["type"].(string)
  1610. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  1611. continue
  1612. }
  1613. normalizedMask := map[string]any{"type": maskType}
  1614. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1615. normalizedMask["settings"] = settings
  1616. }
  1617. normalized = append(normalized, normalizedMask)
  1618. }
  1619. if len(normalized) == 0 {
  1620. return nil
  1621. }
  1622. return normalized
  1623. }
  1624. func hasFinalMaskContent(value any) bool {
  1625. switch v := value.(type) {
  1626. case nil:
  1627. return false
  1628. case string:
  1629. return len(v) > 0
  1630. case map[string]any:
  1631. for _, item := range v {
  1632. if hasFinalMaskContent(item) {
  1633. return true
  1634. }
  1635. }
  1636. return false
  1637. case []any:
  1638. return slices.ContainsFunc(v, hasFinalMaskContent)
  1639. default:
  1640. return true
  1641. }
  1642. }
  1643. func searchHost(headers any) string {
  1644. data, _ := headers.(map[string]any)
  1645. for k, v := range data {
  1646. if strings.EqualFold(k, "host") {
  1647. switch v.(type) {
  1648. case []any:
  1649. hosts, _ := v.([]any)
  1650. if len(hosts) > 0 {
  1651. return hosts[0].(string)
  1652. } else {
  1653. return ""
  1654. }
  1655. case any:
  1656. return v.(string)
  1657. }
  1658. }
  1659. }
  1660. return ""
  1661. }
  1662. // PageData is a view model for subpage.html
  1663. // PageData contains data for rendering the subscription information page.
  1664. type PageData struct {
  1665. Host string
  1666. BasePath string
  1667. SId string
  1668. Enabled bool
  1669. Download string
  1670. Upload string
  1671. Total string
  1672. Used string
  1673. Remained string
  1674. Expire int64
  1675. LastOnline int64
  1676. Datepicker string
  1677. DownloadByte int64
  1678. UploadByte int64
  1679. TotalByte int64
  1680. SubUrl string
  1681. SubJsonUrl string
  1682. SubClashUrl string
  1683. SubTitle string
  1684. SubSupportUrl string
  1685. Result []string
  1686. Emails []string
  1687. }
  1688. // ResolveRequest extracts scheme and host info from request/headers consistently.
  1689. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  1690. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  1691. // scheme
  1692. scheme = "http"
  1693. if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
  1694. scheme = "https"
  1695. }
  1696. // base host (no port)
  1697. if h, err := getHostFromXFH(c.GetHeader("X-Forwarded-Host")); err == nil && h != "" {
  1698. host = h
  1699. }
  1700. if host == "" {
  1701. host = c.GetHeader("X-Real-IP")
  1702. }
  1703. if host == "" {
  1704. var err error
  1705. host, _, err = net.SplitHostPort(c.Request.Host)
  1706. if err != nil {
  1707. host = c.Request.Host
  1708. }
  1709. }
  1710. // host:port for URLs
  1711. hostWithPort = c.GetHeader("X-Forwarded-Host")
  1712. if hostWithPort == "" {
  1713. hostWithPort = c.Request.Host
  1714. }
  1715. if hostWithPort == "" {
  1716. hostWithPort = host
  1717. }
  1718. // header display host
  1719. hostHeader = c.GetHeader("X-Forwarded-Host")
  1720. if hostHeader == "" {
  1721. hostHeader = c.GetHeader("X-Real-IP")
  1722. }
  1723. if hostHeader == "" {
  1724. hostHeader = host
  1725. }
  1726. return
  1727. }
  1728. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  1729. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  1730. func (s *SubService) BuildURLs(subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  1731. if subId == "" {
  1732. return "", "", ""
  1733. }
  1734. configuredSubURI, _ := s.settingService.GetSubURI()
  1735. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  1736. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  1737. // Same base as the panel's Client Information page; s.address is the
  1738. // subscriber's host already normalized away from any loopback/bind IP.
  1739. base := s.settingService.BuildSubURIBase(s.address)
  1740. subURL = s.buildSingleURL(configuredSubURI, base, subPath, subId)
  1741. subJsonURL = s.buildSingleURL(configuredSubJsonURI, base, subJsonPath, subId)
  1742. subClashURL = s.buildSingleURL(configuredSubClashURI, base, subClashPath, subId)
  1743. return subURL, subJsonURL, subClashURL
  1744. }
  1745. // buildSingleURL constructs a single URL using configured URI or base components
  1746. func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string {
  1747. if configuredURI != "" {
  1748. return s.joinPathWithID(configuredURI, subId)
  1749. }
  1750. return s.joinPathWithID(base+basePath, subId)
  1751. }
  1752. // joinPathWithID safely joins a base path with a subscription ID
  1753. func (s *SubService) joinPathWithID(basePath, subId string) string {
  1754. if strings.HasSuffix(basePath, "/") {
  1755. return basePath + subId
  1756. }
  1757. return basePath + "/" + subId
  1758. }
  1759. // BuildPageData parses header and prepares the template view model.
  1760. // BuildPageData constructs page data for rendering the subscription information page.
  1761. 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 {
  1762. download := common.FormatTraffic(traffic.Down)
  1763. upload := common.FormatTraffic(traffic.Up)
  1764. total := "∞"
  1765. used := common.FormatTraffic(traffic.Up + traffic.Down)
  1766. remained := ""
  1767. if traffic.Total > 0 {
  1768. total = common.FormatTraffic(traffic.Total)
  1769. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  1770. remained = common.FormatTraffic(left)
  1771. }
  1772. datepicker := s.datepicker
  1773. if datepicker == "" {
  1774. datepicker = "gregorian"
  1775. }
  1776. return PageData{
  1777. Host: hostHeader,
  1778. BasePath: basePath,
  1779. SId: subId,
  1780. Enabled: traffic.Enable,
  1781. Download: download,
  1782. Upload: upload,
  1783. Total: total,
  1784. Used: used,
  1785. Remained: remained,
  1786. Expire: traffic.ExpiryTime / 1000,
  1787. LastOnline: lastOnline,
  1788. Datepicker: datepicker,
  1789. DownloadByte: traffic.Down,
  1790. UploadByte: traffic.Up,
  1791. TotalByte: traffic.Total,
  1792. SubUrl: subURL,
  1793. SubJsonUrl: subJsonURL,
  1794. SubClashUrl: subClashURL,
  1795. SubTitle: subTitle,
  1796. SubSupportUrl: subSupportUrl,
  1797. Result: subs,
  1798. Emails: emails,
  1799. }
  1800. }
  1801. func getHostFromXFH(s string) (string, error) {
  1802. if strings.Contains(s, ":") {
  1803. realHost, _, err := net.SplitHostPort(s)
  1804. if err != nil {
  1805. return "", err
  1806. }
  1807. return realHost, nil
  1808. }
  1809. return s, nil
  1810. }