subService.go 55 KB

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