subService.go 56 KB

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