1
0

subService.go 54 KB

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