1
0

subService.go 58 KB

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