service.go 68 KB

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