service.go 68 KB

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