service.go 66 KB

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