1
0

subService.go 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  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 echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  553. if ech, _ := echValue.(string); ech != "" {
  554. params["ech"] = ech
  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. if hopPorts := hysteriaHopPorts(stream); hopPorts != "" {
  615. params["mport"] = hopPorts
  616. }
  617. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, s.resolveInboundAddress(inbound), inbound.Port)
  618. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  619. }
  620. // hysteriaHopPorts returns the configured Hysteria2 UDP port-hopping range
  621. // (finalmask.quicParams.udpHop.ports), or "" when port hopping is off. The
  622. // range is emitted as the v2rayN-compatible `mport` query param; the URL port
  623. // field stays numeric so .NET-Uri-based importers (v2rayN) can parse the link.
  624. func hysteriaHopPorts(stream map[string]any) string {
  625. finalmask, _ := stream["finalmask"].(map[string]any)
  626. quicParams, _ := finalmask["quicParams"].(map[string]any)
  627. udpHop, _ := quicParams["udpHop"].(map[string]any)
  628. ports, _ := udpHop["ports"].(string)
  629. return strings.TrimSpace(ports)
  630. }
  631. // loadNodes refreshes nodesByID from the DB. Called once per request so
  632. // the per-inbound resolveInboundAddress lookups are pure map reads.
  633. // We filter to address != ” so a half-configured node row doesn't
  634. // accidentally produce a useless host like "https://:2053".
  635. func (s *SubService) loadNodes() {
  636. db := database.GetDB()
  637. var nodes []*model.Node
  638. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  639. logger.Warning("subscription: load nodes failed:", err)
  640. s.nodesByID = nil
  641. return
  642. }
  643. m := make(map[int]*model.Node, len(nodes))
  644. for _, n := range nodes {
  645. m[n.Id] = n
  646. }
  647. s.nodesByID = m
  648. }
  649. // resolveInboundAddress returns the node's address for node-managed inbounds,
  650. // otherwise the subscriber's host (s.address). The inbound's bind Listen is
  651. // deliberately ignored: it's a server-side address, not a client-reachable
  652. // host, so operators advertise a specific endpoint via External Proxy instead.
  653. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  654. if inbound.NodeID != nil && s.nodesByID != nil {
  655. if n, ok := s.nodesByID[*inbound.NodeID]; ok && n.Address != "" {
  656. return n.Address
  657. }
  658. }
  659. return s.address
  660. }
  661. func findClientIndex(clients []model.Client, email string) int {
  662. for i, client := range clients {
  663. if client.Email == email {
  664. return i
  665. }
  666. }
  667. return -1
  668. }
  669. func unmarshalStreamSettings(streamSettings string) map[string]any {
  670. var stream map[string]any
  671. json.Unmarshal([]byte(streamSettings), &stream)
  672. return stream
  673. }
  674. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  675. params["path"] = settings["path"].(string)
  676. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  677. params["host"] = host
  678. } else {
  679. headers, _ := settings["headers"].(map[string]any)
  680. params["host"] = searchHost(headers)
  681. }
  682. }
  683. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  684. obj["path"] = settings["path"].(string)
  685. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  686. obj["host"] = host
  687. } else {
  688. headers, _ := settings["headers"].(map[string]any)
  689. obj["host"] = searchHost(headers)
  690. }
  691. }
  692. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  693. switch streamNetwork {
  694. case "tcp":
  695. tcp, _ := stream["tcpSettings"].(map[string]any)
  696. header, _ := tcp["header"].(map[string]any)
  697. typeStr, _ := header["type"].(string)
  698. if typeStr == "http" {
  699. request := header["request"].(map[string]any)
  700. requestPath, _ := request["path"].([]any)
  701. params["path"] = requestPath[0].(string)
  702. host := ""
  703. if response, ok := header["response"].(map[string]any); ok {
  704. if respHeaders, ok := response["headers"].(map[string]any); ok {
  705. host = searchHost(respHeaders)
  706. }
  707. }
  708. if host == "" {
  709. headers, _ := request["headers"].(map[string]any)
  710. host = searchHost(headers)
  711. }
  712. params["host"] = host
  713. params["headerType"] = "http"
  714. }
  715. case "kcp":
  716. applyKcpShareParams(stream, params)
  717. case "ws":
  718. ws, _ := stream["wsSettings"].(map[string]any)
  719. applyPathAndHostParams(ws, params)
  720. case "grpc":
  721. grpc, _ := stream["grpcSettings"].(map[string]any)
  722. params["serviceName"] = grpc["serviceName"].(string)
  723. params["authority"], _ = grpc["authority"].(string)
  724. if grpc["multiMode"].(bool) {
  725. params["mode"] = "multi"
  726. }
  727. case "httpupgrade":
  728. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  729. applyPathAndHostParams(httpupgrade, params)
  730. case "xhttp":
  731. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  732. applyXhttpExtraParams(xhttp, params)
  733. }
  734. }
  735. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  736. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  737. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  738. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  739. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  740. obj["x_padding_bytes"] = xpb
  741. }
  742. maps.Copy(obj, buildXhttpExtra(xhttp))
  743. }
  744. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  745. obj["net"] = network
  746. switch network {
  747. case "tcp":
  748. tcp, _ := stream["tcpSettings"].(map[string]any)
  749. header, _ := tcp["header"].(map[string]any)
  750. typeStr, _ := header["type"].(string)
  751. obj["type"] = typeStr
  752. if typeStr == "http" {
  753. request := header["request"].(map[string]any)
  754. requestPath, _ := request["path"].([]any)
  755. obj["path"] = requestPath[0].(string)
  756. host := ""
  757. if response, ok := header["response"].(map[string]any); ok {
  758. if respHeaders, ok := response["headers"].(map[string]any); ok {
  759. host = searchHost(respHeaders)
  760. }
  761. }
  762. if host == "" {
  763. headers, _ := request["headers"].(map[string]any)
  764. host = searchHost(headers)
  765. }
  766. obj["host"] = host
  767. }
  768. case "kcp":
  769. applyKcpShareObj(stream, obj)
  770. case "ws":
  771. ws, _ := stream["wsSettings"].(map[string]any)
  772. applyPathAndHostObj(ws, obj)
  773. case "grpc":
  774. grpc, _ := stream["grpcSettings"].(map[string]any)
  775. obj["path"] = grpc["serviceName"].(string)
  776. obj["authority"] = grpc["authority"].(string)
  777. if grpc["multiMode"].(bool) {
  778. obj["type"] = "multi"
  779. }
  780. case "httpupgrade":
  781. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  782. applyPathAndHostObj(httpupgrade, obj)
  783. case "xhttp":
  784. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  785. applyPathAndHostObj(xhttp, obj)
  786. if mode, ok := xhttp["mode"].(string); ok {
  787. obj["mode"] = mode
  788. }
  789. applyXhttpExtraObj(xhttp, obj)
  790. }
  791. }
  792. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  793. params["security"] = "tls"
  794. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  795. alpns, _ := tlsSetting["alpn"].([]any)
  796. var alpn []string
  797. for _, a := range alpns {
  798. alpn = append(alpn, a.(string))
  799. }
  800. if len(alpn) > 0 {
  801. params["alpn"] = strings.Join(alpn, ",")
  802. }
  803. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  804. params["sni"], _ = sniValue.(string)
  805. }
  806. tlsSettings, _ := searchKey(tlsSetting, "settings")
  807. if tlsSetting != nil {
  808. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  809. params["fp"], _ = fpValue.(string)
  810. }
  811. if pins, ok := pinnedSha256List(tlsSettings); ok {
  812. params["pcs"] = strings.Join(pins, ",")
  813. }
  814. }
  815. }
  816. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  817. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  818. alpns, _ := tlsSetting["alpn"].([]any)
  819. if len(alpns) > 0 {
  820. var alpn []string
  821. for _, a := range alpns {
  822. alpn = append(alpn, a.(string))
  823. }
  824. obj["alpn"] = strings.Join(alpn, ",")
  825. }
  826. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  827. obj["sni"], _ = sniValue.(string)
  828. }
  829. tlsSettings, _ := searchKey(tlsSetting, "settings")
  830. if tlsSetting != nil {
  831. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  832. obj["fp"], _ = fpValue.(string)
  833. }
  834. if pins, ok := pinnedSha256List(tlsSettings); ok {
  835. obj["pcs"] = strings.Join(pins, ",")
  836. }
  837. }
  838. }
  839. // pinnedSha256List extracts tlsSettings.settings.pinnedPeerCertSha256 as a
  840. // []string. The field is panel-only (stripped before the run-config reaches
  841. // xray-core via web/service/xray.go) but flows into share links so clients
  842. // can pin the server's certificate hash.
  843. func pinnedSha256List(tlsClientSettings any) ([]string, bool) {
  844. raw, ok := searchKey(tlsClientSettings, "pinnedPeerCertSha256")
  845. if !ok {
  846. return nil, false
  847. }
  848. arr, ok := raw.([]any)
  849. if !ok || len(arr) == 0 {
  850. return nil, false
  851. }
  852. out := make([]string, 0, len(arr))
  853. for _, v := range arr {
  854. s, ok := v.(string)
  855. if !ok || s == "" {
  856. continue
  857. }
  858. out = append(out, s)
  859. }
  860. if len(out) == 0 {
  861. return nil, false
  862. }
  863. return out, true
  864. }
  865. func applyShareRealityParams(stream map[string]any, params map[string]string) {
  866. params["security"] = "reality"
  867. realitySetting, _ := stream["realitySettings"].(map[string]any)
  868. realitySettings, _ := searchKey(realitySetting, "settings")
  869. if realitySetting != nil {
  870. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  871. sNames, _ := sniValue.([]any)
  872. params["sni"] = sNames[random.Num(len(sNames))].(string)
  873. }
  874. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  875. params["pbk"], _ = pbkValue.(string)
  876. }
  877. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  878. shortIds, _ := sidValue.([]any)
  879. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  880. }
  881. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  882. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  883. params["fp"] = fp
  884. }
  885. }
  886. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  887. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  888. params["pqv"] = pqv
  889. }
  890. }
  891. params["spx"] = "/" + random.Seq(15)
  892. }
  893. }
  894. func buildVmessLink(obj map[string]any) string {
  895. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  896. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  897. }
  898. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  899. newObj := map[string]any{}
  900. for key, value := range baseObj {
  901. if !(newSecurity == "none" && (key == "alpn" || key == "sni" || key == "fp")) {
  902. newObj[key] = value
  903. }
  904. }
  905. return newObj
  906. }
  907. func applyExternalProxyTLSObj(ep map[string]any, obj map[string]any, security string) {
  908. if security != "tls" {
  909. return
  910. }
  911. if sni, ok := externalProxySNI(ep); ok {
  912. obj["sni"] = sni
  913. }
  914. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  915. obj["fp"] = fp
  916. }
  917. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  918. obj["alpn"] = alpn
  919. }
  920. }
  921. func applyExternalProxyTLSParams(ep map[string]any, params map[string]string, security string) {
  922. if security != "tls" {
  923. return
  924. }
  925. if sni, ok := externalProxySNI(ep); ok {
  926. params["sni"] = sni
  927. }
  928. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  929. params["fp"] = fp
  930. }
  931. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  932. params["alpn"] = alpn
  933. }
  934. }
  935. // cloneStreamForExternalProxy returns a shallow clone of stream with
  936. // tlsSettings (and its nested settings map) deep-copied. The external
  937. // proxy loop mutates tlsSettings per iteration, so without isolating
  938. // those maps each proxy's SNI/fingerprint/ALPN would leak into the next.
  939. func cloneStreamForExternalProxy(stream map[string]any) map[string]any {
  940. out := cloneMap(stream)
  941. ts, ok := out["tlsSettings"].(map[string]any)
  942. if !ok || ts == nil {
  943. return out
  944. }
  945. clonedTs := cloneMap(ts)
  946. if inner, ok := clonedTs["settings"].(map[string]any); ok && inner != nil {
  947. clonedTs["settings"] = cloneMap(inner)
  948. }
  949. out["tlsSettings"] = clonedTs
  950. return out
  951. }
  952. func applyExternalProxyTLSToStream(ep map[string]any, stream map[string]any, security string) {
  953. if security != "tls" {
  954. return
  955. }
  956. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  957. if tlsSettings == nil {
  958. tlsSettings = map[string]any{}
  959. stream["tlsSettings"] = tlsSettings
  960. }
  961. if sni, ok := externalProxySNI(ep); ok {
  962. tlsSettings["serverName"] = sni
  963. }
  964. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  965. tlsSettings["fingerprint"] = fp
  966. settings, _ := tlsSettings["settings"].(map[string]any)
  967. if settings == nil {
  968. settings = map[string]any{}
  969. tlsSettings["settings"] = settings
  970. }
  971. settings["fingerprint"] = fp
  972. }
  973. if alpn, ok := externalProxyALPNList(ep["alpn"]); ok {
  974. tlsSettings["alpn"] = alpn
  975. }
  976. }
  977. func externalProxySNI(ep map[string]any) (string, bool) {
  978. if sni, ok := ep["sni"].(string); ok && sni != "" {
  979. return sni, true
  980. }
  981. return "", false
  982. }
  983. func externalProxyALPN(value any) (string, bool) {
  984. switch v := value.(type) {
  985. case string:
  986. return v, v != ""
  987. case []string:
  988. if len(v) == 0 {
  989. return "", false
  990. }
  991. return strings.Join(v, ","), true
  992. case []any:
  993. alpn := make([]string, 0, len(v))
  994. for _, item := range v {
  995. if s, ok := item.(string); ok && s != "" {
  996. alpn = append(alpn, s)
  997. }
  998. }
  999. if len(alpn) == 0 {
  1000. return "", false
  1001. }
  1002. return strings.Join(alpn, ","), true
  1003. default:
  1004. return "", false
  1005. }
  1006. }
  1007. func externalProxyALPNList(value any) ([]any, bool) {
  1008. switch v := value.(type) {
  1009. case string:
  1010. if v == "" {
  1011. return nil, false
  1012. }
  1013. parts := strings.Split(v, ",")
  1014. out := make([]any, 0, len(parts))
  1015. for _, part := range parts {
  1016. if part = strings.TrimSpace(part); part != "" {
  1017. out = append(out, part)
  1018. }
  1019. }
  1020. return out, len(out) > 0
  1021. case []string:
  1022. out := make([]any, 0, len(v))
  1023. for _, item := range v {
  1024. if item != "" {
  1025. out = append(out, item)
  1026. }
  1027. }
  1028. return out, len(out) > 0
  1029. case []any:
  1030. out := make([]any, 0, len(v))
  1031. for _, item := range v {
  1032. if s, ok := item.(string); ok && s != "" {
  1033. out = append(out, s)
  1034. }
  1035. }
  1036. return out, len(out) > 0
  1037. default:
  1038. return nil, false
  1039. }
  1040. }
  1041. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string) string {
  1042. var links strings.Builder
  1043. for index, externalProxy := range externalProxies {
  1044. ep, _ := externalProxy.(map[string]any)
  1045. newSecurity, _ := ep["forceTls"].(string)
  1046. securityToApply := baseObj["tls"].(string)
  1047. if newSecurity != "same" {
  1048. securityToApply = newSecurity
  1049. }
  1050. newObj := cloneVmessShareObj(baseObj, newSecurity)
  1051. newObj["ps"] = s.genRemark(inbound, email, ep["remark"].(string))
  1052. newObj["add"] = ep["dest"].(string)
  1053. newObj["port"] = int(ep["port"].(float64))
  1054. if newSecurity != "same" {
  1055. newObj["tls"] = newSecurity
  1056. }
  1057. applyExternalProxyTLSObj(ep, newObj, securityToApply)
  1058. if index > 0 {
  1059. links.WriteString("\n")
  1060. }
  1061. links.WriteString(buildVmessLink(newObj))
  1062. }
  1063. return links.String()
  1064. }
  1065. // buildLinkWithParams appends ?query and #fragment to a pre-built
  1066. // scheme://userinfo@host:port string without re-parsing it. The caller
  1067. // has already escaped userinfo via encodeUserinfo (or chosen a base64
  1068. // alphabet with no reserved chars); a url.Parse + .String() round-trip
  1069. // would silently decode that escaping because Go's userinfo emitter
  1070. // leaves sub-delims (=, +, ;) literal, which breaks Trojan/Hysteria/SS
  1071. // clients that reject those chars in the password.
  1072. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  1073. return appendQueryAndFragment(link, params, fragment, "", false)
  1074. }
  1075. // buildLinkWithParamsAndSecurity is buildLinkWithParams plus an
  1076. // external-proxy override: the `security` key in params is replaced with
  1077. // the supplied value, and TLS hint fields (alpn/sni/fp) are stripped when
  1078. // the override is `none`.
  1079. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  1080. return appendQueryAndFragment(link, params, fragment, security, omitTLSFields)
  1081. }
  1082. func appendQueryAndFragment(link string, params map[string]string, fragment, securityOverride string, omitTLSFields bool) string {
  1083. var sb strings.Builder
  1084. sb.WriteString(link)
  1085. if len(params) > 0 {
  1086. q := url.Values{}
  1087. for k, v := range params {
  1088. if securityOverride != "" && k == "security" {
  1089. v = securityOverride
  1090. }
  1091. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp") {
  1092. continue
  1093. }
  1094. q.Set(k, v)
  1095. }
  1096. encoded := q.Encode()
  1097. if encoded != "" {
  1098. if strings.Contains(link, "?") {
  1099. sb.WriteByte('&')
  1100. } else {
  1101. sb.WriteByte('?')
  1102. }
  1103. sb.WriteString(encoded)
  1104. }
  1105. }
  1106. if fragment != "" {
  1107. sb.WriteByte('#')
  1108. // Match the frontend's encodeURIComponent(remark): spaces become
  1109. // %20 (not + as in query strings).
  1110. sb.WriteString(strings.ReplaceAll(url.QueryEscape(fragment), "+", "%20"))
  1111. }
  1112. return sb.String()
  1113. }
  1114. func (s *SubService) buildExternalProxyURLLinks(
  1115. externalProxies []any,
  1116. params map[string]string,
  1117. baseSecurity string,
  1118. makeLink func(dest string, port int) string,
  1119. makeRemark func(ep map[string]any) string,
  1120. ) string {
  1121. links := make([]string, 0, len(externalProxies))
  1122. for _, externalProxy := range externalProxies {
  1123. ep, _ := externalProxy.(map[string]any)
  1124. newSecurity, _ := ep["forceTls"].(string)
  1125. dest, _ := ep["dest"].(string)
  1126. port := int(ep["port"].(float64))
  1127. securityToApply := baseSecurity
  1128. if newSecurity != "same" {
  1129. securityToApply = newSecurity
  1130. }
  1131. nextParams := cloneStringMap(params)
  1132. applyExternalProxyTLSParams(ep, nextParams, securityToApply)
  1133. links = append(
  1134. links,
  1135. buildLinkWithParamsAndSecurity(
  1136. makeLink(dest, port),
  1137. nextParams,
  1138. makeRemark(ep),
  1139. securityToApply,
  1140. newSecurity == "none",
  1141. ),
  1142. )
  1143. }
  1144. return strings.Join(links, "\n")
  1145. }
  1146. func cloneStringMap(source map[string]string) map[string]string {
  1147. cloned := make(map[string]string, len(source))
  1148. maps.Copy(cloned, source)
  1149. return cloned
  1150. }
  1151. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string) string {
  1152. separationChar := string(s.remarkModel[0])
  1153. orderChars := s.remarkModel[1:]
  1154. orders := map[byte]string{
  1155. 'i': "",
  1156. 'e': "",
  1157. 'o': "",
  1158. }
  1159. if len(email) > 0 && s.emailInRemark {
  1160. orders['e'] = email
  1161. }
  1162. if len(inbound.Remark) > 0 {
  1163. orders['i'] = inbound.Remark
  1164. }
  1165. if len(extra) > 0 {
  1166. orders['o'] = extra
  1167. }
  1168. var remark []string
  1169. for i := 0; i < len(orderChars); i++ {
  1170. char := orderChars[i]
  1171. order, exists := orders[char]
  1172. if exists && order != "" {
  1173. remark = append(remark, order)
  1174. }
  1175. }
  1176. if s.showInfo {
  1177. statsExist := false
  1178. var stats xray.ClientTraffic
  1179. for _, clientStat := range inbound.ClientStats {
  1180. if clientStat.Email == email {
  1181. stats = clientStat
  1182. statsExist = true
  1183. break
  1184. }
  1185. }
  1186. // Get remained days
  1187. if statsExist {
  1188. if !stats.Enable {
  1189. return fmt.Sprintf("⛔️N/A%s%s", separationChar, strings.Join(remark, separationChar))
  1190. }
  1191. if vol := stats.Total - (stats.Up + stats.Down); vol > 0 {
  1192. remark = append(remark, fmt.Sprintf("%s%s", common.FormatTraffic(vol), "📊"))
  1193. }
  1194. now := time.Now().Unix()
  1195. switch exp := stats.ExpiryTime / 1000; {
  1196. case exp > 0:
  1197. remainingSeconds := exp - now
  1198. days := remainingSeconds / 86400
  1199. hours := (remainingSeconds % 86400) / 3600
  1200. minutes := (remainingSeconds % 3600) / 60
  1201. if days > 0 {
  1202. if hours > 0 {
  1203. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  1204. } else {
  1205. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  1206. }
  1207. } else if hours > 0 {
  1208. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  1209. } else {
  1210. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  1211. }
  1212. case exp < 0:
  1213. days := exp / -86400
  1214. hours := (exp % -86400) / 3600
  1215. minutes := (exp % -3600) / 60
  1216. if days > 0 {
  1217. if hours > 0 {
  1218. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  1219. } else {
  1220. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  1221. }
  1222. } else if hours > 0 {
  1223. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  1224. } else {
  1225. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  1226. }
  1227. }
  1228. }
  1229. }
  1230. return strings.Join(remark, separationChar)
  1231. }
  1232. func searchKey(data any, key string) (any, bool) {
  1233. switch val := data.(type) {
  1234. case map[string]any:
  1235. for k, v := range val {
  1236. if k == key {
  1237. return v, true
  1238. }
  1239. if result, ok := searchKey(v, key); ok {
  1240. return result, true
  1241. }
  1242. }
  1243. case []any:
  1244. for _, v := range val {
  1245. if result, ok := searchKey(v, key); ok {
  1246. return result, true
  1247. }
  1248. }
  1249. }
  1250. return nil, false
  1251. }
  1252. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  1253. // that goes into the URL's `extra` param (or, for VMess, the link
  1254. // object). Carries ONLY the bidirectional fields from xray-core's
  1255. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  1256. // must match. Strictly one-sided fields are excluded:
  1257. //
  1258. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  1259. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  1260. // them just bloats the URL.
  1261. // - client-only values are included only when present in the inbound
  1262. // JSON. Some deployments/imported configs carry them there, and the
  1263. // subscription link is the only place clients can receive them.
  1264. //
  1265. // Truthy-only guards keep default inbounds emitting the same compact URL
  1266. // they did before this helper grew.
  1267. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  1268. if xhttp == nil {
  1269. return nil
  1270. }
  1271. extra := map[string]any{}
  1272. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1273. extra["xPaddingBytes"] = xpb
  1274. }
  1275. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  1276. extra["xPaddingObfsMode"] = true
  1277. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  1278. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1279. extra[field] = v
  1280. }
  1281. }
  1282. }
  1283. stringFields := []string{
  1284. "uplinkHTTPMethod",
  1285. "sessionPlacement", "sessionKey",
  1286. "seqPlacement", "seqKey",
  1287. "uplinkDataPlacement", "uplinkDataKey",
  1288. "scMaxEachPostBytes", "scMinPostsIntervalMs",
  1289. }
  1290. for _, field := range stringFields {
  1291. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1292. extra[field] = v
  1293. }
  1294. }
  1295. for _, field := range []string{"uplinkChunkSize"} {
  1296. if v, ok := nonZeroShareValue(xhttp[field]); ok {
  1297. extra[field] = v
  1298. }
  1299. }
  1300. for _, field := range []string{"noGRPCHeader"} {
  1301. if v, ok := xhttp[field].(bool); ok && v {
  1302. extra[field] = v
  1303. }
  1304. }
  1305. for _, field := range []string{"xmux", "downloadSettings"} {
  1306. if v, ok := nonEmptyShareObject(xhttp[field]); ok {
  1307. extra[field] = v
  1308. }
  1309. }
  1310. // Headers — emitted as the {name: value} map upstream's struct
  1311. // expects. The server runtime ignores this field, but the client
  1312. // (consuming the share link) honors it. Drop any "host" entry —
  1313. // host already wins as a top-level URL param.
  1314. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  1315. out := map[string]any{}
  1316. for k, v := range rawHeaders {
  1317. if strings.EqualFold(k, "host") {
  1318. continue
  1319. }
  1320. out[k] = v
  1321. }
  1322. if len(out) > 0 {
  1323. extra["headers"] = out
  1324. }
  1325. }
  1326. if len(extra) == 0 {
  1327. return nil
  1328. }
  1329. return extra
  1330. }
  1331. func nonZeroShareValue(v any) (any, bool) {
  1332. switch value := v.(type) {
  1333. case string:
  1334. return value, value != ""
  1335. case int:
  1336. return value, value != 0
  1337. case int32:
  1338. return value, value != 0
  1339. case int64:
  1340. return value, value != 0
  1341. case float32:
  1342. return value, value != 0
  1343. case float64:
  1344. return value, value != 0
  1345. default:
  1346. return nil, false
  1347. }
  1348. }
  1349. func nonEmptyShareObject(v any) (any, bool) {
  1350. switch value := v.(type) {
  1351. case map[string]any:
  1352. return value, len(value) > 0
  1353. case map[string]string:
  1354. return value, len(value) > 0
  1355. case []any:
  1356. return value, len(value) > 0
  1357. default:
  1358. return nil, false
  1359. }
  1360. }
  1361. // applyXhttpExtraParams emits the full xhttp config into the URL query
  1362. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  1363. // top level (xray's Build() always lets these win over `extra`) and packs
  1364. // everything else into a JSON `extra` param. Also writes the flat
  1365. // `x_padding_bytes` param sing-box-family clients understand.
  1366. //
  1367. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  1368. // reach the client and handshakes are silently rejected with
  1369. // `invalid padding (...) length: 0` — the client-visible symptom is
  1370. // "xhttp doesn't connect" on OpenWRT / sing-box.
  1371. //
  1372. // Two encodings are written so every popular client can read at least one:
  1373. //
  1374. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  1375. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  1376. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  1377. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  1378. // bidirectional fields beyond path/host/mode.
  1379. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  1380. if xhttp == nil {
  1381. return
  1382. }
  1383. applyPathAndHostParams(xhttp, params)
  1384. if mode, ok := xhttp["mode"].(string); ok {
  1385. params["mode"] = mode
  1386. }
  1387. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1388. params["x_padding_bytes"] = xpb
  1389. }
  1390. extra := buildXhttpExtra(xhttp)
  1391. if extra != nil {
  1392. if b, err := json.Marshal(extra); err == nil {
  1393. params["extra"] = string(b)
  1394. }
  1395. }
  1396. }
  1397. var kcpMaskToHeaderType = map[string]string{
  1398. "dns": "dns",
  1399. "dtls": "dtls",
  1400. "srtp": "srtp",
  1401. "utp": "utp",
  1402. "wechat": "wechat-video",
  1403. "wireguard": "wireguard",
  1404. }
  1405. var validFinalMaskUDPTypes = map[string]struct{}{
  1406. "salamander": {},
  1407. "mkcp-legacy": {},
  1408. "xdns": {},
  1409. "xicmp": {},
  1410. "noise": {},
  1411. "header-custom": {},
  1412. "realm": {},
  1413. }
  1414. var validFinalMaskTCPTypes = map[string]struct{}{
  1415. "header-custom": {},
  1416. "fragment": {},
  1417. "sudoku": {},
  1418. }
  1419. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  1420. // the historical kcpSettings.header/seed shape or the current finalmask model.
  1421. // This keeps subscription output compatible while avoiding panics when older
  1422. // keys are absent from modern inbounds.
  1423. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  1424. extractKcpShareFields(stream).applyToParams(params)
  1425. }
  1426. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  1427. extractKcpShareFields(stream).applyToObj(obj)
  1428. }
  1429. type kcpShareFields struct {
  1430. headerType string
  1431. seed string
  1432. mtu int
  1433. tti int
  1434. }
  1435. func (f kcpShareFields) applyToParams(params map[string]string) {
  1436. if f.headerType != "" && f.headerType != "none" {
  1437. params["headerType"] = f.headerType
  1438. }
  1439. setStringParam(params, "seed", f.seed)
  1440. setIntParam(params, "mtu", f.mtu)
  1441. setIntParam(params, "tti", f.tti)
  1442. }
  1443. func (f kcpShareFields) applyToObj(obj map[string]any) {
  1444. if f.headerType != "" && f.headerType != "none" {
  1445. obj["type"] = f.headerType
  1446. }
  1447. setStringField(obj, "path", f.seed)
  1448. setIntField(obj, "mtu", f.mtu)
  1449. setIntField(obj, "tti", f.tti)
  1450. }
  1451. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  1452. fields := kcpShareFields{headerType: "none"}
  1453. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  1454. if header, ok := kcp["header"].(map[string]any); ok {
  1455. if value, ok := header["type"].(string); ok && value != "" {
  1456. fields.headerType = value
  1457. }
  1458. }
  1459. if value, ok := kcp["seed"].(string); ok && value != "" {
  1460. fields.seed = value
  1461. }
  1462. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  1463. fields.mtu = value
  1464. }
  1465. if value, ok := readPositiveInt(kcp["tti"]); ok {
  1466. fields.tti = value
  1467. }
  1468. }
  1469. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  1470. mask, _ := rawMask.(map[string]any)
  1471. if mask == nil {
  1472. continue
  1473. }
  1474. if maskType, _ := mask["type"].(string); maskType != "mkcp-legacy" {
  1475. continue
  1476. }
  1477. settings, _ := mask["settings"].(map[string]any)
  1478. header, _ := settings["header"].(string)
  1479. value, _ := settings["value"].(string)
  1480. if header == "" {
  1481. fields.seed = value
  1482. continue
  1483. }
  1484. if mapped, ok := kcpMaskToHeaderType[header]; ok {
  1485. fields.headerType = mapped
  1486. }
  1487. }
  1488. return fields
  1489. }
  1490. func readPositiveInt(value any) (int, bool) {
  1491. switch number := value.(type) {
  1492. case int:
  1493. return number, number > 0
  1494. case int32:
  1495. return int(number), number > 0
  1496. case int64:
  1497. return int(number), number > 0
  1498. case float32:
  1499. parsed := int(number)
  1500. return parsed, parsed > 0
  1501. case float64:
  1502. parsed := int(number)
  1503. return parsed, parsed > 0
  1504. default:
  1505. return 0, false
  1506. }
  1507. }
  1508. func setStringParam(params map[string]string, key, value string) {
  1509. if value == "" {
  1510. delete(params, key)
  1511. return
  1512. }
  1513. params[key] = value
  1514. }
  1515. func setIntParam(params map[string]string, key string, value int) {
  1516. if value <= 0 {
  1517. delete(params, key)
  1518. return
  1519. }
  1520. params[key] = fmt.Sprintf("%d", value)
  1521. }
  1522. func setStringField(obj map[string]any, key, value string) {
  1523. if value == "" {
  1524. delete(obj, key)
  1525. return
  1526. }
  1527. obj[key] = value
  1528. }
  1529. func setIntField(obj map[string]any, key string, value int) {
  1530. if value <= 0 {
  1531. delete(obj, key)
  1532. return
  1533. }
  1534. obj[key] = value
  1535. }
  1536. // applyFinalMaskParams exports the finalmask payload as the compact
  1537. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  1538. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  1539. if fm, ok := marshalFinalMask(finalmask); ok {
  1540. params["fm"] = fm
  1541. }
  1542. }
  1543. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  1544. if fm, ok := marshalFinalMask(finalmask); ok {
  1545. obj["fm"] = fm
  1546. }
  1547. }
  1548. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  1549. normalized := normalizeFinalMask(finalmask)
  1550. if !hasFinalMaskContent(normalized) {
  1551. return "", false
  1552. }
  1553. b, err := json.Marshal(normalized)
  1554. if err != nil || len(b) == 0 || string(b) == "null" {
  1555. return "", false
  1556. }
  1557. return string(b), true
  1558. }
  1559. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  1560. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  1561. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  1562. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  1563. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  1564. return nil
  1565. }
  1566. result := map[string]any{}
  1567. if len(tcpMasks) > 0 {
  1568. result["tcp"] = tcpMasks
  1569. }
  1570. if len(udpMasks) > 0 {
  1571. result["udp"] = udpMasks
  1572. }
  1573. if hasQuicParams && len(quicParams) > 0 {
  1574. result["quicParams"] = quicParams
  1575. }
  1576. return result
  1577. }
  1578. func normalizedFinalMaskTCPMasks(value any) []any {
  1579. finalmask, _ := value.(map[string]any)
  1580. if finalmask == nil {
  1581. return nil
  1582. }
  1583. rawMasks, _ := finalmask["tcp"].([]any)
  1584. if len(rawMasks) == 0 {
  1585. return nil
  1586. }
  1587. normalized := make([]any, 0, len(rawMasks))
  1588. for _, rawMask := range rawMasks {
  1589. mask, _ := rawMask.(map[string]any)
  1590. if mask == nil {
  1591. continue
  1592. }
  1593. maskType, _ := mask["type"].(string)
  1594. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  1595. continue
  1596. }
  1597. normalizedMask := map[string]any{"type": maskType}
  1598. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1599. normalizedMask["settings"] = settings
  1600. }
  1601. normalized = append(normalized, normalizedMask)
  1602. }
  1603. if len(normalized) == 0 {
  1604. return nil
  1605. }
  1606. return normalized
  1607. }
  1608. func normalizedFinalMaskUDPMasks(value any) []any {
  1609. finalmask, _ := value.(map[string]any)
  1610. if finalmask == nil {
  1611. return nil
  1612. }
  1613. rawMasks, _ := finalmask["udp"].([]any)
  1614. if len(rawMasks) == 0 {
  1615. return nil
  1616. }
  1617. normalized := make([]any, 0, len(rawMasks))
  1618. for _, rawMask := range rawMasks {
  1619. mask, _ := rawMask.(map[string]any)
  1620. if mask == nil {
  1621. continue
  1622. }
  1623. maskType, _ := mask["type"].(string)
  1624. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  1625. continue
  1626. }
  1627. normalizedMask := map[string]any{"type": maskType}
  1628. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1629. normalizedMask["settings"] = settings
  1630. }
  1631. normalized = append(normalized, normalizedMask)
  1632. }
  1633. if len(normalized) == 0 {
  1634. return nil
  1635. }
  1636. return normalized
  1637. }
  1638. func hasFinalMaskContent(value any) bool {
  1639. switch v := value.(type) {
  1640. case nil:
  1641. return false
  1642. case string:
  1643. return len(v) > 0
  1644. case map[string]any:
  1645. for _, item := range v {
  1646. if hasFinalMaskContent(item) {
  1647. return true
  1648. }
  1649. }
  1650. return false
  1651. case []any:
  1652. return slices.ContainsFunc(v, hasFinalMaskContent)
  1653. default:
  1654. return true
  1655. }
  1656. }
  1657. func searchHost(headers any) string {
  1658. data, _ := headers.(map[string]any)
  1659. for k, v := range data {
  1660. if strings.EqualFold(k, "host") {
  1661. switch v.(type) {
  1662. case []any:
  1663. hosts, _ := v.([]any)
  1664. if len(hosts) > 0 {
  1665. return hosts[0].(string)
  1666. } else {
  1667. return ""
  1668. }
  1669. case any:
  1670. return v.(string)
  1671. }
  1672. }
  1673. }
  1674. return ""
  1675. }
  1676. // PageData is a view model for subpage.html
  1677. // PageData contains data for rendering the subscription information page.
  1678. type PageData struct {
  1679. Host string
  1680. BasePath string
  1681. SId string
  1682. Enabled bool
  1683. Download string
  1684. Upload string
  1685. Total string
  1686. Used string
  1687. Remained string
  1688. Expire int64
  1689. LastOnline int64
  1690. Datepicker string
  1691. DownloadByte int64
  1692. UploadByte int64
  1693. TotalByte int64
  1694. SubUrl string
  1695. SubJsonUrl string
  1696. SubClashUrl string
  1697. SubTitle string
  1698. SubSupportUrl string
  1699. Result []string
  1700. Emails []string
  1701. }
  1702. // ResolveRequest extracts scheme and host info from request/headers consistently.
  1703. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  1704. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  1705. // scheme
  1706. scheme = "http"
  1707. if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
  1708. scheme = "https"
  1709. }
  1710. // base host (no port)
  1711. if h, err := getHostFromXFH(c.GetHeader("X-Forwarded-Host")); err == nil && h != "" {
  1712. host = h
  1713. }
  1714. if host == "" {
  1715. host = c.GetHeader("X-Real-IP")
  1716. }
  1717. if host == "" {
  1718. var err error
  1719. host, _, err = net.SplitHostPort(c.Request.Host)
  1720. if err != nil {
  1721. host = c.Request.Host
  1722. }
  1723. }
  1724. // host:port for URLs
  1725. hostWithPort = c.GetHeader("X-Forwarded-Host")
  1726. if hostWithPort == "" {
  1727. hostWithPort = c.Request.Host
  1728. }
  1729. if hostWithPort == "" {
  1730. hostWithPort = host
  1731. }
  1732. // header display host
  1733. hostHeader = c.GetHeader("X-Forwarded-Host")
  1734. if hostHeader == "" {
  1735. hostHeader = c.GetHeader("X-Real-IP")
  1736. }
  1737. if hostHeader == "" {
  1738. hostHeader = host
  1739. }
  1740. return
  1741. }
  1742. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  1743. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  1744. func (s *SubService) BuildURLs(subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  1745. if subId == "" {
  1746. return "", "", ""
  1747. }
  1748. configuredSubURI, _ := s.settingService.GetSubURI()
  1749. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  1750. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  1751. // Same base as the panel's Client Information page; s.address is the
  1752. // subscriber's host already normalized away from any loopback/bind IP.
  1753. base := s.settingService.BuildSubURIBase(s.address)
  1754. subURL = s.buildSingleURL(configuredSubURI, base, subPath, subId)
  1755. subJsonURL = s.buildSingleURL(configuredSubJsonURI, base, subJsonPath, subId)
  1756. subClashURL = s.buildSingleURL(configuredSubClashURI, base, subClashPath, subId)
  1757. return subURL, subJsonURL, subClashURL
  1758. }
  1759. // buildSingleURL constructs a single URL using configured URI or base components
  1760. func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string {
  1761. if configuredURI != "" {
  1762. return s.joinPathWithID(configuredURI, subId)
  1763. }
  1764. return s.joinPathWithID(base+basePath, subId)
  1765. }
  1766. // joinPathWithID safely joins a base path with a subscription ID
  1767. func (s *SubService) joinPathWithID(basePath, subId string) string {
  1768. if strings.HasSuffix(basePath, "/") {
  1769. return basePath + subId
  1770. }
  1771. return basePath + "/" + subId
  1772. }
  1773. // BuildPageData parses header and prepares the template view model.
  1774. // BuildPageData constructs page data for rendering the subscription information page.
  1775. 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 {
  1776. download := common.FormatTraffic(traffic.Down)
  1777. upload := common.FormatTraffic(traffic.Up)
  1778. total := "∞"
  1779. used := common.FormatTraffic(traffic.Up + traffic.Down)
  1780. remained := ""
  1781. if traffic.Total > 0 {
  1782. total = common.FormatTraffic(traffic.Total)
  1783. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  1784. remained = common.FormatTraffic(left)
  1785. }
  1786. datepicker := s.datepicker
  1787. if datepicker == "" {
  1788. datepicker = "gregorian"
  1789. }
  1790. return PageData{
  1791. Host: hostHeader,
  1792. BasePath: basePath,
  1793. SId: subId,
  1794. Enabled: traffic.Enable,
  1795. Download: download,
  1796. Upload: upload,
  1797. Total: total,
  1798. Used: used,
  1799. Remained: remained,
  1800. Expire: traffic.ExpiryTime / 1000,
  1801. LastOnline: lastOnline,
  1802. Datepicker: datepicker,
  1803. DownloadByte: traffic.Down,
  1804. UploadByte: traffic.Up,
  1805. TotalByte: traffic.Total,
  1806. SubUrl: subURL,
  1807. SubJsonUrl: subJsonURL,
  1808. SubClashUrl: subClashURL,
  1809. SubTitle: subTitle,
  1810. SubSupportUrl: subSupportUrl,
  1811. Result: subs,
  1812. Emails: emails,
  1813. }
  1814. }
  1815. func getHostFromXFH(s string) (string, error) {
  1816. if strings.Contains(s, ":") {
  1817. realHost, _, err := net.SplitHostPort(s)
  1818. if err != nil {
  1819. return "", err
  1820. }
  1821. return realHost, nil
  1822. }
  1823. return s, nil
  1824. }