subService.go 55 KB

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