subService.go 53 KB

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