subService.go 57 KB

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