1
0

subService.go 53 KB

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