1
0

subService.go 55 KB

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