subService.go 53 KB

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