service.go 65 KB

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